@codemem/server 0.43.1 → 0.44.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/helpers.d.ts +11 -0
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7152 -6184
- package/dist/index.js.map +1 -1
- package/dist/routes/raw-events.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +9 -5
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/target-validation.d.ts.map +1 -1
- package/dist/routes/team-setup-view.d.ts +212 -0
- package/dist/routes/team-setup-view.d.ts.map +1 -0
- package/dist/routes/team-setup.d.ts +30 -135
- package/dist/routes/team-setup.d.ts.map +1 -1
- package/package.json +11 -11
- package/static/app.js +59 -62
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +250 -18
package/static/app.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
(function(){var wp=Object.defineProperty,Lw=(e,t)=>{let n={};for(var r in e)wp(n,r,{get:e[r],enumerable:!0});return t||wp(n,Symbol.toStringTag,{value:"Module"}),n};function _e(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function Me(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function we(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function Sp(e,t,n,r,i){const a=new URLSearchParams;return a.set("project",e||""),typeof t=="number"&&a.set("limit",String(t)),typeof n=="number"&&a.set("offset",String(n)),r&&a.set("scope",r),i&&a.set("q",i),a.toString()}async function $w(){return Me("/api/observer-status")}async function Mw(){return Me("/api/config")}async function Ow(e){const t=await fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.text();let r=null;if(n)try{r=JSON.parse(n)}catch{}if(!t.ok){const i=_e(r)||n||"request failed";throw new Error(i)}return r}async function Za(){return Me("/api/coordinator/admin/status")}async function Cp(e){return Me(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function jw(e){const t=await fetch("/api/coordinator/admin/groups",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Fw(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Bw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Uw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Gw(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return Me(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function Hw(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function qw(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return Me(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function Kw(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:a}=await we(r);if(!r.ok)throw new Error(_e(a)||i||"request failed");return a}async function Vw(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await we(i);if(!i.ok)throw new Error(_e(s)||a||"request failed");return s}async function Ww(e){const t=new URLSearchParams;return e&&t.set("group_id",e),Me(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function Np(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),Me(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function zw(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Jw(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:a}=await we(r);if(!r.ok)throw new Error(_e(a)||i||"request failed");return a}async function Yw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Xw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Qw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Tp(e){const t=await fetch("/api/coordinator/admin/invites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Ip(e,t){return Me(`/api/observations?${Sp(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function Zw(e,t){const n=await fetch("/api/memories/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,visibility:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function eS(e,t){const n=await fetch("/api/memories/project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,project:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function tS(e){const t=await fetch("/api/memories/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function kp(e,t){return Me(`/api/summaries?${Sp(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function nS(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function rS(e=1200){const t=new AbortController,n=window.setTimeout(()=>t.abort(),e);try{const r=await fetch("/api/runtime",{cache:"no-store",signal:t.signal});if(!r.ok)throw new Error(`/api/runtime: ${r.status} ${r.statusText}`)}finally{window.clearTimeout(n)}}async function iS(){return Me("/api/runtime")}async function eo(){return(await Me("/api/projects")).projects||[]}async function aS(){return Me("/api/stats")}async function oS(e){return Me(`/api/usage?project=${encodeURIComponent(e)}`)}async function sS(e){return Me(`/api/session?project=${encodeURIComponent(e)}`)}async function cS(e){return Me(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function to(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),Me(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function yc(e,t){const n=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await we(n);if(!n.ok){const a=typeof i?.detail=="string"?i.detail.trim():"";throw new Error(a||_e(i)||r||"request failed")}return i}async function Ep(e,t={}){const n=await fetch("/api/sync/invites/inspect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function lS(){return Me("/api/sync/actors")}async function dS(e=!1){return Me(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function Pp(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Ap(e,t){const n=await fetch("/api/sync/peers/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_device_id:e,name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function uS(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let a={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(a=c)}catch{a={}}const s=typeof a.detail=="string"?a.detail:void 0;if(!r.ok)throw new Error(s||_e(a)||i||"request failed");return a}var xp=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},no=class extends Error{requiredGuardrails;requiredGuardrailTokens;guardrailWarnings;constructor(e){super("Sharing domain guardrail confirmation required"),this.name="SharingDomainGuardrailConfirmationError",this.requiredGuardrails=e.required_guardrails??[],this.requiredGuardrailTokens=e.required_guardrail_tokens??[],this.guardrailWarnings=e.guardrail_warnings??[]}},Rp=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},bc=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},ro=1,Dp=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_failed"]),pS=new Set(["needs_setup","in_progress","stale","ready"]),Lp=new Set(["needs_setup","in_progress","stale","completed"]);function tt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rn(e){return typeof e=="string"||e===null}function an(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ut(e,t){return Array.isArray(e)&&e.every(t)}function $p(e){return tt(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&pS.has(e.status)&&an(e.deviceCount)&&an(e.projectCount)&&an(e.unresolvedDeviceCount)&&an(e.unresolvedProjectCount):!1}function mS(e){return tt(e)&&e.version===ro&&Ut(e.candidates,$p)}function fS(e){return tt(e)?e.kind==="absent"||e.kind==="existing"&&an(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function hS(e){return tt(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&rn(e.existingIdentityRef)&&rn(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&rn(e.targetIdentityRef)&&fS(e.expectation):!1}function gS(e){return tt(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&rn(e.canonicalProjectRef)&&rn(e.resolvedProjectRef)&&Ut(e.mappingChoices,t=>tt(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string"):!1}function vS(e){if(!tt(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return Ut(e.teamChanges,n=>tt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&t(n.change)&&[null,"person_all_devices","reviewed_allowlist"].includes(n.fromDeviceEligibilityMode)&&n.toDeviceEligibilityMode==="reviewed_allowlist")&&Ut(e.membershipChanges,n=>tt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&Ut(e.projectChanges,n=>tt(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&rn(n.fromResolvedProjectRef)&&rn(n.fromResolvedProjectDisplayName)&&rn(n.toResolvedProjectRef)&&rn(n.toResolvedProjectDisplayName)&&t(n.change))&&Ut(e.recipientChanges,n=>tt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&n.recipientKind==="team"&&typeof n.recipientRef=="string"&&typeof n.recipientDisplayName=="string"&&t(n.change))&&Ut(e.deviceAccessChanges,n=>tt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&typeof n.deviceRef=="string"&&typeof n.deviceDisplayName=="string"&&typeof n.change=="string"&&["add","remove"].includes(n.change))}function yS(e){return!tt(e)||!(e.version===ro&&$p(e.candidate)&&typeof e.attemptId=="string"&&typeof e.draftState=="string"&&Lp.has(e.draftState)&&an(e.unresolvedDeviceCount)&&an(e.unresolvedProjectCount)&&Ut(e.devices,hS)&&Ut(e.projects,gS)&&Ut(e.identityChoices,t=>tt(t)&&typeof t.identityRef=="string"&&typeof t.displayName=="string"))?!1:e.canFinish===!0?e.conflictState===null&&typeof e.finishDigest=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.viewerAccessDeltaDigest=="string"&&vS(e.accessDelta):e.canFinish===!1&&(e.conflictState===null||typeof e.conflictState=="string"&&Dp.has(e.conflictState))}function xi(e){return tt(e)&&e.version===ro&&typeof e.candidateRef=="string"&&typeof e.attemptId=="string"&&typeof e.draftState=="string"&&Lp.has(e.draftState)&&typeof e.canFinish=="boolean"&&an(e.unresolvedDeviceCount)&&an(e.unresolvedProjectCount)}function bS(e){return tt(e)&&e.version===ro&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var Gt=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="LegacyTeamSetupApiError"}};function Sn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function Cn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new Gt(0,"team_setup_failed")}let i;try{const a=await r.text();if(!a)throw new Error("empty Team setup response");i=JSON.parse(a)}catch{throw new Gt(r.status,"team_setup_failed")}if(!r.ok){const a=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=Dp.has(a)?a:"team_setup_failed";throw new Gt(r.status,s)}if(!t(i))throw new Gt(r.status,"team_setup_failed");return i}function xr(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function Mp(){return Cn(Sn(),mS)}function _S(e){return Cn(Sn(e),yS)}function wS(e,t,n){return Cn(`${Sn(e)}/devices/${encodeURIComponent(t)}/assignment`,xi,xr("PUT",n))}function SS(e,t,n){return Cn(`${Sn(e)}/devices/${encodeURIComponent(t)}/decision`,xi,xr("PUT",n))}function CS(e,t,n){return Cn(`${Sn(e)}/devices/${encodeURIComponent(t)}/decision`,xi,xr("DELETE",n))}function NS(e,t,n){return Cn(`${Sn(e)}/projects/${encodeURIComponent(t)}/mapping`,xi,xr("PUT",n))}function TS(e){return Cn(`${Sn(e)}/refresh`,xi,xr("POST",{}))}function IS(e,t){return Cn(`${Sn(e)}/finish`,bS,xr("POST",t))}var _c=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function wc(){return Me("/api/sync/recipient-policy/v1/intent")}function Sc(){return Me("/api/sync/recipient-policy/v1/device-inventory")}async function Op(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok){const a=i?.errorCode||i?.error||_e(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new bc(n.status,a,s)}return i}function jp(e){return Op("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function Fp(e){return Op("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function kS(){return Me("/api/sync/recipient-policy/v1/reconciliation-status")}async function Bp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new _c(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const a=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(a||_e(i)||r||"request failed")}return i}function ES(e){return Bp("/api/sync/recipient-policy/v1/edges/preview",e)}function PS(e){return Bp("/api/sync/recipient-policy/v1/edges/commit",e)}async function Up(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}function AS(e){return Up("/api/sync/recipient-policy/v1/invites/preview",e)}function xS(e){return Up("/api/sync/recipient-policy/v1/invites",e)}async function RS(){const e=await Me("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function DS(){return Me("/api/sync/sharing-domains/settings")}async function io(e={}){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i==null||i===""||t.set(r,String(i));const n=t.toString();return Me(`/api/sync/projects${n?`?${n}`:""}`)}async function Gp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}function LS(e){return Gp("/api/sync/project-invites/preview",e)}function $S(e){return Gp("/api/sync/project-invites",e)}function Hp(){return Me("/api/sync/share-operations")}function MS(e){return Me(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function OS(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function jS(e){const t=await fetch("/api/sync/sharing-domains/project-mappings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new no(r):new Error(_e(r)||n||"request failed");const i=r?.mapping;if(!i)throw new Error("response missing mapping");return{...i,guardrail_warnings:r.guardrail_warnings??i.guardrail_warnings}}async function FS(e){const t=await fetch("/api/sync/sharing-domains/project-mappings/bulk",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new no(r):new Error(_e(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function BS(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return!!r?.deleted}async function US(e){const t=await fetch("/api/sync/projects/reassign-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function GS(e){const t=await fetch("/api/sync/projects/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new xp(r.preview):new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function HS(e){const t=await fetch("/api/sync/legacy-shared-review/reassign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new Rp(r.preview):new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function qS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function KS(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");const a=i?.preferences;if(!a)throw new Error("response missing preferences");return a}async function VS(e){const t=await fetch("/api/sync/actors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function WS(e,t){const n=await fetch("/api/sync/actors/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e,display_name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function qp(e,t){const n=await fetch("/api/sync/actors/merge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primary_actor_id:e,secondary_actor_id:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function zS(e){const t=await fetch("/api/sync/actors/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function JS(e){const t=await fetch("/api/sync/legacy-devices/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({origin_device_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Cc(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await we(i);if(!i.ok)throw new Error(_e(s)||a||"request failed");if(!a)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(a||"invalid sync response");return s}async function YS(){return Me("/api/update-status")}function XS(e){return{current_version:"unknown",latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function ao(e){return e!==null&&typeof e=="object"?e:null}function Kp(e){const t=ao(e),n=ao(t?.status),r=ao(ao(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var Ri,fe,Vp,Wp,Nn,zp,Jp,Yp,Nc,oo,Di,Xp,Tc,Ic,kc,Qp,so={},co=[],QS=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Li=Array.isArray;function Ht(e,t){for(var n in t)e[n]=t[n];return e}function Ec(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function y(e,t,n){var r,i,a,s={};for(a in t)a=="key"?r=t[a]:a=="ref"?i=t[a]:s[a]=t[a];if(arguments.length>2&&(s.children=arguments.length>3?Ri.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(a in e.defaultProps)s[a]===void 0&&(s[a]=e.defaultProps[a]);return $i(e,s,r,i,null)}function $i(e,t,n,r,i){var a={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Vp,__i:-1,__u:0};return i==null&&fe.vnode!=null&&fe.vnode(a),a}function Zp(){return{current:null}}function Z(e){return e.children}function Tt(e,t){this.props=e,this.context=t}function Rr(e,t){if(t==null)return e.__?Rr(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?Rr(e):null}function ZS(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],a=Ht({},t);a.__v=t.__v+1,fe.vnode&&fe.vnode(a),Ac(e.__P,a,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Rr(t),!!(32&t.__u),i),a.__v=t.__v,a.__.__k[a.__i]=a,am(r,a,i),t.__e=t.__=null,a.__e!=n&&em(a)}}function em(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),em(e)}function Pc(e){(!e.__d&&(e.__d=!0)&&Nn.push(e)&&!lo.__r++||zp!=fe.debounceRendering)&&((zp=fe.debounceRendering)||Jp)(lo)}function lo(){try{for(var e,t=1;Nn.length;)Nn.length>t&&Nn.sort(Yp),e=Nn.shift(),t=Nn.length,ZS(e)}finally{Nn.length=lo.__r=0}}function tm(e,t,n,r,i,a,s,c,l,d,u){var p,m,f,g,h,v,w,b=r&&r.__k||co,S=t.length;for(l=eC(n,t,b,l,S),p=0;p<S;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&b[f.__i]||so,f.__i=p,v=Ac(e,f,m,i,a,s,c,l,d,u),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&Rc(m.ref,null,f),u.push(f.ref,f.__c||g,f)),h==null&&g!=null&&(h=g),(w=!!(4&f.__u))||m.__k===f.__k?(l=nm(f,l,e,w),w&&m.__e&&(m.__e=null)):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=h,l}function eC(e,t,n,r,i){var a,s,c,l,d,u=n.length,p=u,m=0;for(e.__k=new Array(i),a=0;a<i;a++)(s=t[a])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[a]=$i(null,s,null,null,null):Li(s)?s=e.__k[a]=$i(Z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[a]=$i(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[a]=s,l=a+m,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=tC(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?m--:d==l+1?m++:(d>l?m--:m++,s.__u|=4))):e.__k[a]=null;if(p)for(a=0;a<u;a++)(c=n[a])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=Rr(c)),sm(c,c));return r}function nm(e,t,n,r){var i,a;if(typeof e.type=="function"){for(i=e.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=e,t=nm(i[a],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Rr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function on(e,t){return t=t||[],e==null||typeof e=="boolean"||(Li(e)?e.some(function(n){on(n,t)}):t.push(e)),t}function tC(e,t,n,r){var i,a,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,a=n+1;i>=0||a<t.length;)if((d=t[s=i>=0?i--:a++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function rm(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||QS.test(t)?n:n+"px"}function uo(e,t,n,r,i){var a,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||rm(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||rm(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")a=t!=(t=t.replace(Xp,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+a]=n,n?r?n[Di]=r[Di]:(n[Di]=Tc,e.addEventListener(t,a?kc:Ic,a)):e.removeEventListener(t,a?kc:Ic,a);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function im(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[oo]==null)t[oo]=Tc++;else if(t[oo]<n[Di])return;return n(fe.event?fe.event(t):t)}}}function Ac(e,t,n,r,i,a,s,c,l,d){var u,p,m,f,g,h,v,w,b,S,C,T,P,k,M,U=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),a=[c=t.__e=n.__e]),(u=fe.__b)&&u(t);e:if(typeof U=="function")try{if(w=t.props,b=U.prototype&&U.prototype.render,S=(u=U.contextType)&&r[u.__c],C=u?S?S.props.value:u.__:r,n.__c?v=(p=t.__c=n.__c).__=p.__E:(b?t.__c=p=new U(w,C):(t.__c=p=new Tt(w,C),p.constructor=U,p.render=rC),S&&S.sub(p),p.state||(p.state={}),p.__n=r,m=p.__d=!0,p.__h=[],p._sb=[]),b&&p.__s==null&&(p.__s=p.state),b&&U.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ht({},p.__s)),Ht(p.__s,U.getDerivedStateFromProps(w,p.__s))),f=p.props,g=p.state,p.__v=t,m)b&&U.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),b&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(b&&U.getDerivedStateFromProps==null&&w!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(w,C),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(w,p.__s,C)===!1){t.__v!=n.__v&&(p.props=w,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(E){E&&(E.__=t)}),co.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(w,p.__s,C),b&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,h)})}if(p.context=C,p.props=w,p.__P=e,p.__e=!1,T=fe.__r,P=0,b)p.state=p.__s,p.__d=!1,T&&T(t),u=p.render(p.props,p.state,p.context),co.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,T&&T(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++P<25);p.state=p.__s,p.getChildContext!=null&&(r=Ht(Ht({},r),p.getChildContext())),b&&!m&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,g)),k=u!=null&&u.type===Z&&u.key==null?om(u.props.children):u,c=tm(e,Li(k)?k:[k],t,n,r,i,a,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),v&&(p.__E=p.__=null)}catch(E){if(t.__v=null,l||a!=null)if(E.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;a[a.indexOf(c)]=null,t.__e=c}else{for(M=a.length;M--;)Ec(a[M]);xc(t)}else t.__e=n.__e,t.__k=n.__k,E.then||xc(t);fe.__e(E,t,n)}else a==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=nC(n.__e,t,n,r,i,a,s,l,d);return(u=fe.diffed)&&u(t),128&t.__u?void 0:c}function xc(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(xc))}function am(e,t,n){for(var r=0;r<n.length;r++)Rc(n[r],n[++r],n[++r]);fe.__c&&fe.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(a){a.call(i)})}catch(a){fe.__e(a,i.__v)}})}function om(e){return typeof e!="object"||e==null||e.__b>0?e:Li(e)?e.map(om):e.constructor!==void 0?null:Ht({},e)}function nC(e,t,n,r,i,a,s,c,l){var d,u,p,m,f,g,h,v=n.props||so,w=t.props,b=t.type;if(b=="svg"?i="http://www.w3.org/2000/svg":b=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),a!=null){for(d=0;d<a.length;d++)if((f=a[d])&&"setAttribute"in f==!!b&&(b?f.localName==b:f.nodeType==3)){e=f,a[d]=null;break}}if(e==null){if(b==null)return document.createTextNode(w);e=document.createElementNS(i,b,w.is&&w),c&&(fe.__m&&fe.__m(t,a),c=!1),a=null}if(b==null)v===w||c&&e.data==w||(e.data=w);else{if(a=b=="textarea"&&w.defaultValue!=null?null:a&&Ri.call(e.childNodes),!c&&a!=null)for(v={},d=0;d<e.attributes.length;d++)v[(f=e.attributes[d]).name]=f.value;for(d in v)f=v[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in w||d=="value"&&"defaultValue"in w||d=="checked"&&"defaultChecked"in w||uo(e,d,null,f,i);for(d in w)f=w[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?g=f:d=="checked"?h=f:c&&typeof f!="function"||v[d]===f||uo(e,d,f,v[d],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),tm(t.type=="template"?e.content:e,Li(m)?m:[m],t,n,r,b=="foreignObject"?"http://www.w3.org/1999/xhtml":i,a,s,a?a[0]:n.__k&&Rr(n,0),c,l),a!=null)for(d=a.length;d--;)Ec(a[d]);c&&b!="textarea"||(d="value",b=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||b=="progress"&&!g||b=="option"&&g!=v[d])&&uo(e,d,g,v[d],i),d="checked",h!=null&&h!=e[d]&&uo(e,d,h,v[d],i))}return e}function Rc(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(i){fe.__e(i,n)}}function sm(e,t,n){var r,i;if(fe.unmount&&fe.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Rc(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(a){fe.__e(a,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&sm(r[i],t,n||typeof e.type!="function");n||Ec(e.__e),e.__c=e.__=e.__e=void 0}function rC(e,t,n){return this.constructor(e,n)}function Ge(e,t,n){var r,i,a,s;t==document&&(t=document.documentElement),fe.__&&fe.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,a=[],s=[],Ac(t,e=(!r&&n||t).__k=y(Z,null,[e]),i||so,so,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?Ri.call(t.childNodes):null,a,!r&&n?n:i?i.__e:t.firstChild,r,s),am(a,e,s)}function cm(e,t){Ge(e,t,cm)}function iC(e,t,n){var r,i,a,s,c=Ht({},e.props);for(a in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)a=="key"?r=t[a]:a=="ref"?i=t[a]:c[a]=t[a]===void 0&&s!=null?s[a]:t[a];return arguments.length>2&&(c.children=arguments.length>3?Ri.call(arguments,2):n),$i(e.type,c,r||e.key,i||e.ref,null)}function Jn(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(a){this.props.value!=a.value&&r.forEach(function(s){s.__e=!0,Pc(s)})},this.sub=function(a){r.add(a);var s=a.componentWillUnmount;a.componentWillUnmount=function(){r&&r.delete(a),s&&s.call(a)}}),n.children}return t.__c="__cC"+Qp++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Ri=co.slice,fe={__e:function(e,t,n,r){for(var i,a,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((a=i.constructor)&&a.getDerivedStateFromError!=null&&(i.setState(a.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Vp=0,Wp=function(e){return e!=null&&e.constructor===void 0},Tt.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ht({},this.state);typeof e=="function"&&(e=e(Ht({},n),this.props)),e&&Ht(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Pc(this))},Tt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Pc(this))},Tt.prototype.render=Z,Nn=[],Jp=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Yp=function(e,t){return e.__v.__b-t.__v.__b},lo.__r=0,Nc=Math.random().toString(8),oo="__d"+Nc,Di="__a"+Nc,Xp=/(PointerCapture)$|Capture$/i,Tc=0,Ic=im(!1),kc=im(!0),Qp=0;var sn,je,Dc,lm,Dr=0,dm=[],He=fe,um=He.__b,pm=He.__r,mm=He.diffed,fm=He.__c,hm=He.unmount,gm=He.__;function Yn(e,t){He.__h&&He.__h(je,e,Dr||t),Dr=0;var n=je.__H||(je.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function x(e){return Dr=1,Mi(ym,e)}function Mi(e,t,n){var r=Yn(sn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):ym(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=je,!je.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!a||a.call(this,c,l,d);var p=r.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),a&&a.call(this,c,l,d)||p};je.__f=!0;var a=je.shouldComponentUpdate,s=je.componentWillUpdate;je.componentWillUpdate=function(c,l,d){if(this.__e){var u=a;a=void 0,i(c,l,d),a=u}s&&s.call(this,c,l,d)},je.shouldComponentUpdate=i}return r.__N||r.__}function J(e,t){var n=Yn(sn++,3);!He.__s&&Mc(n.__H,t)&&(n.__=e,n.u=t,je.__H.__h.push(n))}function bt(e,t){var n=Yn(sn++,4);!He.__s&&Mc(n.__H,t)&&(n.__=e,n.u=t,je.__h.push(n))}function B(e){return Dr=5,Re(function(){return{current:e}},[])}function po(e,t,n){Dr=6,bt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function Re(e,t){var n=Yn(sn++,7);return Mc(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function se(e,t){return Dr=8,Re(function(){return e},t)}function Tn(e){var t=je.context[e.__c],n=Yn(sn++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(je)),t.props.value):e.__}function Lc(e,t){He.useDebugValue&&He.useDebugValue(t?t(e):e)}function aC(e){var t=Yn(sn++,10),n=x();return t.__=e,je.componentDidCatch||(je.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Lr(){var e=Yn(sn++,11);if(!e.__){for(var t=je.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function oC(){for(var e;e=dm.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(mo),t.__h.some($c),t.__h=[]}catch(n){t.__h=[],He.__e(n,e.__v)}}}He.__b=function(e){je=null,um&&um(e)},He.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),gm&&gm(e,t)},He.__r=function(e){pm&&pm(e),sn=0;var t=(je=e.__c).__H;t&&(Dc===je?(t.__h=[],je.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(mo),t.__h.some($c),t.__h=[],sn=0)),Dc=je},He.diffed=function(e){mm&&mm(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(dm.push(t)!==1&&lm===He.requestAnimationFrame||((lm=He.requestAnimationFrame)||sC)(oC)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Dc=je=null},He.__c=function(e,t){t.some(function(n){try{n.__h.some(mo),n.__h=n.__h.filter(function(r){return!r.__||$c(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],He.__e(r,n.__v)}}),fm&&fm(e,t)},He.unmount=function(e){hm&&hm(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{mo(r)}catch(i){t=i}}),n.__H=void 0,t&&He.__e(t,n.__v))};var vm=typeof requestAnimationFrame=="function";function sC(e){var t,n=function(){clearTimeout(r),vm&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);vm&&(t=requestAnimationFrame(n))}function mo(e){var t=je,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),je=t}function $c(e){var t=je;e.__c=e.__(),je=t}function Mc(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function ym(e,t){return typeof t=="function"?t(e):t}var Y1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,cC=0,X1=Array.isArray;function o(e,t,n,r,i,a){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cC,__i:-1,__u:0,__source:i,__self:a};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return fe.vnode&&fe.vnode(d),d}function Oi({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:a="Close"}){return o("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[o("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),o("span",{className:"modal-close-button-label",children:a})]})}var bm=Lw({Children:()=>qt,Component:()=>Tt,Fragment:()=>Z,PureComponent:()=>fo,StrictMode:()=>Z,Suspense:()=>ji,SuspenseList:()=>$r,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Om,cloneElement:()=>Mr,createContext:()=>Jn,createElement:()=>y,createFactory:()=>jm,createPortal:()=>cn,createRef:()=>Zp,default:()=>dn,findDOMNode:()=>Gm,flushSync:()=>ho,forwardRef:()=>V,hydrate:()=>Rm,isElement:()=>qm,isFragment:()=>Fm,isMemo:()=>Bm,isValidElement:()=>ln,lazy:()=>Em,memo:()=>wm,render:()=>xm,startTransition:()=>Bc,unmountComponentAtNode:()=>Um,unstable_batchedUpdates:()=>Hm,useCallback:()=>se,useContext:()=>Tn,useDebugValue:()=>Lc,useDeferredValue:()=>Uc,useEffect:()=>J,useErrorBoundary:()=>aC,useId:()=>Lr,useImperativeHandle:()=>po,useInsertionEffect:()=>Hc,useLayoutEffect:()=>bt,useMemo:()=>Re,useReducer:()=>Mi,useRef:()=>B,useState:()=>x,useSyncExternalStore:()=>jc,useTransition:()=>Gc,version:()=>bC});function _m(e,t){for(var n in t)e[n]=t[n];return e}function Oc(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function jc(e,t){var n=t(),r=x({t:{__:n,u:t}}),i=r[0].t,a=r[1];return bt(function(){i.__=n,i.u=t,Fc(i)&&a({t:i})},[e,n,t]),J(function(){return Fc(i)&&a({t:i}),e(function(){Fc(i)&&a({t:i})})},[e]),n}function Fc(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function Bc(e){e()}function Uc(e){return e}function Gc(){return[!1,Bc]}var Hc=bt;function fo(e,t){this.props=e,this.context=t}function wm(e,t){function n(i){var a=this.props.ref;return a!=i.ref&&a&&(typeof a=="function"?a(null):a.current=null),t?!t(this.props,i)||a!=i.ref:Oc(this.props,i)}function r(i){return this.shouldComponentUpdate=n,y(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(fo.prototype=new Tt).isPureReactComponent=!0,fo.prototype.shouldComponentUpdate=function(e,t){return Oc(this.props,e)||Oc(this.state,t)};var Sm=fe.__b;fe.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Sm&&Sm(e)};var lC=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function V(e){function t(n){var r=_m({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=lC,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Cm=function(e,t){return e==null?null:on(on(e).map(t))},qt={map:Cm,forEach:Cm,count:function(e){return e?on(e).length:0},only:function(e){var t=on(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:on},dC=fe.__e;fe.__e=function(e,t,n,r){if(e.then){for(var i,a=t;a=a.__;)if((i=a.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k),i.__c(e,t)}dC(e,t,n,r)};var Nm=fe.unmount;function Tm(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=_m({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Tm(r,t,n)})),e}function Im(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Im(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function ji(){this.__u=0,this.o=null,this.__b=null}function km(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Em(e){var t,n,r,i=null;function a(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?y(i,s):null}return a.displayName="Lazy",a.__f=!0,a}function $r(){this.i=null,this.l=null}fe.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Nm&&Nm(e)},(ji.prototype=new Tt).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=km(r.__v),a=!1,s=function(){a||r.__z||(a=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Im(d,d.__c.__P,d.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.__P=c,u.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},ji.prototype.componentWillUnmount=function(){this.o=[]},ji.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Tm(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&y(Z,null,e.fallback);return i&&(i.__u&=-33),[y(Z,null,t.__a?null:e.children),i]};var Pm=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function uC(e){return this.getChildContext=function(){return e.context},e.children}function pC(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ge(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,a){this.childNodes.push(i),t.h.insertBefore(i,a)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ge(y(uC,{context:t.context},e.__v),t.v)}function cn(e,t){var n=y(pC,{__v:e,h:t});return n.containerInfo=t,n}($r.prototype=new Tt).__a=function(e){var t=this,n=km(t.__v),r=t.l.get(e);return r[0]++,function(i){var a=function(){t.props.revealOrder?(r.push(i),Pm(t,e,r)):i()};n?n(a):a()}},$r.prototype.render=function(e){this.i=null,this.l=new Map;var t=on(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},$r.prototype.componentDidUpdate=$r.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Pm(e,n,t)})};var Am=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,mC=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,fC=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,hC=/[A-Z0-9]/g,gC=typeof document<"u",vC=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xm(e,t,n){return t.__k??(t.textContent=""),Ge(e,t),typeof n=="function"&&n(),e?e.__c:null}function Rm(e,t,n){return cm(e,t),typeof n=="function"&&n(),e?e.__c:null}Tt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Tt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Dm=fe.event;fe.event=function(e){return Dm&&(e=Dm(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var qc,yC={configurable:!0,get:function(){return this.class}},Lm=fe.vnode;fe.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},a=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||gC&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&c===!0?c="":l==="translate"&&c==="no"?c=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||vC(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":fC.test(s)&&(s=l):l=s="oninput":a&&mC.test(s)?s=s.replace(hC,"-$&").toLowerCase():c===null&&(c=void 0),l==="oninput"&&i[s=l]&&(s="oninputCapture"),i[s]=c}}r=="select"&&(i.multiple&&Array.isArray(i.value)&&(i.value=on(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=on(n.children).forEach(function(d){d.props.selected=i.multiple?i.defaultValue.indexOf(d.props.value)!=-1:i.defaultValue==d.props.value}))),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",yC)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Am,Lm&&Lm(e)};var $m=fe.__r;fe.__r=function(e){$m&&$m(e),qc=e.__c};var Mm=fe.diffed;fe.diffed=function(e){Mm&&Mm(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),qc=null};var Om={ReactCurrentDispatcher:{current:{readContext:function(e){return qc.__n[e.__c].props.value},useCallback:se,useContext:Tn,useDebugValue:Lc,useDeferredValue:Uc,useEffect:J,useId:Lr,useImperativeHandle:po,useInsertionEffect:Hc,useLayoutEffect:bt,useMemo:Re,useReducer:Mi,useRef:B,useState:x,useSyncExternalStore:jc,useTransition:Gc}}},bC="18.3.1";function jm(e){return y.bind(null,e)}function ln(e){return!!e&&e.$$typeof===Am}function Fm(e){return ln(e)&&e.type===Z}function Bm(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Mr(e){return ln(e)?iC.apply(null,arguments):e}function Um(e){return!!e.__k&&(Ge(null,e),!0)}function Gm(e){return e&&(e.base||e.nodeType===1&&e)||null}var Hm=function(e,t){return e(t)},ho=function(e,t){var n=fe.debounceRendering;fe.debounceRendering=function(i){return i()};var r=e(t);return fe.debounceRendering=n,r},qm=ln,dn={useState:x,useId:Lr,useReducer:Mi,useEffect:J,useLayoutEffect:bt,useInsertionEffect:Hc,useTransition:Gc,useDeferredValue:Uc,useSyncExternalStore:jc,startTransition:Bc,useRef:B,useImperativeHandle:po,useMemo:Re,useCallback:se,useContext:Tn,useDebugValue:Lc,version:"18.3.1",Children:qt,render:xm,hydrate:Rm,unmountComponentAtNode:Um,createPortal:cn,createElement:y,createContext:Jn,createFactory:jm,cloneElement:Mr,createRef:Zp,Fragment:Z,isValidElement:ln,isElement:qm,isFragment:Fm,isMemo:Bm,findDOMNode:Gm,Component:Tt,PureComponent:fo,memo:wm,forwardRef:V,flushSync:ho,unstable_batchedUpdates:Hm,StrictMode:Z,Suspense:ji,SuspenseList:$r,lazy:Em,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Om},Q1=!!(typeof window<"u"&&window.document&&window.document.createElement);function Q(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function Km(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function go(...e){return t=>{let n=!1;const r=e.map(i=>{const a=Km(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():Km(e[i],null)}}}}function Se(...e){return se(go(...e),e)}function _C(e,t){const n=Jn(t),r=a=>{const{children:s,...c}=a,l=Re(()=>c,Object.values(c));return o(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(a){const s=Tn(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[r,i]}function st(e,t=[]){let n=[];function r(a,s){const c=Jn(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...g}=p,h=m?.[e]?.[l]||c,v=Re(()=>g,Object.values(g));return o(h.Provider,{value:v,children:f})};d.displayName=a+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,g=Tn(f);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${a}\``)}return[d,u]}const i=()=>{const a=n.map(s=>Jn(s));return function(c){const l=c?.[e]||a;return Re(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,wC(i,...t)]}function wC(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(a){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return Re(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var We=globalThis?.document?bt:()=>{},SC=bm[" useId ".trim().toString()]||(()=>{}),CC=0;function ct(e){const[t,n]=x(SC());return We(()=>{e||n(r=>r??String(CC++))},[e]),e||(t?`radix-${t}`:"")}var NC=bm[" useInsertionEffect ".trim().toString()]||We;function It({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,a,s]=TC({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=B(e!==void 0);J(()=>{const u=d.current;u!==c&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,r])}return[l,se(d=>{if(c){const u=IC(d)?d(e):d;u!==e&&s.current?.(u)}else a(d)},[c,e,a,s])]}function TC({defaultProp:e,onChange:t}){const[n,r]=x(e),i=B(n),a=B(t);return NC(()=>{a.current=t},[t]),J(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}function IC(e){return typeof e=="function"}function Xn(e){const t=kC(e),n=V((r,i)=>{const{children:a,...s}=r,c=qt.toArray(a),l=c.find(PC);if(l){const d=l.props.children,u=c.map(p=>p===l?qt.count(d)>1?qt.only(null):ln(d)?d.props.children:null:p);return o(t,{...s,ref:i,children:ln(d)?Mr(d,void 0,u):null})}return o(t,{...s,ref:i,children:a})});return n.displayName=`${e}.Slot`,n}function kC(e){const t=V((n,r)=>{const{children:i,...a}=n;if(ln(i)){const s=xC(i),c=AC(a,i.props);return i.type!==Z&&(c.ref=r?go(r,s):s),Mr(i,c)}return qt.count(i)>1?qt.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Vm=Symbol("radix.slottable");function EC(e){const t=({children:n})=>o(Z,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Vm,t}function PC(e){return ln(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Vm}function AC(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...s)=>{const c=a(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}function xC(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var pe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=Xn(`Primitive.${t}`),r=V((i,a)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o(l,{...c,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Kc(e,t){e&&ho(()=>e.dispatchEvent(t))}function lt(e){const t=B(e);return J(()=>{t.current=e}),Re(()=>(...n)=>t.current?.(...n),[])}function RC(e,t=globalThis?.document){const n=lt(e);J(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var DC="DismissableLayer",Vc="dismissableLayer.update",LC="dismissableLayer.pointerDownOutside",$C="dismissableLayer.focusOutside",Wm,zm=Jn({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Qn=V((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:s,onDismiss:c,...l}=e,d=Tn(zm),[u,p]=x(null),m=u?.ownerDocument??globalThis?.document,[,f]=x({}),g=Se(t,k=>p(k)),h=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),w=h.indexOf(v),b=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,C=b>=w,T=OC(k=>{const M=k.target,U=[...d.branches].some(E=>E.contains(M));!C||U||(i?.(k),s?.(k),k.defaultPrevented||c?.())},m),P=jC(k=>{const M=k.target;[...d.branches].some(U=>U.contains(M))||(a?.(k),s?.(k),k.defaultPrevented||c?.())},m);return RC(k=>{b===d.layers.size-1&&(r?.(k),!k.defaultPrevented&&c&&(k.preventDefault(),c()))},m),J(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Wm=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Ym(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Wm)}},[u,m,n,d]),J(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Ym())},[u,d]),J(()=>{const k=()=>f({});return document.addEventListener(Vc,k),()=>document.removeEventListener(Vc,k)},[]),o(pe.div,{...l,ref:g,style:{pointerEvents:S?C?"auto":"none":void 0,...e.style},onFocusCapture:Q(e.onFocusCapture,P.onFocusCapture),onBlurCapture:Q(e.onBlurCapture,P.onBlurCapture),onPointerDownCapture:Q(e.onPointerDownCapture,T.onPointerDownCapture)})});Qn.displayName=DC;var MC="DismissableLayerBranch",Jm=V((e,t)=>{const n=Tn(zm),r=B(null),i=Se(t,r);return J(()=>{const a=r.current;if(a)return n.branches.add(a),()=>{n.branches.delete(a)}},[n.branches]),o(pe.div,{...e,ref:i})});Jm.displayName=MC;function OC(e,t=globalThis?.document){const n=lt(e),r=B(!1),i=B(()=>{});return J(()=>{const a=c=>{if(c.target&&!r.current){let l=function(){Xm(LC,n,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",a),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function jC(e,t=globalThis?.document){const n=lt(e),r=B(!1);return J(()=>{const i=a=>{a.target&&!r.current&&Xm($C,n,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Ym(){const e=new CustomEvent(Vc);document.dispatchEvent(e)}function Xm(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Kc(i,a):i.dispatchEvent(a)}var FC=Qn,BC=Jm,Wc="focusScope.autoFocusOnMount",zc="focusScope.autoFocusOnUnmount",Qm={bubbles:!1,cancelable:!0},UC="FocusScope",Fi=V((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...s}=e,[c,l]=x(null),d=lt(i),u=lt(a),p=B(null),m=Se(t,h=>l(h)),f=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;J(()=>{if(r){let h=function(S){if(f.paused||!c)return;const C=S.target;c.contains(C)?p.current=C:In(p.current,{select:!0})},v=function(S){if(f.paused||!c)return;const C=S.relatedTarget;C!==null&&(c.contains(C)||In(p.current,{select:!0}))},w=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&In(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",v);const b=new MutationObserver(w);return c&&b.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",v),b.disconnect()}}},[r,c,f.paused]),J(()=>{if(c){tf.add(f);const h=document.activeElement;if(!c.contains(h)){const v=new CustomEvent(Wc,Qm);c.addEventListener(Wc,d),c.dispatchEvent(v),v.defaultPrevented||(GC(WC(Zm(c)),{select:!0}),document.activeElement===h&&In(c))}return()=>{c.removeEventListener(Wc,d),setTimeout(()=>{const v=new CustomEvent(zc,Qm);c.addEventListener(zc,u),c.dispatchEvent(v),v.defaultPrevented||In(h??document.body,{select:!0}),c.removeEventListener(zc,u),tf.remove(f)},0)}}},[c,d,u,f]);const g=se(h=>{if(!n&&!r||f.paused)return;const v=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(v&&w){const b=h.currentTarget,[S,C]=HC(b);S&&C?!h.shiftKey&&w===C?(h.preventDefault(),n&&In(S,{select:!0})):h.shiftKey&&w===S&&(h.preventDefault(),n&&In(C,{select:!0})):w===b&&h.preventDefault()}},[n,r,f.paused]);return o(pe.div,{tabIndex:-1,...s,ref:m,onKeyDown:g})});Fi.displayName=UC;function GC(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(In(r,{select:t}),document.activeElement!==n)return}function HC(e){const t=Zm(e);return[ef(t,e),ef(t.reverse(),e)]}function Zm(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ef(e,t){for(const n of e)if(!qC(n,{upTo:t}))return n}function qC(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function KC(e){return e instanceof HTMLInputElement&&"select"in e}function In(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&KC(e)&&t&&e.select()}}var tf=VC();function VC(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=nf(e,t),e.unshift(t)},remove(t){e=nf(e,t),e[0]?.resume()}}}function nf(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function WC(e){return e.filter(t=>t.tagName!=="A")}var zC="Portal",Zn=V((e,t)=>{const{container:n,...r}=e,[i,a]=x(!1);We(()=>a(!0),[]);const s=n||i&&globalThis?.document?.body;return s?dn.createPortal(o(pe.div,{...r,ref:t}),s):null});Zn.displayName=zC;function JC(e,t){return Mi((n,r)=>t[n][r]??n,e)}var nt=e=>{const{present:t,children:n}=e,r=YC(t),i=typeof n=="function"?n({present:r.isPresent}):qt.only(n),a=Se(r.ref,XC(i));return typeof n=="function"||r.isPresent?Mr(i,{ref:a}):null};nt.displayName="Presence";function YC(e){const[t,n]=x(),r=B(null),i=B(e),a=B("none"),[s,c]=JC(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return J(()=>{const l=vo(r.current);a.current=s==="mounted"?l:"none"},[s]),We(()=>{const l=r.current,d=i.current;if(d!==e){const u=a.current,p=vo(l);e?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(d&&u!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,c]),We(()=>{if(t){let l;const d=t.ownerDocument.defaultView??window,u=m=>{const f=vo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=m=>{m.target===t&&(a.current=vo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(l),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:se(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function vo(e){return e?.animationName||"none"}function XC(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Jc=0;function yo(){J(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??rf()),document.body.insertAdjacentElement("beforeend",e[1]??rf()),Jc++,()=>{Jc===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Jc--}},[])}function rf(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Kt=function(){return Kt=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},Kt.apply(this,arguments)};function af(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function QC(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var bo="right-scroll-bar-position",_o="width-before-scroll-bar",ZC="with-scroll-bars-hidden",eN="--removed-body-scroll-bar-size";function Yc(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function tN(e,t){var n=x(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var nN=typeof window<"u"?bt:J,of=new WeakMap;function rN(e,t){var n=tN(t||null,function(r){return e.forEach(function(i){return Yc(i,r)})});return nN(function(){var r=of.get(n);if(r){var i=new Set(r),a=new Set(e),s=n.current;i.forEach(function(c){a.has(c)||Yc(c,null)}),a.forEach(function(c){i.has(c)||Yc(c,s)})}of.set(n,e)},[e]),n}function iN(e){return e}function aN(e,t){t===void 0&&(t=iN);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var c=function(){var d=a;a=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){a.push(d),l()},filter:function(d){return a=a.filter(d),n}}}}}function oN(e){e===void 0&&(e={});var t=aN(null);return t.options=Kt({async:!0,ssr:!1},e),t}var sf=function(e){var t=e.sideCar,n=af(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return y(r,Kt({},n))};sf.isSideCarExport=!0;function sN(e,t){return e.useMedium(t),sf}var cf=oN(),Xc=function(){},wo=V(function(e,t){var n=B(null),r=x({onScrollCapture:Xc,onWheelCapture:Xc,onTouchMoveCapture:Xc}),i=r[0],a=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,g=e.noIsolation,h=e.inert,v=e.allowPinchZoom,w=e.as,b=w===void 0?"div":w,S=e.gapMode,C=af(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),T=m,P=rN([n,t]),k=Kt(Kt({},C),i);return y(Z,null,u&&y(T,{sideCar:cf,removeScrollBar:d,shards:p,noRelative:f,noIsolation:g,inert:h,setCallbacks:a,allowPinchZoom:!!v,lockRef:n,gapMode:S}),s?Mr(qt.only(c),Kt(Kt({},k),{ref:P})):y(b,Kt({},k,{className:l,ref:P}),c))});wo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},wo.classNames={fullWidth:_o,zeroRight:bo};var lf,cN=function(){if(lf)return lf;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function lN(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=cN();return t&&e.setAttribute("nonce",t),e}function dN(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function uN(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var pN=function(){var e=0,t=null;return{add:function(n){e==0&&(t=lN())&&(dN(t,n),uN(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},mN=function(){var e=pN();return function(t,n){J(function(){return e.add(t),function(){e.remove()}},[t&&n])}},df=function(){var e=mN(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},fN={left:0,top:0,right:0,gap:0},Qc=function(e){return parseInt(e||"",10)||0},hN=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[Qc(n),Qc(r),Qc(i)]},gN=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return fN;var t=hN(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},vN=df(),Bi="data-scroll-locked",yN=function(e,t,n,r){var i=e.left,a=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
|
|
2
|
-
.`.concat(
|
|
1
|
+
(function(){var Ff=Object.defineProperty,NS=(e,t)=>{let n={};for(var r in e)Ff(n,r,{get:e[r],enumerable:!0});return t||Ff(n,Symbol.toStringTag,{value:"Module"}),n};function _e(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function Oe(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function we(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function Bf(e,t,n,r,i){const o=new URLSearchParams;return o.set("project",e||""),typeof t=="number"&&o.set("limit",String(t)),typeof n=="number"&&o.set("offset",String(n)),r&&o.set("scope",r),i&&o.set("q",i),o.toString()}async function ES(){return Oe("/api/observer-status")}async function AS(){return Oe("/api/config")}async function xS(e){const t=await fetch("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.text();let r=null;if(n)try{r=JSON.parse(n)}catch{}if(!t.ok){const i=_e(r)||n||"request failed";throw new Error(i)}return r}async function ul(){return Oe("/api/coordinator/admin/status")}async function Uf(e){return Oe(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function DS(e){const t=await fetch("/api/coordinator/admin/groups",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function $S(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function LS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function jS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function OS(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return Oe(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function MS(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function qf(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return Oe(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function FS(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:o}=await we(r);if(!r.ok)throw new Error(_e(o)||i||"request failed");return o}async function BS(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:o,payload:s}=await we(i);if(!i.ok)throw new Error(_e(s)||o||"request failed");return s}async function US(e){const t=new URLSearchParams;e&&t.set("group_id",e);const n=t.size?`?${t.toString()}`:"";return Oe(`/api/coordinator/admin/join-requests${n}`)}async function Gf(e,t=!0){const n=new URLSearchParams;e&&n.set("group_id",e),t&&n.set("include_disabled","1");const r=n.size?`?${n.toString()}`:"";return Oe(`/api/coordinator/admin/devices${r}`)}async function qS(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function GS(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:o}=await we(r);if(!r.ok)throw new Error(_e(o)||i||"request failed");return o}async function HS(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function KS(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function VS(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function Hf(e){const t=await fetch("/api/coordinator/admin/invites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Kf(e,t){const n=Bf(e,t?.limit,t?.offset,t?.scope,t?.q);return Oe(`/api/observations?${n}`)}async function zS(e,t){const n=await fetch("/api/memories/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,visibility:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function WS(e,t){const n=await fetch("/api/memories/project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,project:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function JS(e){const t=await fetch("/api/memories/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Vf(e,t){const n=Bf(e,t?.limit,t?.offset,t?.scope,t?.q);return Oe(`/api/summaries?${n}`)}async function YS(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function XS(e=1200){const t=new AbortController,n=window.setTimeout(()=>t.abort(),e);try{const r=await fetch("/api/runtime",{cache:"no-store",signal:t.signal});if(!r.ok)throw new Error(`/api/runtime: ${r.status} ${r.statusText}`)}finally{window.clearTimeout(n)}}async function QS(){return Oe("/api/runtime")}async function Fa(){return(await Oe("/api/projects")).projects||[]}async function ZS(){return Oe("/api/stats")}async function eC(e){return Oe(`/api/usage?project=${encodeURIComponent(e)}`)}async function tC(e){return Oe(`/api/session?project=${encodeURIComponent(e)}`)}async function nC(e){return Oe(`/api/raw-events?project=${encodeURIComponent(e)}`)}var Ba=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="RecipientPolicyTeamRenameApiError"}},rC=new Set(["team_name_invalid","team_not_found","team_rename_stale","team_link_stale","team_link_ambiguous","team_coordinator_rename_failed","team_local_rename_pending","team_rename_failed"]);async function iC(e){let t;try{t=await fetch(`/api/sync/recipient-policy/v1/teams/${encodeURIComponent(e.teamId)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayName:e.displayName,expectedDisplayName:e.expectedDisplayName})})}catch{throw new Ba(0,"team_rename_failed")}const{payload:n}=await we(t);if(!t.ok){const r=n&&typeof n=="object"&&"error"in n?String(n.error):"";throw new Ba(t.status,rC.has(r)?r:"team_rename_failed")}if(n?.version!==1||typeof n.teamId!="string"||typeof n.displayName!="string"||typeof n.revision!="string"||typeof n.linkedCoordinatorGroupRenamed!="boolean")throw new Ba(t.status,"team_rename_failed");return n}var oC=new Set(["device_display_name_invalid","device_display_name_required","device_display_name_too_long","invite_already_bound","invite_expired","invite_identity_conflict","invite_invalid","inviter_identity_invalid","project_invite_acceptance_failed","project_invite_bootstrap_incomplete","project_invite_self_acceptance_forbidden","project_invite_trust_state_invalid","project_sync_enablement_failed","recipient_display_name_invalid","recipient_display_name_required","recipient_display_name_too_long"]),zf=class extends Error{errorCode;constructor(e,t){super(e),this.errorCode=t,this.name="ProjectInviteAcceptanceError"}};async function Ua(e,t="",n){const r=new URLSearchParams;e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1");const i=r.size?`?${r.toString()}`:"";return Oe(`/api/sync/status${i}`)}async function pl(e,t,n){const r=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:i,payload:o}=await we(r);if(!r.ok){const s=typeof o?.detail=="string"?o.detail.trim():"",c=_e(o),l=s||c||i||"request failed";throw n==="project_share_invite"&&c&&oC.has(c)?new zf(l,c):new Error(l)}return o}async function Wf(e,t={}){const n=await fetch("/api/sync/invites/inspect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function aC(){return Oe("/api/sync/actors")}async function sC(e=!1){return Oe(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function Jf(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function Yf(e,t){const n=await fetch("/api/sync/peers/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_device_id:e,name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function cC(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let o={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(o=c)}catch{o={}}const s=typeof o.detail=="string"?o.detail:void 0;if(!r.ok)throw new Error(s||_e(o)||i||"request failed");return o}var Xf=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},qa=class extends Error{requiredGuardrails;requiredGuardrailTokens;guardrailWarnings;constructor(e){super("Sharing domain guardrail confirmation required"),this.name="SharingDomainGuardrailConfirmationError",this.requiredGuardrails=e.required_guardrails??[],this.requiredGuardrailTokens=e.required_guardrail_tokens??[],this.guardrailWarnings=e.guardrail_warnings??[]}},Qf=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},fl=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},ml=1,Zf=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_completion_unavailable","team_setup_completion_conflict","team_setup_completion_invalid","team_setup_failed"]),lC=new Set(["needs_setup","in_progress","stale","ready"]),dC=new Set(["reviewing","ready_to_finish","unavailable","completed"]),uC=new Set(["setup_incomplete","setup_unavailable","setup_completed","device_inactive","device_active","assignment_evidence_inactive","assignment_required","assignment_unavailable","decision_unresolved","mapping_unavailable","automatic_mapping"]);function et(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function Gt(e){return typeof e=="string"||e===null}function br(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function tn(e,t){return Array.isArray(e)&&e.every(t)}function em(e){return et(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&lC.has(e.status)&&br(e.deviceCount)&&br(e.projectCount)&&br(e.unresolvedDeviceCount)&&br(e.unresolvedProjectCount):!1}function pC(e){return et(e)&&e.version===ml&&tn(e.candidates,t=>em(t)&&t.status!=="ready")}function fC(e){return et(e)?e.kind==="absent"||e.kind==="existing"&&br(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function Gn(e){return!et(e)||!qn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&uC.has(e.blockedReason)}function mC(e){return!et(e)||!qn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:Gn(e.assignIdentity)&&Gn(e.include)&&Gn(e.exclude)&&Gn(e.remove)&&Gn(e.clearDecision)}function hC(e){return et(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&Gt(e.existingIdentityRef)&&Gt(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&Gt(e.targetIdentityRef)&&fC(e.expectation)&&mC(e.actions):!1}function gC(e){return et(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&Gt(e.canonicalProjectRef)&&Gt(e.resolvedProjectRef)&&tn(e.mappingChoices,t=>et(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&et(e.actions)&&qn(e.actions,["map"])&&Gn(e.actions.map):!1}function vC(e){if(!et(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return tn(e.teamChanges,n=>et(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&t(n.change)&&[null,"person_all_devices","reviewed_allowlist"].includes(n.fromDeviceEligibilityMode)&&n.toDeviceEligibilityMode==="reviewed_allowlist")&&tn(e.membershipChanges,n=>et(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&tn(e.projectChanges,n=>et(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&Gt(n.fromCanonicalProjectRef)&&Gt(n.fromResolvedProjectRef)&&Gt(n.fromResolvedProjectDisplayName)&&Gt(n.toCanonicalProjectRef)&&Gt(n.toResolvedProjectRef)&&Gt(n.toResolvedProjectDisplayName)&&t(n.change))&&tn(e.recipientChanges,n=>et(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&n.recipientKind==="team"&&typeof n.recipientRef=="string"&&typeof n.recipientDisplayName=="string"&&t(n.change))&&tn(e.deviceAccessChanges,n=>et(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&(n.canonicalProjectKind==="project"||n.canonicalProjectKind==="legacy_default_sharing")&&typeof n.deviceRef=="string"&&typeof n.deviceDisplayName=="string"&&typeof n.change=="string"&&["add","remove"].includes(n.change))}function yC(e){return et(e)&&qn(e,["finish","refresh"])&&Gn(e.refresh)&&Gn(e.finish)}function tm(e,t,n){return e.every(r=>Object.values(r.actions).every(i=>!i.enabled&&i.blockedReason===n))&&t.every(r=>!r.actions.map.enabled&&r.actions.map.blockedReason===n)}function ci(e){if(!et(e)||!(e.version===ml&&em(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&dC.has(e.state)&&br(e.unresolvedDeviceCount)&&br(e.unresolvedProjectCount)&&tn(e.devices,hC)&&tn(e.projects,gC)&&yC(e.actions)&&tn(e.identityChoices,o=>et(o)&&typeof o.identityRef=="string"&&typeof o.displayName=="string")))return!1;const t=e.actions,n=e.devices,r=e.projects,i=["actions","attemptId","candidate","devices","identityChoices","projects","state","unresolvedDeviceCount","unresolvedProjectCount","version"];return e.state==="ready_to_finish"?qn(e,[...i,"accessDelta","accessDeltaDigest","finishDigest","viewerAccessDeltaDigest"])&&t.refresh.enabled===!0&&t.finish.enabled===!0&&typeof e.finishDigest=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.viewerAccessDeltaDigest=="string"&&vC(e.accessDelta):e.state==="unavailable"?qn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&Zf.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&tm(n,r,"setup_unavailable"):e.state==="completed"?qn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&tm(n,r,"setup_completed"):qn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function bC(e){return et(e)&&e.version===ml&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var Ht=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="LegacyTeamSetupApiError"}};function Hn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function Kn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new Ht(0,"team_setup_failed")}let i;try{const o=await r.text();if(!o)throw new Error("empty Team setup response");i=JSON.parse(o)}catch{throw new Ht(r.status,"team_setup_failed")}if(!r.ok){const o=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=Zf.has(o)?o:"team_setup_failed";throw new Ht(r.status,s)}if(!t(i))throw new Ht(r.status,"team_setup_failed");return i}function li(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function nm(){return Kn(Hn(),pC)}function _C(e){return Kn(Hn(e),ci)}function wC(e,t,n){return Kn(`${Hn(e)}/devices/${encodeURIComponent(t)}/assignment`,ci,li("PUT",n))}function SC(e,t,n){return Kn(`${Hn(e)}/devices/${encodeURIComponent(t)}/decision`,ci,li("PUT",n))}function CC(e,t,n){return Kn(`${Hn(e)}/devices/${encodeURIComponent(t)}/decision`,ci,li("DELETE",n))}function IC(e,t,n){return Kn(`${Hn(e)}/projects/${encodeURIComponent(t)}/mapping`,ci,li("PUT",n))}function PC(e){return Kn(`${Hn(e)}/refresh`,ci,li("POST",{}))}function RC(e,t){return Kn(`${Hn(e)}/finish`,bC,li("POST",t))}var hl=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function gl(){return Oe("/api/sync/recipient-policy/v1/intent")}function vl(){return Oe("/api/sync/recipient-policy/v1/device-inventory")}async function rm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok){const o=i?.errorCode||i?.error||_e(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new fl(n.status,o,s)}return i}function im(e){return rm("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function om(e){return rm("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function kC(){return Oe("/api/sync/recipient-policy/v1/reconciliation-status")}async function am(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new hl(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const o=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(o||_e(i)||r||"request failed")}return i}function TC(e){return am("/api/sync/recipient-policy/v1/edges/preview",e)}function NC(e){return am("/api/sync/recipient-policy/v1/edges/commit",e)}async function sm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}function EC(e){return sm("/api/sync/recipient-policy/v1/invites/preview",e)}function AC(e){return sm("/api/sync/recipient-policy/v1/invites",e)}async function xC(){const e=await Oe("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function DC(){return Oe("/api/sync/sharing-domains/settings")}async function ho(e={}){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i==null||i===""||t.set(r,String(i));const n=t.toString();return Oe(`/api/sync/projects${n?`?${n}`:""}`)}async function cm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}function $C(e){return cm("/api/sync/project-invites/preview",e)}function LC(e){return cm("/api/sync/project-invites",e)}function lm(){return Oe("/api/sync/share-operations")}function jC(e){return Oe(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function OC(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function MC(e){const t=await fetch("/api/sync/sharing-domains/project-mappings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new qa(r):new Error(_e(r)||n||"request failed");const i=r?.mapping;if(!i)throw new Error("response missing mapping");return{...i,guardrail_warnings:r.guardrail_warnings??i.guardrail_warnings}}async function FC(e){const t=await fetch("/api/sync/sharing-domains/project-mappings/bulk",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new qa(r):new Error(_e(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function BC(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return!!r?.deleted}async function UC(e){const t=await fetch("/api/sync/projects/reassign-project",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function qC(e){const t=await fetch("/api/sync/projects/forget",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new Xf(r.preview):new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function GC(e){const t=await fetch("/api/sync/legacy-shared-review/reassign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await we(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new Qf(r.preview):new Error(_e(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function HC(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function KC(e,t){const n=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");const o=i?.preferences;if(!o)throw new Error("response missing preferences");return o}async function VC(e){const t=await fetch("/api/sync/actors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function zC(e,t){const n=await fetch("/api/sync/actors/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e,display_name:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function dm(e,t){const n=await fetch("/api/sync/actors/merge",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({primary_actor_id:e,secondary_actor_id:t})}),{text:r,payload:i}=await we(n);if(!n.ok)throw new Error(_e(i)||r||"request failed");return i}async function WC(e){const t=await fetch("/api/sync/actors/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({actor_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function JC(e){const t=await fetch("/api/sync/legacy-devices/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({origin_device_id:e})}),{text:n,payload:r}=await we(t);if(!t.ok)throw new Error(_e(r)||n||"request failed");return r}async function yl(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:o,payload:s}=await we(i);if(!i.ok)throw new Error(_e(s)||o||"request failed");if(!o)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(o||"invalid sync response");return s}async function YC(){return Oe("/api/update-status")}function XC(e){return{current_version:"unknown",latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function Ga(e){return e!==null&&typeof e=="object"?e:null}function um(e){const t=Ga(e),n=Ga(t?.status),r=Ga(Ga(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var go,he,pm,fm,Vn,mm,hm,gm,bl,Ha,vo,vm,_l,wl,Sl,ym,Ka={},Va=[],QC=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,yo=Array.isArray;function nn(e,t){for(var n in t)e[n]=t[n];return e}function Cl(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(e,t,n){var r,i,o,s={};for(o in t)o=="key"?r=t[o]:o=="ref"?i=t[o]:s[o]=t[o];if(arguments.length>2&&(s.children=arguments.length>3?go.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(o in e.defaultProps)s[o]===void 0&&(s[o]=e.defaultProps[o]);return bo(e,s,r,i,null)}function bo(e,t,n,r,i){var o={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++pm,__i:-1,__u:0};return i==null&&he.vnode!=null&&he.vnode(o),o}function bm(){return{current:null}}function z(e){return e.children}function jt(e,t){this.props=e,this.context=t}function _r(e,t){if(t==null)return e.__?_r(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?_r(e):null}function ZC(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=nn({},t);o.__v=t.__v+1,he.vnode&&he.vnode(o),Pl(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??_r(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Rm(r,o,i),t.__e=t.__=null,o.__e!=n&&_m(o)}}function _m(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),_m(e)}function Il(e){(!e.__d&&(e.__d=!0)&&Vn.push(e)&&!za.__r++||mm!=he.debounceRendering)&&((mm=he.debounceRendering)||hm)(za)}function za(){try{for(var e,t=1;Vn.length;)Vn.length>t&&Vn.sort(gm),e=Vn.shift(),t=Vn.length,ZC(e)}finally{Vn.length=za.__r=0}}function wm(e,t,n,r,i,o,s,c,l,d,u){var p,f,m,v,g,h,y=r&&r.__k||Va,w=t.length;for(l=eI(n,t,y,l,w),p=0;p<w;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&y[m.__i]||Ka,m.__i=p,h=Pl(e,m,f,i,o,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Rl(f.ref,null,m),u.push(m.ref,m.__c||v,m)),g==null&&v!=null&&(g=v),4&m.__u?(l=Sm(m,l,e),f.__e&&(f.__e=null)):typeof m.type=="function"&&h!==void 0?l=h:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=g,l}function eI(e,t,n,r,i){var o,s,c,l,d,u=n.length,p=u,f=0;for(e.__k=new Array(i),o=0;o<i;o++)(s=t[o])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[o]=bo(null,s,null,null,null):yo(s)?s=e.__k[o]=bo(z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=bo(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,l=o+f,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=tI(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?f--:i<u&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?f--:d==l+1?f++:(d>l?f--:f++,s.__u|=4))):e.__k[o]=null;if(p)for(o=0;o<u;o++)(c=n[o])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=_r(c)),Tm(c,c));return r}function Sm(e,t,n){var r,i;if(typeof e.type=="function"){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=Sm(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=_r(e)),t=n.insertBefore(e.__e,t||null));do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function wn(e,t){return t=t||[],e==null||typeof e=="boolean"||(yo(e)?e.some(function(n){wn(n,t)}):t.push(e)),t}function tI(e,t,n,r){var i,o,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,o=n+1;i>=0||o<t.length;)if((d=t[s=i>=0?i--:o++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function Cm(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||QC.test(t)?n:n+"px"}function Wa(e,t,n,r,i){var o,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Cm(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Cm(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(vm,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?r?n[vo]=r[vo]:(n[vo]=_l,e.addEventListener(t,o?Sl:wl,o)):e.removeEventListener(t,o?Sl:wl,o);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Im(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Ha]==null)t[Ha]=_l++;else if(t[Ha]<n[vo])return;return n(he.event?he.event(t):t)}}}function Pl(e,t,n,r,i,o,s,c,l,d){var u,p,f,m,v,g,h,y,w,_,I,P,k,A,L,F,T=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=he.__b)&&u(t);e:if(typeof T=="function"){p=s.length;try{if(w=t.props,_=T.prototype&&T.prototype.render,I=(u=T.contextType)&&r[u.__c],P=u?I?I.props.value:u.__:r,n.__c?y=(f=t.__c=n.__c).__=f.__E:(_?t.__c=f=new T(w,P):(t.__c=f=new jt(w,P),f.constructor=T,f.render=rI),I&&I.sub(f),f.state||(f.state={}),f.__n=r,m=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&T.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=nn({},f.__s)),nn(f.__s,T.getDerivedStateFromProps(w,f.__s))),v=f.props,g=f.state,f.__v=t,m)_&&T.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&T.getDerivedStateFromProps==null&&w!==v&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(w,P),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(w,f.__s,P)===!1){t.__v!=n.__v&&(f.props=w,f.state=f.__s,f.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(M){M&&(M.__=t)}),Va.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f),c=_r(n);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(w,f.__s,P),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(v,g,h)})}if(f.context=P,f.props=w,f.__P=e,f.__e=!1,k=he.__r,A=0,_)f.state=f.__s,f.__d=!1,k&&k(t),u=f.render(f.props,f.state,f.context),Va.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,k&&k(t),u=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++A<25);f.state=f.__s,f.getChildContext!=null&&(r=nn(nn({},r),f.getChildContext())),_&&!m&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(v,g)),L=u!=null&&u.type===z&&u.key==null?km(u.props.children):u,c=wm(e,yo(L)?L:[L],t,n,r,i,o,s,c,l,d),f.base=t.__e,t.__u&=-161,f.__h.length&&s.push(f),y&&(f.__E=f.__=null)}catch(M){if(s.length=p,t.__v=null,l||o!=null){if(M.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;o!=null&&(o[o.indexOf(c)]=null),t.__e=c}else if(o!=null)for(F=o.length;F--;)Cl(o[F])}else t.__e=n.__e;t.__k??=n.__k||[],M.then||Pm(t),he.__e(M,t,n)}}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=nI(n.__e,t,n,r,i,o,s,l,d);return(u=he.diffed)&&u(t),128&t.__u?void 0:c}function Pm(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Pm))}function Rm(e,t,n){for(var r=0;r<n.length;r++)Rl(n[r],n[++r],n[++r]);he.__c&&he.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){he.__e(o,i.__v)}})}function km(e){return typeof e!="object"||e==null||e.__b>0?e:yo(e)?e.map(km):e.constructor!==void 0?null:nn({},e)}function nI(e,t,n,r,i,o,s,c,l){var d,u,p,f,m,v,g,h=n.props||Ka,y=t.props,w=t.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),o!=null){for(d=0;d<o.length;d++)if((m=o[d])&&"setAttribute"in m==!!w&&(w?m.localName==w:m.nodeType==3)){e=m,o[d]=null;break}}if(e==null){if(w==null)return document.createTextNode(y);e=document.createElementNS(i,w,y.is&&y),c&&(he.__m&&he.__m(t,o),c=!1),o=null}if(w==null)h===y||c&&e.data==y||(e.data=y);else{if(o=w=="textarea"&&y.defaultValue!=null?null:o&&go.call(e.childNodes),!c&&o!=null)for(h={},d=0;d<e.attributes.length;d++)h[(m=e.attributes[d]).name]=m.value;for(d in h)m=h[d],d=="dangerouslySetInnerHTML"?p=m:d=="children"||d in y||d=="value"&&"defaultValue"in y||d=="checked"&&"defaultChecked"in y||Wa(e,d,null,m,i);for(d in y)m=y[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?u=m:d=="value"?v=m:d=="checked"?g=m:c&&typeof m!="function"||h[d]===m||Wa(e,d,m,h[d],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),wm(t.type=="template"?e.content:e,yo(f)?f:[f],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&_r(n,0),c,l),o!=null)for(d=o.length;d--;)Cl(o[d]);c&&w!="textarea"||(d="value",w=="progress"&&v==null?e.removeAttribute("value"):v!=null&&(v!==e[d]||w=="progress"&&!v||w=="option"&&v!=h[d])&&Wa(e,d,v,h[d],i),d="checked",g!=null&&g!=e[d]&&Wa(e,d,g,h[d],i))}return e}function Rl(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(i){he.__e(i,n)}}function Tm(e,t,n){var r,i;if(he.unmount&&he.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Rl(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){he.__e(o,t)}r.base=r.__P=r.__n=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Tm(r[i],t,n||typeof e.type!="function");n||Cl(e.__e),e.__c=e.__=e.__e=void 0}function rI(e,t,n){return this.constructor(e,n)}function We(e,t,n){var r,i,o,s;t==document&&(t=document.documentElement),he.__&&he.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,o=[],s=[],Pl(t,e=(!r&&n||t).__k=b(z,null,[e]),i||Ka,Ka,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?go.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),Rm(o,e,s),e.props.children=null}function Nm(e,t){We(e,t,Nm)}function iI(e,t,n){var r,i,o,s,c=nn({},e.props);for(o in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)o=="key"?r=t[o]:o=="ref"?i=t[o]:c[o]=t[o]===void 0&&s!=null?s[o]:t[o];return arguments.length>2&&(c.children=arguments.length>3?go.call(arguments,2):n),bo(e.type,c,r||e.key,i||e.ref,null)}function wr(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&r.forEach(function(s){s.__e=!0,Il(s)})},this.sub=function(o){r.add(o);var s=o.componentWillUnmount;o.componentWillUnmount=function(){r&&r.delete(o),s&&s.call(o)}}),n.children}return t.__c="__cC"+ym++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}go=Va.slice,he={__e:function(e,t,n,r){for(var i,o,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((o=i.constructor)&&o.getDerivedStateFromError!=null&&(i.setState(o.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},pm=0,fm=function(e){return e!=null&&e.constructor===void 0},jt.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=nn({},this.state);typeof e=="function"&&(e=e(nn({},n),this.props)),e&&nn(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Il(this))},jt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Il(this))},jt.prototype.render=z,Vn=[],hm=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,gm=function(e,t){return e.__v.__b-t.__v.__b},za.__r=0,bl=Math.random().toString(8),Ha="__d"+bl,vo="__a"+bl,vm=/(PointerCapture)$|Capture$/i,_l=0,wl=Im(!1),Sl=Im(!0),ym=0;var Sn,Be,kl,Em,di=0,Am=[],Je=he,xm=Je.__b,Dm=Je.__r,$m=Je.diffed,Lm=Je.__c,jm=Je.unmount,Om=Je.__;function Sr(e,t){Je.__h&&Je.__h(Be,e,di||t),di=0;var n=Be.__H||(Be.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function x(e){return di=1,zn(Fm,e)}function zn(e,t,n){var r=Sr(Sn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Fm(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=Be,!Be.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=!1,p=r.__c.props!==c;if(r.__c.__H.__.some(function(m){if(m.__N){u=!0;var v=m.__[0];m.__=m.__N,m.__N=void 0,v!==m.__[0]&&(p=!0)}}),o){var f=o.call(this,c,l,d);return u?f||p:f}return!u||p};Be.__f=!0;var o=Be.shouldComponentUpdate,s=Be.componentWillUpdate;Be.componentWillUpdate=function(c,l,d){if(this.__e){var u=o;o=void 0,i(c,l,d),o=u}s&&s.call(this,c,l,d)},Be.shouldComponentUpdate=i}return r.__N||r.__}function K(e,t){var n=Sr(Sn++,3);!Je.__s&&El(n.__H,t)&&(n.__=e,n.u=t,Be.__H.__h.push(n))}function It(e,t){var n=Sr(Sn++,4);!Je.__s&&El(n.__H,t)&&(n.__=e,n.u=t,Be.__h.push(n))}function q(e){return di=5,Re(function(){return{current:e}},[])}function Ja(e,t,n){di=6,It(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function Re(e,t){var n=Sr(Sn++,7);return El(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function se(e,t){return di=8,Re(function(){return e},t)}function Cn(e){var t=Be.context[e.__c],n=Sr(Sn++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Be)),t.props.value):e.__}function Tl(e,t){Je.useDebugValue&&Je.useDebugValue(t?t(e):e)}function oI(e){var t=Sr(Sn++,10),n=x();return t.__=e,Be.componentDidCatch||(Be.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Cr(){var e=Sr(Sn++,11);if(!e.__){for(var t=Be.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function aI(){for(var e;e=Am.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ya),t.__h.some(Nl),t.__h=[]}catch(n){t.__h=[],Je.__e(n,e.__v)}}}Je.__b=function(e){Be=null,xm&&xm(e)},Je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Om&&Om(e,t)},Je.__r=function(e){Dm&&Dm(e),Sn=0;var t=(Be=e.__c).__H;t&&(kl===Be?(t.__h=[],Be.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Ya),t.__h.some(Nl),t.__h=[],Sn=0)),kl=Be},Je.diffed=function(e){$m&&$m(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Am.push(t)!==1&&Em===Je.requestAnimationFrame||((Em=Je.requestAnimationFrame)||sI)(aI)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),kl=Be=null},Je.__c=function(e,t){t.some(function(n){try{n.__h.some(Ya),n.__h=n.__h.filter(function(r){return!r.__||Nl(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Je.__e(r,n.__v)}}),Lm&&Lm(e,t)},Je.unmount=function(e){jm&&jm(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Ya(r)}catch(i){t=i}}),n.__H=void 0,t&&Je.__e(t,n.__v))};var Mm=typeof requestAnimationFrame=="function";function sI(e){var t,n=function(){clearTimeout(r),Mm&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Mm&&(t=requestAnimationFrame(n))}function Ya(e){var t=Be,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Be=t}function Nl(e){var t=Be;e.__c=e.__(),Be=t}function El(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Fm(e,t){return typeof t=="function"?t(e):t}var cI=0,bU=Array.isArray;function a(e,t,n,r,i,o){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cI,__i:-1,__u:0,__source:i,__self:o};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return he.vnode&&he.vnode(d),d}function ui({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:o="Close"}){return a("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[a("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),a("span",{className:"modal-close-button-label",children:o})]})}var pi=NS({Children:()=>Ir,Component:()=>jt,Fragment:()=>z,PureComponent:()=>Xa,StrictMode:()=>z,Suspense:()=>_o,SuspenseList:()=>fi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>rh,cloneElement:()=>Pr,createContext:()=>wr,createElement:()=>b,createFactory:()=>ih,createPortal:()=>rn,createRef:()=>bm,default:()=>_I,findDOMNode:()=>ch,flushSync:()=>Qa,forwardRef:()=>J,hydrate:()=>Qm,isElement:()=>dh,isFragment:()=>oh,isMemo:()=>ah,isValidElement:()=>In,lazy:()=>Wm,memo:()=>Um,render:()=>Xm,startTransition:()=>$l,unmountComponentAtNode:()=>sh,unstable_batchedUpdates:()=>lh,useCallback:()=>se,useContext:()=>Cn,useDebugValue:()=>Tl,useDeferredValue:()=>Ll,useEffect:()=>K,useErrorBoundary:()=>oI,useId:()=>Cr,useImperativeHandle:()=>Ja,useInsertionEffect:()=>Ol,useLayoutEffect:()=>It,useMemo:()=>Re,useReducer:()=>zn,useRef:()=>q,useState:()=>x,useSyncExternalStore:()=>xl,useTransition:()=>jl,version:()=>bI});function Bm(e,t){for(var n in t)e[n]=t[n];return e}function Al(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function xl(e,t){var n=t(),r=x({t:{__:n,u:t}}),i=r[0].t,o=r[1];return It(function(){i.__=n,i.u=t,Dl(i)&&o({t:i})},[e,n,t]),K(function(){return Dl(i)&&o({t:i}),e(function(){Dl(i)&&o({t:i})})},[e]),n}function Dl(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function $l(e){e()}function Ll(e){return e}function jl(){return[!1,$l]}var Ol=It;function Xa(e,t){this.props=e,this.context=t}function Um(e,t){function n(i){var o=this.props.ref;return o!=i.ref&&o&&(typeof o=="function"?o(null):o.current=null),t?!t(this.props,i)||o!=i.ref:Al(this.props,i)}function r(i){return this.shouldComponentUpdate=n,b(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Xa.prototype=new jt).isPureReactComponent=!0,Xa.prototype.shouldComponentUpdate=function(e,t){return Al(this.props,e)||Al(this.state,t)};var qm=he.__b;he.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),qm&&qm(e)};var lI=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=Bm({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=lI,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Gm=function(e,t){return e==null?null:wn(wn(e).map(t))},Ir={map:Gm,forEach:Gm,count:function(e){return e?wn(e).length:0},only:function(e){var t=wn(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:wn},dI=he.__e;he.__e=function(e,t,n,r){if(e.then){for(var i,o=t;o=o.__;)if((i=o.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k||[]),i.__c(e,t)}dI(e,t,n,r)};var Hm=he.unmount;function Km(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Bm({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Km(r,t,n)})),e}function Vm(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Vm(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function _o(){this.__u=0,this.o=null,this.__b=null}function zm(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Wm(e){var t,n,r,i=null;function o(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?b(i,s):null}return o.displayName="Lazy",o.__f=!0,o}function fi(){this.i=null,this.l=null}he.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Hm&&Hm(e)},(_o.prototype=new jt).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=zm(r.__v),o=!1,s=function(){o||r.__z||(o=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Vm(d,d.__c.__P,d.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.__P=c,u.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},_o.prototype.componentWillUnmount=function(){this.o=[]},_o.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Km(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&b(z,null,e.fallback);return i&&(i.__u&=-33),[b(z,null,t.__a?null:e.children),i]};var Jm=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function uI(e){return this.getChildContext=function(){return e.context},e.children}function pI(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){We(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,o){this.childNodes.push(i),t.h.insertBefore(i,o)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}We(b(uI,{context:t.context},e.__v),t.v)}function rn(e,t){var n=b(pI,{__v:e,h:t});return n.containerInfo=t,n}(fi.prototype=new jt).__a=function(e){var t=this,n=zm(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),Jm(t,e,r)):i()};n?n(o):o()}},fi.prototype.render=function(e){this.i=null,this.l=new Map;var t=wn(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},fi.prototype.componentDidUpdate=fi.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Jm(e,n,t)})};var Ym=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,fI=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,mI=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,hI=/[A-Z0-9]/g,gI=typeof document<"u",vI=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Xm(e,t,n){return t.__k??(t.textContent=""),We(e,t),typeof n=="function"&&n(),e?e.__c:null}function Qm(e,t,n){return Nm(e,t),typeof n=="function"&&n(),e?e.__c:null}jt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(jt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Zm=he.event;he.event=function(e){return Zm&&(e=Zm(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Ml,yI={configurable:!0,get:function(){return this.class}},eh=he.vnode;he.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},o=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||gI&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&c===!0?c="":l==="translate"&&c==="no"?c=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||vI(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":mI.test(s)&&(s=l):l=s="oninput":o&&fI.test(s)?s=s.replace(hI,"-$&").toLowerCase():c===null&&(c=void 0),l==="oninput"&&i[s=l]&&(s="oninputCapture"),i[s]=c}}r=="select"&&(i.multiple&&Array.isArray(i.value)&&(i.value=wn(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=wn(n.children).forEach(function(d){d.props.selected=i.multiple?i.defaultValue.indexOf(d.props.value)!=-1:i.defaultValue==d.props.value}))),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",yI)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Ym,eh&&eh(e)};var th=he.__r;he.__r=function(e){th&&th(e),Ml=e.__c};var nh=he.diffed;he.diffed=function(e){nh&&nh(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),Ml=null};var rh={ReactCurrentDispatcher:{current:{readContext:function(e){return Ml.__n[e.__c].props.value},useCallback:se,useContext:Cn,useDebugValue:Tl,useDeferredValue:Ll,useEffect:K,useId:Cr,useImperativeHandle:Ja,useInsertionEffect:Ol,useLayoutEffect:It,useMemo:Re,useReducer:zn,useRef:q,useState:x,useSyncExternalStore:xl,useTransition:jl}}},bI="18.3.1";function ih(e){return b.bind(null,e)}function In(e){return!!e&&e.$$typeof===Ym}function oh(e){return In(e)&&e.type===z}function ah(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Pr(e){return In(e)?iI.apply(null,arguments):e}function sh(e){return!!e.__k&&(We(null,e),!0)}function ch(e){return e&&(e.base||e.nodeType===1&&e)||null}var lh=function(e,t){return e(t)},Qa=function(e,t){var n,r=he.debounceRendering;he.debounceRendering=function(o){n=o};try{var i=e(t);return n&&n(),i}finally{he.debounceRendering=r}},dh=In,_I={useState:x,useId:Cr,useReducer:zn,useEffect:K,useLayoutEffect:It,useInsertionEffect:Ol,useTransition:jl,useDeferredValue:Ll,useSyncExternalStore:xl,startTransition:$l,useRef:q,useImperativeHandle:Ja,useMemo:Re,useCallback:se,useContext:Cn,useDebugValue:Tl,version:"18.3.1",Children:Ir,render:Xm,hydrate:Qm,unmountComponentAtNode:sh,createPortal:rn,createElement:b,createContext:wr,createFactory:ih,cloneElement:Pr,createRef:bm,Fragment:z,isValidElement:In,isElement:dh,isFragment:oh,isMemo:ah,findDOMNode:ch,Component:jt,PureComponent:Xa,memo:Um,forwardRef:J,flushSync:Qa,unstable_batchedUpdates:lh,StrictMode:z,Suspense:_o,SuspenseList:fi,lazy:Wm,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:rh},wI=Object.defineProperty,mi=(e,t)=>wI(e,"name",{value:t,configurable:!0}),uh=!!(typeof window<"u"&&window.document&&window.document.createElement);function ne(e,t,{checkForDefaultPrevented:n=!0}={}){return mi(function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)},"handleEvent")}mi(ne,"composeEventHandlers");function SI(e){if(!uh)throw new Error("Cannot access window outside of the DOM");return e?.ownerDocument?.defaultView??window}mi(SI,"getOwnerWindow");function Fl(e){if(!uh)throw new Error("Cannot access document outside of the DOM");return e?.ownerDocument??document}mi(Fl,"getOwnerDocument");function ph(e,t=!1){const{activeElement:n}=Fl(e);if(!n?.nodeName)return null;if(fh(n)&&n.contentDocument)return ph(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=Fl(n).getElementById(r);if(i)return i}}return n}mi(ph,"getActiveElement");function fh(e){return e.tagName==="IFRAME"}mi(fh,"isFrame");var CI=Object.defineProperty,Bl=(e,t)=>CI(e,"name",{value:t,configurable:!0});function Ul(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Bl(Ul,"setRef");function mh(...e){return t=>{let n=!1;const r=e.map(i=>{const o=Ul(i,t);return!n&&typeof o=="function"&&(n=!0),o});if(n)return()=>{for(let i=0;i<r.length;i++){const o=r[i];typeof o=="function"?o():Ul(e[i],null)}}}}Bl(mh,"composeRefs");function Se(...e){return se(mh(...e),e)}Bl(Se,"useComposedRefs");var II=Object.defineProperty,Ot=(e,t)=>II(e,"name",{value:t,configurable:!0});function PI(e,t){const n=wr(t);n.displayName=e+"Context";const r=Ot(o=>{const{children:s,...c}=o,l=Re(()=>c,Object.values(c));return a(n.Provider,{value:l,children:s})},"Provider");r.displayName=e+"Provider";function i(o,s={}){const{optional:c=!1}=s,l=Cn(n);if(l)return l;if(t!==void 0)return t;if(!c)throw new Error(`\`${o}\` must be used within \`${e}\``)}return Ot(i,"useContext"),[r,i]}Ot(PI,"createContext");function lt(e,t=[]){let n=[];function r(o,s){const c=wr(s);c.displayName=o+"Context";const l=n.length;n=[...n,s];const d=Ot(p=>{const{scope:f,children:m,...v}=p,g=f?.[e]?.[l]||c,h=Re(()=>v,Object.values(v));return a(g.Provider,{value:h,children:m})},"Provider");d.displayName=o+"Provider";function u(p,f,m={}){const{optional:v=!1}=m,g=f?.[e]?.[l]||c,h=Cn(g);if(h)return h;if(s!==void 0)return s;if(!v)throw new Error(`\`${p}\` must be used within \`${o}\``)}return Ot(u,"useContext"),[d,u]}Ot(r,"createContext");const i=Ot(()=>{const o=n.map(s=>wr(s));return Ot(function(c){const l=c?.[e]||o;return Re(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])},"useScope")},"createScope");return i.scopeName=e,[r,hh(i,...t)]}Ot(lt,"createContextScope");function hh(...e){const t=e[0];if(e.length===1)return t;const n=Ot(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ot(function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return Re(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ot(hh,"composeContextScopes");var Xe=globalThis?.document?It:()=>{},RI=Object.defineProperty,kI=(e,t)=>RI(e,"name",{value:t,configurable:!0}),TI=pi[" useId ".trim().toString()]||(()=>{}),NI=0;function Nt(e){const[t,n]=x(TI());return Xe(()=>{e||n(r=>r??String(NI++))},[e]),e||(t?`radix-${t}`:"")}kI(Nt,"useId");var EI=Object.defineProperty,AI=(e,t)=>EI(e,"name",{value:t,configurable:!0}),gh=pi[" useEffectEvent ".trim().toString()],vh=pi[" useInsertionEffect ".trim().toString()];function yh(e){if(typeof gh=="function")return gh(e);const t=q(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof vh=="function"?vh(()=>{t.current=e}):Xe(()=>{t.current=e}),Re(()=>((...n)=>t.current?.(...n)),[])}AI(yh,"useEffectEvent");var xI=Object.defineProperty,wo=(e,t)=>xI(e,"name",{value:t,configurable:!0}),DI=pi[" useInsertionEffect ".trim().toString()]||Xe;function Et({prop:e,defaultProp:t,onChange:n=wo(()=>{},"onChange"),caller:r}){const[i,o,s]=bh({defaultProp:t,onChange:n}),c=e!==void 0;return[c?e:i,se(d=>{if(c){const u=_h(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}wo(Et,"useControllableState");function bh({defaultProp:e,onChange:t}){const[n,r]=x(e),i=q(n),o=q(t);return DI(()=>{o.current=t},[t]),K(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}wo(bh,"useUncontrolledState");function _h(e){return typeof e=="function"}wo(_h,"isFunction");var wh=Symbol("RADIX:SYNC_STATE");function $I(e,t,n,r){const{prop:i,defaultProp:o,onChange:s,caller:c}=t,l=i!==void 0,d=yh(s),u=[{...n,state:o}];r&&u.push(r);const[p,f]=zn((h,y)=>{if(y.type===wh)return{...h,state:y.state};const w=e(h,y);return l&&!Object.is(w.state,h.state)&&d(w.state),w},...u),m=p.state,v=q(m);K(()=>{v.current!==m&&(v.current=m,l||d(m))},[m,v,l]);const g=Re(()=>i!==void 0?{...p,state:i}:p,[p,i]);return K(()=>{l&&!Object.is(i,p.state)&&f({type:wh,state:i})},[i,p.state,l]),[g,f]}wo($I,"useControllableStateReducer");var LI=Object.defineProperty,Kt=(e,t)=>LI(e,"name",{value:t,configurable:!0});function on(e){const t=J((n,r)=>{let{children:i,...o}=n,s=null,c=!1;const l=[];ql(i)&&typeof Za=="function"&&(i=Za(i._payload)),Ir.forEach(i,f=>{if(Rh(f)){c=!0;const m=f;let v="child"in m.props?m.props.child:m.props.children;ql(v)&&typeof Za=="function"&&(v=Za(v._payload)),s=jI(m,v),l.push(s?.props?.children)}else l.push(f)}),s?s=Pr(s,void 0,l):!c&&Ir.count(i)===1&&In(i)&&(s=i);const d=s?Ph(s):void 0,u=Se(r,d);if(!s){if(i||i===0)throw new Error(c?FI(e):MI(e));return i}const p=Ih(o,s.props??{});return s.type!==z&&(p.ref=r?u:d),Pr(s,p)});return t.displayName=`${e}.Slot`,t}Kt(on,"createSlot");var Sh=Symbol.for("radix.slottable");function Ch(e){const t=Kt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=Sh,t}Kt(Ch,"createSlottable");var jI=Kt((e,t)=>{if("child"in e.props){const n=e.props.child;return In(n)?Pr(n,void 0,e.props.children(n.props.children)):null}return In(t)?t:null},"getSlottableElementFromSlottable");function Ih(e,t){const n={...t};for(const r in t){const i=e[r],o=t[r];/^on[A-Z]/.test(r)?i&&o?n[r]=(...s)=>{const c=o(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...o}:r==="className"&&(n[r]=[i,o].filter(Boolean).join(" "))}return{...e,...n}}Kt(Ih,"mergeProps");function Ph(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Kt(Ph,"getElementRef");function Rh(e){return In(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Sh}Kt(Rh,"isSlottable");var OI=Symbol.for("react.lazy");function ql(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===OI&&"_payload"in e&&kh(e._payload)}Kt(ql,"isLazyComponent");function kh(e){return typeof e=="object"&&e!==null&&"then"in e}Kt(kh,"isPromiseLike");var MI=Kt(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),FI=Kt(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Za=pi[" use ".trim().toString()],BI=Object.defineProperty,UI=(e,t)=>BI(e,"name",{value:t,configurable:!0}),ve=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=on(`Primitive.${t}`),r=J((i,o)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),a(l,{...c,ref:o})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function es(e,t){e&&Qa(()=>e.dispatchEvent(t))}UI(es,"dispatchDiscreteCustomEvent");var qI=Object.defineProperty,GI=(e,t)=>qI(e,"name",{value:t,configurable:!0});function mt(e){const t=q(e);return K(()=>{t.current=e}),Re(()=>((...n)=>t.current?.(...n)),[])}GI(mt,"useCallbackRef");var HI=Object.defineProperty,tt=(e,t)=>HI(e,"name",{value:t,configurable:!0}),Gl="dismissableLayer.update",KI="dismissableLayer.pointerDownOutside",VI="dismissableLayer.focusOutside",Th,Hl=wr({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),hi=J(tt(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:c,onInteractOutside:l,onDismiss:d,...u}=t,p=Cn(Hl),[f,m]=x(null),v=f?.ownerDocument??globalThis?.document,[,g]=x({}),h=Se(n,m),y=Array.from(p.layers),[w]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),_=w?y.indexOf(w):-1,I=f?y.indexOf(f):-1,P=p.layersWithOutsidePointerEventsDisabled.size>0,k=I>=_,A=q(!1),L=Eh(j=>{s?.(j),l?.(j),j.defaultPrevented||d?.()},{ownerDocument:v,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:A,dismissableSurfaces:p.dismissableSurfaces,shouldHandlePointerDownOutside:se(j=>{if(!(j instanceof Node))return!1;const B=[...p.branches].some(U=>U.contains(j));return k&&!B},[p.branches,k])}),F=Ah(j=>{if(i&&A.current)return;const B=j.target;[...p.branches].some(U=>U.contains(B))||(c?.(j),l?.(j),j.defaultPrevented||d?.())},v),T=f?I===y.length-1:!1,M=mt(j=>{j.key==="Escape"&&(o?.(j),!j.defaultPrevented&&d&&(j.preventDefault(),d()))});return K(()=>{if(T)return v.addEventListener("keydown",M,{capture:!0}),()=>v.removeEventListener("keydown",M,{capture:!0})},[v,T,M]),K(()=>{if(f)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(Th=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(f)),p.layers.add(f),Kl(),()=>{r&&(p.layersWithOutsidePointerEventsDisabled.delete(f),p.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=Th))}},[f,v,r,p]),K(()=>()=>{f&&(p.layers.delete(f),p.layersWithOutsidePointerEventsDisabled.delete(f),Kl())},[f,p]),K(()=>{const j=tt(()=>g({}),"handleUpdate");return document.addEventListener(Gl,j),()=>document.removeEventListener(Gl,j)},[]),a(ve.div,{...u,ref:h,style:{pointerEvents:P?k?"auto":"none":void 0,...t.style},onFocusCapture:ne(t.onFocusCapture,F.onFocusCapture),onBlurCapture:ne(t.onBlurCapture,F.onBlurCapture),onPointerDownCapture:ne(t.onPointerDownCapture,L.onPointerDownCapture)})},"DismissableLayer")),zI=J(tt(function(t,n){const r=Cn(Hl),i=q(null),o=Se(n,i);return K(()=>{const s=i.current;if(s)return r.branches.add(s),()=>{r.branches.delete(s)}},[r.branches]),a(ve.div,{...t,ref:o})},"DismissableLayerBranch"));function Nh(){const e=Cn(Hl),[t,n]=x(null);return K(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}tt(Nh,"useDismissableLayerSurface");var WI=tt(()=>!0,"IS_TRUE");function Eh(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:s=WI}=t,c=mt(e),l=q(!1),d=q(!1),u=q(new Map),p=q(()=>{});return K(()=>{function f(){d.current=!1,i.current=!1,u.current.clear()}tt(f,"resetOutsideInteraction");function m(){return Array.from(u.current.values()).some(Boolean)}tt(m,"isOutsideInteractionIntercepted");function v(_){if(!d.current)return;const I=_.target;I instanceof Node&&[...o].some(P=>P.contains(I))||u.current.set(_.type,!0),_.type==="click"&&window.setTimeout(()=>{d.current&&p.current()},0)}tt(v,"handleInteractionCapture");function g(_){d.current&&u.current.set(_.type,!1)}tt(g,"handleInteractionBubble");const h=tt(_=>{if(_.target&&!l.current){let I=function(){n.removeEventListener("click",p.current);const k=m();f(),k||Vl(KI,c,P,{discrete:!0})};if(tt(I,"handleAndDispatchPointerDownOutsideEvent"),!s(_.target)){n.removeEventListener("click",p.current),f(),l.current=!1;return}const P={originalEvent:_};d.current=!0,i.current=r&&_.button===0,u.current.clear(),!r||_.button!==0?I():(n.removeEventListener("click",p.current),p.current=I,n.addEventListener("click",p.current,{once:!0}))}else n.removeEventListener("click",p.current),f();l.current=!1},"handlePointerDown"),y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const _ of y)n.addEventListener(_,v,!0),n.addEventListener(_,g);const w=window.setTimeout(()=>{n.addEventListener("pointerdown",h)},0);return()=>{window.clearTimeout(w),n.removeEventListener("pointerdown",h),n.removeEventListener("click",p.current);for(const _ of y)n.removeEventListener(_,v,!0),n.removeEventListener(_,g)}},[n,c,r,i,o,s]),{onPointerDownCapture:tt(()=>l.current=!0,"onPointerDownCapture")}}tt(Eh,"usePointerDownOutside");function Ah(e,t=globalThis?.document){const n=mt(e),r=q(!1);return K(()=>{const i=tt(o=>{o.target&&!r.current&&Vl(VI,n,{originalEvent:o},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:tt(()=>r.current=!0,"onFocusCapture"),onBlurCapture:tt(()=>r.current=!1,"onBlurCapture")}}tt(Ah,"useFocusOutside");function Kl(){const e=new CustomEvent(Gl);document.dispatchEvent(e)}tt(Kl,"dispatchUpdate");function Vl(e,t,n,{discrete:r}){const i=n.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?es(i,o):i.dispatchEvent(o)}tt(Vl,"handleAndDispatchCustomEvent");var JI=hi,YI=zI,XI=Object.defineProperty,wt=(e,t)=>XI(e,"name",{value:t,configurable:!0}),zl="focusScope.autoFocusOnMount",Wl="focusScope.autoFocusOnUnmount",xh={bubbles:!1,cancelable:!0},ts=J(wt(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...c}=t,[l,d]=x(null),u=mt(o),p=mt(s),f=q(null),m=Se(n,d),v=q({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;K(()=>{if(i){let h=function(I){if(v.paused||!l)return;const P=I.target;l.contains(P)?f.current=P:Pn(f.current,{select:!0})},y=function(I){if(v.paused||!l)return;const P=I.relatedTarget;P!==null&&(l.contains(P)||Pn(f.current,{select:!0}))},w=function(I){if(document.activeElement===document.body)for(const P of I)P.removedNodes.length>0&&Pn(l)};wt(h,"handleFocusIn"),wt(y,"handleFocusOut"),wt(w,"handleMutations"),document.addEventListener("focusin",h),document.addEventListener("focusout",y);const _=new MutationObserver(w);return l&&_.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",y),_.disconnect()}}},[i,l,v.paused]),K(()=>{if(l){Oh.add(v);const h=document.activeElement;if(!l.contains(h)){const y=new CustomEvent(zl,xh);l.addEventListener(zl,u),l.dispatchEvent(y),y.defaultPrevented||(Dh(Fh(Jl(l)),{select:!0}),document.activeElement===h&&Pn(l))}return()=>{l.removeEventListener(zl,u),setTimeout(()=>{const y=new CustomEvent(Wl,xh);l.addEventListener(Wl,p),l.dispatchEvent(y),y.defaultPrevented||Pn(h??document.body,{select:!0}),l.removeEventListener(Wl,p),Oh.remove(v)},0)}}},[l,u,p,v]);const g=se(h=>{if(!r&&!i||v.paused)return;const y=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(y&&w){const _=h.currentTarget,[I,P]=$h(_);I&&P?!h.shiftKey&&w===P?(h.preventDefault(),r&&Pn(I,{select:!0})):h.shiftKey&&w===I&&(h.preventDefault(),r&&Pn(P,{select:!0})):w===_&&h.preventDefault()}},[r,i,v.paused]);return a(ve.div,{tabIndex:-1,...c,ref:m,onKeyDown:g})},"FocusScope"));function Dh(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Pn(r,{select:t}),document.activeElement!==n)return}wt(Dh,"focusFirst");function $h(e){const t=Jl(e);return[Yl(t,e),Yl(t.reverse(),e)]}wt($h,"getTabbableEdges");function Jl(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:wt(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}wt(Jl,"getTabbableCandidates");function Yl(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):Lh(r,{upTo:t})))return r}wt(Yl,"findVisible");function Lh(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}wt(Lh,"isHidden");function jh(e){return e instanceof HTMLInputElement&&"select"in e}wt(jh,"isSelectableInput");function Pn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&jh(e)&&t&&e.select()}}wt(Pn,"focus");var Oh=Mh();function Mh(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Xl(e,t),e.unshift(t)},remove(t){e=Xl(e,t),e[0]?.resume()}}}wt(Mh,"createFocusScopesStack");function Xl(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}wt(Xl,"arrayRemove");function Fh(e){return e.filter(t=>t.tagName!=="A")}wt(Fh,"removeLinks");var QI=Object.defineProperty,ZI=(e,t)=>QI(e,"name",{value:t,configurable:!0}),gi=J(ZI(function(t,n){const{container:r,...i}=t,[o,s]=x(!1);Xe(()=>s(!0),[]);const c=r||o&&globalThis?.document?.body;return c?rn(a(ve.div,{...i,ref:n}),c):null},"Portal")),eP=Object.defineProperty,Rn=(e,t)=>eP(e,"name",{value:t,configurable:!0});function Bh(e,t){return zn((n,r)=>t[n][r]??n,e)}Rn(Bh,"useStateMachine");var Pt=Rn(e=>{const{present:t,children:n}=e,r=Uh(t),i=typeof n=="function"?n({present:r.isPresent}):Ir.only(n),o=qh(r.ref,Gh(i));return typeof n=="function"||r.isPresent?Pr(i,{ref:o}):null},"Presence");function Uh(e){const[t,n]=x(),r=q(null),i=q(e),o=q("none"),s=q(void 0),[c,l]=Bh(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return K(()=>{c==="mounted"?(o.current=s.current??vi(r.current),s.current=void 0):o.current="none"},[c]),Xe(()=>{const d=r.current,u=i.current;if(u!==e){const p=o.current,f=vi(d);e?(s.current=f,l("MOUNT")):f==="none"||d?.display==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,l]),Xe(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,p=Rn(m=>{const v=vi(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(l("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},"handleAnimationEnd"),f=Rn(m=>{m.target===t&&(o.current=vi(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:se(d=>{if(d){const u=getComputedStyle(d);r.current=u,s.current=vi(u)}else r.current=null;n(d)},[])}}Rn(Uh,"usePresence");function Ql(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Rn(Ql,"setRef");function qh(...e){const t=q(e);return t.current=e,se(n=>{const r=t.current;let i=!1;const o=r.map(s=>{const c=Ql(s,n);return!i&&typeof c=="function"&&(i=!0),c});if(i)return()=>{for(let s=0;s<o.length;s++){const c=o[s];typeof c=="function"?c():Ql(r[s],null)}}},[])}Rn(qh,"useStableComposedRefs");function vi(e){return e?.animationName||"none"}Rn(vi,"getAnimationName");function Gh(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}Rn(Gh,"getElementRef");var tP=Object.defineProperty,Zl=(e,t)=>tP(e,"name",{value:t,configurable:!0}),ns=0,yi=null;function nP(e){return bi(),e.children}Zl(nP,"FocusGuards");function bi(){K(()=>{yi||(yi={start:ed(),end:ed()});const{start:e,end:t}=yi;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),ns++,()=>{ns===1&&(yi?.start.remove(),yi?.end.remove(),yi=null),ns=Math.max(0,ns-1)}},[])}Zl(bi,"useFocusGuards");function ed(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}Zl(ed,"createFocusGuard");var an=function(){return an=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},an.apply(this,arguments)};function Hh(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function rP(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,o;r<i;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}var rs="right-scroll-bar-position",is="width-before-scroll-bar",iP="with-scroll-bars-hidden",oP="--removed-body-scroll-bar-size";function td(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function aP(e,t){var n=x(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=t,n.facade}var sP=typeof window<"u"?It:K,Kh=new WeakMap;function cP(e,t){var n=aP(t||null,function(r){return e.forEach(function(i){return td(i,r)})});return sP(function(){var r=Kh.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||td(c,null)}),o.forEach(function(c){i.has(c)||td(c,s)})}Kh.set(n,e)},[e]),n}function lP(e){return e}function dP(e,t){t===void 0&&(t=lP);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var o=t(i,r);return n.push(o),function(){n=n.filter(function(s){return s!==o})}},assignSyncMedium:function(i){for(r=!0;n.length;){var o=n;n=[],o.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var o=[];if(n.length){var s=n;n=[],s.forEach(i),o=n}var c=function(){var d=o;o=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){o.push(d),l()},filter:function(d){return o=o.filter(d),n}}}}}function uP(e){e===void 0&&(e={});var t=dP(null);return t.options=an({async:!0,ssr:!1},e),t}var Vh=function(e){var t=e.sideCar,n=Hh(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return b(r,an({},n))};Vh.isSideCarExport=!0;function pP(e,t){return e.useMedium(t),Vh}var zh=uP(),nd=function(){},os=J(function(e,t){var n=q(null),r=x({onScrollCapture:nd,onWheelCapture:nd,onTouchMoveCapture:nd}),i=r[0],o=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,f=e.sideCar,m=e.noRelative,v=e.noIsolation,g=e.inert,h=e.allowPinchZoom,y=e.as,w=y===void 0?"div":y,_=e.gapMode,I=Hh(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),P=f,k=cP([n,t]),A=an(an({},I),i);return b(z,null,u&&b(P,{sideCar:zh,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:g,setCallbacks:o,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?Pr(Ir.only(c),an(an({},A),{ref:k})):b(w,an({},A,{className:l,ref:k}),c))});os.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},os.classNames={fullWidth:is,zeroRight:rs};var Wh,fP=function(){if(Wh)return Wh;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function mP(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=fP();return t&&e.setAttribute("nonce",t),e}function hP(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function gP(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var vP=function(){var e=0,t=null;return{add:function(n){e==0&&(t=mP())&&(hP(t,n),gP(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},yP=function(){var e=vP();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Jh=function(){var e=yP(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},bP={left:0,top:0,right:0,gap:0},rd=function(e){return parseInt(e||"",10)||0},_P=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],i=t[e==="padding"?"paddingRight":"marginRight"];return[rd(n),rd(r),rd(i)]},wP=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return bP;var t=_P(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},SP=Jh(),So="data-scroll-locked",CP=function(e,t,n,r){var i=e.left,o=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
|
|
2
|
+
.`.concat(iP,` {
|
|
3
3
|
overflow: hidden `).concat(r,`;
|
|
4
4
|
padding-right: `).concat(c,"px ").concat(r,`;
|
|
5
5
|
}
|
|
6
|
-
body[`).concat(
|
|
6
|
+
body[`).concat(So,`] {
|
|
7
7
|
overflow: hidden `).concat(r,`;
|
|
8
8
|
overscroll-behavior: contain;
|
|
9
9
|
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
10
10
|
padding-left: `.concat(i,`px;
|
|
11
|
-
padding-top: `).concat(
|
|
11
|
+
padding-top: `).concat(o,`px;
|
|
12
12
|
padding-right: `).concat(s,`px;
|
|
13
13
|
margin-left:0;
|
|
14
14
|
margin-top:0;
|
|
@@ -16,99 +16,96 @@
|
|
|
16
16
|
`),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
.`).concat(
|
|
19
|
+
.`).concat(rs,` {
|
|
20
20
|
right: `).concat(c,"px ").concat(r,`;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
.`).concat(
|
|
23
|
+
.`).concat(is,` {
|
|
24
24
|
margin-right: `).concat(c,"px ").concat(r,`;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
.`).concat(
|
|
27
|
+
.`).concat(rs," .").concat(rs,` {
|
|
28
28
|
right: 0 `).concat(r,`;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
.`).concat(
|
|
31
|
+
.`).concat(is," .").concat(is,` {
|
|
32
32
|
margin-right: 0 `).concat(r,`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
body[`).concat(
|
|
36
|
-
`).concat(
|
|
35
|
+
body[`).concat(So,`] {
|
|
36
|
+
`).concat(oP,": ").concat(c,`px;
|
|
37
37
|
}
|
|
38
|
-
`)},
|
|
38
|
+
`)},Yh=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},IP=function(){K(function(){return document.body.setAttribute(So,(Yh()+1).toString()),function(){var e=Yh()-1;e<=0?document.body.removeAttribute(So):document.body.setAttribute(So,e.toString())}},[])},PP=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;IP();var o=Re(function(){return wP(i)},[i]);return b(SP,{styles:CP(o,!t,i,n?"":"!important")})},id=!1;if(typeof window<"u")try{var as=Object.defineProperty({},"passive",{get:function(){return id=!0,!0}});window.addEventListener("test",as,as),window.removeEventListener("test",as,as)}catch{id=!1}var _i=id?{passive:!1}:!1,RP=function(e){return e.tagName==="TEXTAREA"},Xh=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!RP(e)&&n[t]==="visible")},kP=function(e){return Xh(e,"overflowY")},TP=function(e){return Xh(e,"overflowX")},Qh=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),Zh(e,r)){var i=eg(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},NP=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},EP=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Zh=function(e,t){return e==="v"?kP(t):TP(t)},eg=function(e,t){return e==="v"?NP(t):EP(t)},AP=function(e,t){return e==="h"&&t==="rtl"?-1:1},xP=function(e,t,n,r,i){var o=AP(e,window.getComputedStyle(t).direction),s=o*r,c=n.target,l=t.contains(c),d=!1,u=s>0,p=0,f=0;do{if(!c)break;var m=eg(e,c),v=m[0],g=m[1]-m[2]-o*v;(v||g)&&Zh(e,c)&&(p+=g,f+=v);var h=c.parentNode;c=h&&h.nodeType===Node.DOCUMENT_FRAGMENT_NODE?h.host:h}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(u&&(i&&Math.abs(p)<1||!i&&s>p)||!u&&(i&&Math.abs(f)<1||!i&&-s>f))&&(d=!0),d},ss=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},tg=function(e){return[e.deltaX,e.deltaY]},ng=function(e){return e&&"current"in e?e.current:e},DP=function(e,t){return e[0]===t[0]&&e[1]===t[1]},$P=function(e){return`
|
|
39
39
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
40
40
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
41
|
-
`)},AN=0,jr=[];function xN(e){var t=B([]),n=B([0,0]),r=B(),i=x(AN++)[0],a=x(df)[0],s=B(e);J(function(){s.current=e},[e]),J(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var h=QC([e.lockRef.current],(e.shards||[]).map(vf),!0).filter(Boolean);return h.forEach(function(v){return v.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),h.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=se(function(h,v){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var w=Co(h),b=n.current,S="deltaX"in h?h.deltaX:b[0]-w[0],C="deltaY"in h?h.deltaY:b[1]-w[1],T,P=h.target,k=Math.abs(S)>Math.abs(C)?"h":"v";if("touches"in h&&k==="h"&&P.type==="range")return!1;var M=window.getSelection(),U=M&&M.anchorNode;if(U&&(U===P||U.contains(P)))return!1;var E=mf(k,P);if(!E)return!0;if(E?T=k:(T=k==="v"?"h":"v",E=mf(k,P)),!E)return!1;if(!r.current&&"changedTouches"in h&&(S||C)&&(r.current=T),!T)return!0;var j=r.current||T;return kN(j,v,h,j==="h"?S:C,!0)},[]),l=se(function(h){var v=h;if(!(!jr.length||jr[jr.length-1]!==a)){var w="deltaY"in v?gf(v):Co(v),b=t.current.filter(function(C){return C.name===v.type&&(C.target===v.target||v.target===C.shadowParent)&&EN(C.delta,w)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var S=(s.current.shards||[]).map(vf).filter(Boolean).filter(function(C){return C.contains(v.target)});(S.length>0?c(v,S[0]):!s.current.noIsolation)&&v.cancelable&&v.preventDefault()}}},[]),d=se(function(h,v,w,b){var S={name:h,delta:v,target:w,should:b,shadowParent:RN(w)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(C){return C!==S})},1)},[]),u=se(function(h){n.current=Co(h),r.current=void 0},[]),p=se(function(h){d(h.type,gf(h),h.target,c(h,e.lockRef.current))},[]),m=se(function(h){d(h.type,Co(h),h.target,c(h,e.lockRef.current))},[]);J(function(){return jr.push(a),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:m}),document.addEventListener("wheel",l,Or),document.addEventListener("touchmove",l,Or),document.addEventListener("touchstart",u,Or),function(){jr=jr.filter(function(h){return h!==a}),document.removeEventListener("wheel",l,Or),document.removeEventListener("touchmove",l,Or),document.removeEventListener("touchstart",u,Or)}},[]);var f=e.removeScrollBar,g=e.inert;return y(Z,null,g?y(a,{styles:PN(i)}):null,f?y(_N,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function RN(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var DN=sN(cf,xN),Ui=V(function(e,t){return y(wo,Kt({},e,{ref:t,sideCar:DN}))});Ui.classNames=wo.classNames;var LN=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Fr=new WeakMap,No=new WeakMap,To={},el=0,yf=function(e){return e&&(e.host||yf(e.parentNode))},$N=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=yf(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},MN=function(e,t,n,r){var i=$N(t,Array.isArray(e)?e:[e]);To[n]||(To[n]=new WeakMap);var a=To[n],s=[],c=new Set,l=new Set(i),d=function(p){!p||c.has(p)||(c.add(p),d(p.parentNode))};i.forEach(d);var u=function(p){!p||l.has(p)||Array.prototype.forEach.call(p.children,function(m){if(c.has(m))u(m);else try{var f=m.getAttribute(r),g=f!==null&&f!=="false",h=(Fr.get(m)||0)+1,v=(a.get(m)||0)+1;Fr.set(m,h),a.set(m,v),s.push(m),h===1&&g&&No.set(m,!0),v===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(w){console.error("aria-hidden: cannot operate on ",m,w)}})};return u(t),c.clear(),el++,function(){s.forEach(function(p){var m=Fr.get(p)-1,f=a.get(p)-1;Fr.set(p,m),a.set(p,f),m||(No.has(p)||p.removeAttribute(r),No.delete(p)),f||p.removeAttribute(n)}),el--,el||(Fr=new WeakMap,Fr=new WeakMap,No=new WeakMap,To={})}},Io=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||LN(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),MN(r,i,n,"aria-hidden")):function(){return null}},ko="Dialog",[bf,Z1]=st(ko),[ON,Dt]=bf(ko),_f=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!0}=e,c=B(null),l=B(null),[d,u]=It({prop:r,defaultProp:i??!1,onChange:a,caller:ko});return o(ON,{scope:t,triggerRef:c,contentRef:l,contentId:ct(),titleId:ct(),descriptionId:ct(),open:d,onOpenChange:u,onOpenToggle:se(()=>u(p=>!p),[u]),modal:s,children:n})};_f.displayName=ko;var wf="DialogTrigger",jN=V((e,t)=>{const{__scopeDialog:n,...r}=e,i=Dt(wf,n),a=Se(t,i.triggerRef);return o(pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":rl(i.open),...r,ref:a,onClick:Q(e.onClick,i.onOpenToggle)})});jN.displayName=wf;var tl="DialogPortal",[FN,Sf]=bf(tl,{forceMount:void 0}),Cf=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=Dt(tl,t);return o(FN,{scope:t,forceMount:n,children:qt.map(r,s=>o(nt,{present:n||a.open,children:o(Zn,{asChild:!0,container:i,children:s})}))})};Cf.displayName=tl;var Eo="DialogOverlay",Nf=V((e,t)=>{const n=Sf(Eo,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Dt(Eo,e.__scopeDialog);return a.modal?o(nt,{present:r||a.open,children:o(UN,{...i,ref:t})}):null});Nf.displayName=Eo;var BN=Xn("DialogOverlay.RemoveScroll"),UN=V((e,t)=>{const{__scopeDialog:n,...r}=e,i=Dt(Eo,n);return o(Ui,{as:BN,allowPinchZoom:!0,shards:[i.contentRef],children:o(pe.div,{"data-state":rl(i.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),er="DialogContent",Tf=V((e,t)=>{const n=Sf(er,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=Dt(er,e.__scopeDialog);return o(nt,{present:r||a.open,children:a.modal?o(GN,{...i,ref:t}):o(HN,{...i,ref:t})})});Tf.displayName=er;var GN=V((e,t)=>{const n=Dt(er,e.__scopeDialog),r=B(null),i=Se(t,n.contentRef,r);return J(()=>{const a=r.current;if(a)return Io(a)},[]),o(If,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Q(e.onCloseAutoFocus,a=>{a.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Q(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&a.preventDefault()}),onFocusOutside:Q(e.onFocusOutside,a=>a.preventDefault())})}),HN=V((e,t)=>{const n=Dt(er,e.__scopeDialog),r=B(!1),i=B(!1);return o(If,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||n.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;n.triggerRef.current?.contains(s)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),If=V((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...s}=e,c=Dt(er,n),l=B(null),d=Se(t,l);return yo(),o(Z,{children:[o(Fi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o(Qn,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":rl(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),o(Z,{children:[o(WN,{titleId:c.titleId}),o(JN,{contentRef:l,descriptionId:c.descriptionId})]})]})}),nl="DialogTitle",qN=V((e,t)=>{const{__scopeDialog:n,...r}=e,i=Dt(nl,n);return o(pe.h2,{id:i.titleId,...r,ref:t})});qN.displayName=nl;var kf="DialogDescription",KN=V((e,t)=>{const{__scopeDialog:n,...r}=e,i=Dt(kf,n);return o(pe.p,{id:i.descriptionId,...r,ref:t})});KN.displayName=kf;var Ef="DialogClose",VN=V((e,t)=>{const{__scopeDialog:n,...r}=e,i=Dt(Ef,n);return o(pe.button,{type:"button",...r,ref:t,onClick:Q(e.onClick,()=>i.onOpenChange(!1))})});VN.displayName=Ef;function rl(e){return e?"open":"closed"}var Pf="DialogTitleWarning",[eF,Af]=_C(Pf,{contentName:er,titleName:nl,docsSlug:"dialog"}),WN=({titleId:e})=>{const t=Af(Pf),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
42
|
-
|
|
43
|
-
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
44
|
-
|
|
45
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return J(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},zN="DialogDescriptionWarning",JN=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Af(zN).contentName}}.`;return J(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},YN=_f,XN=Cf,QN=Nf,ZN=Tf;function Br({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:a=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:m,overlayId:f,slotId:g}){return o(YN,{modal:a,open:p,onOpenChange:u,children:p?o(XN,{children:[o(QN,{asChild:!0,children:o("div",{className:m,id:f})}),o(ZN,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:o("div",{role:"dialog",className:r,id:i,onClick:h=>{h.target===h.currentTarget&&u(!1)},tabIndex:-1,children:n??(g?o("div",{id:g}):null)})})]}):null})}var xf=500,Po=null,Gi=null,Hi=null;function qi(e){return Gi?Gi(e)?(Hi=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Hi=document.activeElement instanceof HTMLElement?document.activeElement:null,Po=e,!0)}function rt(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Rf(e){const t=e.indexOf(":"),n=e.slice(0,t),r=e.slice(t+1);return r?n==="identity"?{recipientKind:"identity",identityId:r}:n==="team"?{recipientKind:"team",teamId:r}:null:null}function il(e){return e.recipientKind==="identity"?rt({recipientKind:"identity",identityId:e.identityId}):rt({recipientKind:"team",teamId:e.teamId})}function eT(e,t){return il(e)===rt(t)}function Df(e,t){return e instanceof _c?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Lf({checked:e,description:t,disabled:n,label:r,onChange:i}){const a=`recipient-policy-choice-${Lr()}`;return o("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:a,children:[o("input",{checked:e,disabled:n,id:a,onChange:i,type:"checkbox"}),o("span",{children:[o("strong",{className:"recipient-policy-management-name",children:r}),o("span",{className:"small recipient-policy-management-description",children:t})]})]})}function tT(e,t){const n=e.teamMemberships.filter(s=>s.status==="active"),r=new Map(e.identities.map(s=>[s.identityId,s])),i=[...e.teams.filter(s=>s.status==="active").map(s=>{const c=n.filter(l=>l.teamId===s.teamId).map(l=>r.get(l.identityId)?.displayName).filter(l=>!!l);return{key:rt({recipientKind:"team",teamId:s.teamId}),label:s.displayName,description:`Team · ${c.length.toLocaleString()} current ${c.length===1?"member":"members"}${c.length?`: ${c.join(", ")}`:""}`}}),...e.identities.filter(s=>s.status==="active"||s.status==="pending").map(s=>({key:rt({recipientKind:"identity",identityId:s.identityId}),label:s.displayName,description:`Identity · ${s.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return i;const a=new Set(i.map(s=>s.key));for(const s of e.projectRecipients){if(s.status!=="active"||s.canonicalProjectIdentity!==t.projectId)continue;const c=il(s);if(!a.has(c)){if(s.recipientKind==="team"){const l=e.teams.find(d=>d.teamId===s.teamId);i.push({key:c,label:l?.displayName??"Unavailable Team",description:`${l?.status==="archived"?"Archived Team":"Unavailable Team"} · existing access can only be removed`})}else{const l=r.get(s.identityId);i.push({key:c,label:l?.displayName??"Unavailable Identity",description:`${l?.status==="merged"?"Merged Identity":"Unavailable Identity"} · existing access can only be removed`})}a.add(c)}}return i}function $f(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function nT(e,t){const n=t.projectRecipients.filter(r=>r.status==="active");return e.mode==="project-add"?[]:e.mode==="project-manage"?n.filter(r=>r.canonicalProjectIdentity===e.projectId).map(il):n.filter(r=>eT(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function rT(e,t,n){const r=t.mode==="recipient-add"?e.filter(s=>!n.includes(s.canonicalProjectIdentity)):e,i=r.map(s=>({...s,description:`${s.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return i;const a=new Set(r.map(s=>s.canonicalProjectIdentity));for(const s of n)a.has(s)||i.push({canonicalProjectIdentity:s,displayName:s,existingMemoryCount:0,description:"Unavailable Project · existing access can only be removed"});return i}function iT(e,t,n){return e.mode==="project-add"?$f(e).flatMap(r=>t.flatMap(i=>{const a=Rf(i);return a?[{canonicalProjectIdentity:r,recipient:a,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Rf(r);return!i||n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:e.projectId,recipient:i,action:t.includes(r)?"add":"remove"}]}):e.mode==="recipient-add"?t.map(r=>({canonicalProjectIdentity:r,recipient:e.recipient,action:"add"})):[...new Set([...n,...t])].flatMap(r=>n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:r,recipient:e.recipient,action:t.includes(r)?"add":"remove"}])}function aT(e){return e.mode==="project-add"?{title:"Add recipient access",description:"Choose the Teams and Identities that should receive the selected Projects.",legend:"Choose recipients"}:e.mode==="project-manage"?{title:"Manage Project recipients",description:"Choose exactly which Teams and Identities receive this Project.",legend:"Project recipients"}:e.mode==="recipient-add"?{title:"Add Projects",description:"Choose additional Projects for this recipient. Existing access cannot be removed here.",legend:"Additional Projects"}:{title:"Manage recipient Projects",description:"Choose exactly which Projects this recipient receives.",legend:"Recipient Projects"}}function Mf(e,t){let n=!1,r=!1,i=!1,a=!1;const s=rt(t);for(const c of e){const{change:l,outcome:d}=c;rt(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(a=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!a?"Already has access":a&&!i?"Already without access":"No changes"}function oT(e){const t=new Set(e.selectedRecipients.map(rt)),n=new Map;for(const r of e.normalizedChanges){const i=rt(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function sT(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function cT({preview:e,recipientLabels:t}){const n=sT(e.effectiveDevices),r=oT(e);return o("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[o("section",{"aria-labelledby":"recipient-policy-review-projects",children:[o("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),o("ul",{children:e.projects.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:i.displayName}),o("span",{children:[" ","— Access changes affect ",i.existingMemoryCount.toLocaleString()," existing memories",i.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},i.canonicalProjectIdentity))})]}),o("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[o("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),o("ul",{children:[e.selectedRecipients.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:i.displayName})," ",o("span",{children:["— ",Mf(e.outcomes,i)," · "]}),i.recipientKind==="identity"?o("span",{children:"Identity · locally verified"}):o("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",i.currentMembers.length.toLocaleString()," current"," ",i.currentMembers.length===1?"member":"members",i.currentMembers.length?o(Z,{children:[":"," ",o("span",{className:"recipient-policy-management-member-names",children:i.currentMembers.map(a=>a.displayName).join(", ")})]}):null,". Future Team members"," ",i.futureMembersInherit?"inherit":"do not inherit"," access."]})]},rt(i))),r.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:t.get(rt(i))??(i.recipientKind==="team"?i.teamId:i.identityId)})," ",o("span",{children:["— ",Mf(e.outcomes,i)," ·"," ",i.recipientKind==="team"?"Team":"Identity"]})]},rt(i)))]})]}),o("section",{"aria-labelledby":"recipient-policy-review-availability",children:[o("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),n.length?o(Z,{children:[o("p",{children:["After the update, the affected Projects will be available on"," ",n.length.toLocaleString()," current"," ",n.length===1?"device":"devices"," across all recipients."]}),o("ul",{children:n.map(i=>o("li",{className:"recipient-policy-management-name",children:i.displayName},i.deviceId))})]}):o("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Change details"}),o("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?o(Z,{children:[o("p",{className:"small recipient-policy-management-detail-label",children:o("strong",{children:"Unchanged Projects"})}),o("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(i=>o("li",{className:"recipient-policy-management-name",children:i.displayName},i.canonicalProjectIdentity))})]}):null]})]})}function lT({preview:e,result:t}){const n=t.status==="applied"?"Applied":t.status==="not_found"?"Not found":`${t.status.charAt(0).toUpperCase()}${t.status.slice(1)}`;return o("div",{className:"sync-dialog-stack recipient-policy-management-result",children:o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Technical details"}),o("p",{children:["Status: ",n,". Writes: ",t.writeCount.toLocaleString(),"."]}),t.errorCode?o("p",{children:["Error code: ",t.errorCode.replaceAll("_"," "),"."]}):null,t.outcomes.length?o("ul",{children:t.outcomes.map(r=>{const i=e.projects.find(s=>s.canonicalProjectIdentity===r.change.canonicalProjectIdentity)?.displayName??"Selected Project",a=e.selectedRecipients.find(s=>rt(s)===rt(r.change.recipient))?.displayName??(r.change.recipient.recipientKind==="team"?"Team":"Identity");return o("li",{children:[r.change.action==="add"?"Add":"Remove"," ",a," ",r.change.action==="add"?"to":"from"," ",i,":"," ",r.outcome.replaceAll("_"," ")]},`${r.change.canonicalProjectIdentity}:${rt(r.change.recipient)}`)})}):null]})})}function dT({intent:e,options:t,projects:n}){const[r,i]=x(null),[a,s]=x([]),[c,l]=x([]),[d,u]=x(null),[p,m]=x(null),[f,g]=x(null),[h,v]=x(""),[w,b]=x(!1),S=B(!1),C=Re(()=>tT(e,r),[e,r]),T=Re(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName])]),[e]),P=Re(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]);if(J(()=>{if(Gi=Y=>{if(S.current)return!1;const he=nT(Y,e);return i(Y),l(he),s(Y.mode==="recipient-add"?[]:he),u(null),m(null),g(null),v(""),b(!1),S.current=!1,!0},Po){const Y=Po;Po=null,Gi(Y)}return()=>{Gi=null}},[e]),J(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const k=aT(r),M=$f(r),U=r.mode==="recipient-manage"?!1:M.some(Y=>!P.has(Y)),E=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!C.some(Y=>Y.key===rt(r.recipient)),j=t.loading||t.loadError||U||E,O=iT(r,a,c),q=O.length>xf,L=(r.mode==="project-add"||r.mode==="recipient-add")&&a.length===0,R=r.mode!=="project-add"&&r.mode!=="recipient-add"&&O.length===0,A=rT(n,r,c),I=p?.status==="applied",D=p?I?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":k.title,F=p?I?"The reviewed recipient access changes are applied.":"Some reviewed recipient access changes were not applied. Review the technical details.":d?"Confirm the exact Projects, recipients, and resulting access.":k.description,K=()=>{S.current||(i(null),u(null),m(null),g(null),v(""))},ce=Y=>{s(he=>he.includes(Y)?he.filter(ne=>ne!==Y):[...he,Y]),g(null),v("")},ie=async()=>{if(!(j||L||R||q||S.current)){S.current=!0,b(!0),g(null),v("Reviewing exact recipient access changes.");try{u(await ES({version:1,changes:O})),v("Review ready. Confirm the exact changes.")}catch(Y){g(Df(Y,"Unable to review recipient access changes.")),v("")}finally{S.current=!1,b(!1)}}},re=async()=>{if(!(!d||S.current)){S.current=!0,b(!0),g(null),v("Saving recipient access changes.");try{const Y=await PS({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(Y),v("");try{await t.onCommitted?.(Y)}catch{g("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof _c&&(u(null),v("")),g(Df(Y,"Unable to save recipient access changes."))}finally{S.current=!1,b(!1)}}};let ye=null;return t.loading?ye="Loading the complete recipient access inventory…":t.loadError?ye="The complete recipient access inventory is unavailable. Refresh and try again.":U?ye="One selected Project is no longer available. Refresh and try again.":E&&(ye="This recipient is no longer available. Refresh and try again."),o(Br,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const he=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ne=Hi?.isConnected?Hi:document.getElementById(he);ne instanceof HTMLElement&&ne.focus(),Hi=null},onOpenAutoFocus:Y=>{const he=document.getElementById("recipient-policy-management-title");he&&(Y.preventDefault(),he.focus())},onOpenChange:Y=>{Y||K()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:o("div",{"aria-busy":w||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:D}),o(Oi,{ariaLabel:`Close ${D}`,className:"modal-close-button recipient-policy-management-target",disabled:w,onClick:K})]}),o("div",{className:"modal-body recipient-policy-management-selection",children:[o("p",{className:"small",id:"recipient-policy-management-description",children:F}),ye?o("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:ye}):p&&d?o(lT,{preview:d,result:p}):d?o(cT,{preview:d,recipientLabels:T}):r.mode==="recipient-add"||r.mode==="recipient-manage"?o("fieldset",{className:"sync-dialog-radio-list",disabled:w,children:[o("legend",{children:k.legend}),A.length?A.map(Y=>o(Lf,{checked:a.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:w,label:Y.displayName,onChange:()=>ce(Y.canonicalProjectIdentity)},Y.canonicalProjectIdentity)):o("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):o("fieldset",{className:"sync-dialog-radio-list",disabled:w,children:[o("legend",{children:k.legend}),C.length?C.map(Y=>o(Lf,{checked:a.includes(Y.key),description:Y.description,disabled:w,label:Y.label,onChange:()=>ce(Y.key)},Y.key)):o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:o("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:h}),f?o("p",{"aria-live":"assertive",role:"alert",children:f}):null,q?o("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",O.length.toLocaleString()," access changes. Review at most ",xf.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),o("div",{className:"modal-footer recipient-policy-management-actions",children:[o("button",{className:"settings-button recipient-policy-management-target",disabled:w,onClick:d&&!p?()=>{u(null),v("")}:K,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!ye?o("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:w||!d&&(L||R||q),onClick:()=>{d?re():ie()},type:"button",children:w?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Of(e,t,n,r={}){Ge(o(dT,{intent:n,options:r,projects:t}),e)}function Ao(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function uT(e){const t=new Map;for(const n of e)n.read_only_reason==="peer_received"&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0,latestSessionAt:n.latest_session_at??null});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function xo(e){const t=new Map;for(const n of e)Ao(n)&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function jf({detailRowCount:e=3,label:t}){return o(Z,{children:[o("span",{className:"sr-only",role:"status",children:t}),o("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>o("div",{"aria-hidden":"true",className:"loading-card",children:[o("div",{className:"loading-card-header",children:[o("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),o("span",{className:"loading-card-badge"})]}),o("div",{className:"loading-card-details",children:Array.from({length:e},(i,a)=>o("div",{className:"loading-card-detail",children:[o("span",{className:"loading-card-line loading-card-label"}),o("span",{className:`loading-card-line ${(r+a)%2?"w-45":"w-60"}`})]},a))})]},r))})]})}function pT(e){return e.state!=="configured"}function Ff(e){return e?.items.filter(pT)??[]}function Ro(e,t){return e.truncated?{blocked:!0,recovery:"Refresh Devices after the complete inventory is available."}:e.coordinatorEvidence.availability==="available"?{blocked:!1,recovery:null}:e.coordinatorEvidence.safeErrorCode==="coordinator_not_configured"&&t.isLocal?{blocked:!1,recovery:null}:{blocked:!0,recovery:"Refresh Devices after coordinator device information is available."}}var mT=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,fT=/^(?:actor|device|identity|local):\S+$/iu,hT=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,gT=/^pending[_-]\S+$/iu,vT=/^[a-f0-9]{12,64}$/iu;function Bf(e){return[mT,fT,hT,gT,vT].some(t=>t.test(e))}function Ur(e){if(typeof e!="string"||[...e].some(n=>/[\p{Cc}\p{Cf}]/u.test(n)))return"";const t=e.replace(/\s+/gu," ").trim();return!t||[...t].length>120||Bf(t)?"":t}var Gr=null,Hr=null;function Do(e=[],t=""){if(Hr){const n=Hr(e,t);return n||(Gr=null),n}return Gr={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Uf(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Gf(e,t){if(!(e instanceof Error))return t;switch(e.message){case"team_sharing_not_configured":return"Set up Team sharing before creating an invitation.";case"team_selection_ambiguous":return"Choose one active Team in settings before creating an invitation.";case"project_selection_ambiguous":return"One selected project has a name collision. Review its project identity first.";case"project_selection_unsupported":case"project_selection_unknown":case"reviewed_project_set_changed":return"The selected projects changed. Review the invitation again.";default:return t}}function yT(e){const t=`share-project-${Lr()}`,n=Uf(e.project);return o("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[o("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),o("span",{children:[o("strong",{children:e.project.display_project}),o("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function bT({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?o("p",{className:"small",children:"This invitation will use the existing teammate."}):null,o("ul",{children:e.projects.map(t=>o("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),o("p",{children:o("strong",{children:"No other projects will be shared."})})]})}function _T({projects:e,inventoryError:t}){const[n,r]=x(!1),[i,a]=x(""),[s,c]=x([]),[l,d]=x(null),[u,p]=x(null),[m,f]=x(null),[g,h]=x(!1),[v,w]=x(null),[b,S]=x(!1),C=Re(()=>e.filter(Uf),[e]);J(()=>{if(Hr=(E,j="")=>{if(t)return!1;const O=[...new Set(E)],q=O.some(L=>!C.some(R=>R.workspace_identity===L));return a(j.trim()),c(q?[]:O),S(q),d(null),p(null),f(q?"The original project selection is no longer available. Refresh Projects and try again.":null),w(null),r(!0),!0},Gr){const E=Gr;Gr=null,Hr(E.projectIds,E.teammateName)}return()=>{Hr=null}},[C,t]),J(()=>{t&&(Gr=null,r(!1),a(""),c([]),d(null),p(null),f(null),w(null),S(!1))},[t]);const T=()=>{g||r(!1)},P=E=>{c(j=>j.includes(E)?j.filter(O=>O!==E):[...j,E])},k=async()=>{if(f(null),!i.trim()){f("Enter your teammate's name.");return}if(s.length===0){f("Select at least one project.");return}h(!0);try{d(await LS({teammate_name:i.trim(),project_ids:s}))}catch(E){f(Gf(E,"Unable to review this invitation."))}finally{h(!1)}},M=async()=>{if(l){f(null),h(!0);try{p(await $S({teammate_name:l.teammate.display_name,project_ids:l.projects.map(E=>E.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(E){E instanceof Error&&E.message==="reviewed_project_set_changed"&&d(null),f(Gf(E,"Unable to create this invitation."))}finally{h(!1)}}},U=async()=>{if(u){f(null),w(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),w("Invite copied.")}catch(E){f(E instanceof Error?E.message:"Unable to copy the invitation.")}}};return o(Z,{children:[o("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||C.length===0,onClick:()=>Hr?.([]),type:"button",children:"Share projects"}),t?o("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?o(Br,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:E=>{E||T()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"project-share-title",children:"Share projects"}),o("button",{"aria-label":"Close Share projects",disabled:g,onClick:T,type:"button",children:"×"})]}),o("div",{"aria-busy":g,className:"modal-body",children:[o("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?o("div",{children:[o("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),o("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(E=>E.display_name).join(", "),"."]}),o("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),o("button",{className:"settings-button",onClick:()=>{U()},type:"button",children:"Copy invite"}),v?o("p",{role:"status",children:v}):null]}):l?o(bT,{preview:l}):o(Z,{children:[o("label",{className:"field",htmlFor:"project-share-teammate",children:[o("span",{children:"Who are you sharing with?"}),o("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:E=>a(E.currentTarget.value),type:"text",value:i})]}),o("fieldset",{className:"sync-dialog-radio-list",children:[o("legend",{children:"Select exact projects"}),e.map(E=>o(yT,{onToggle:P,project:E,selected:s.includes(E.workspace_identity)},E.workspace_identity))]})]}),m?o("p",{role:"alert",children:m}):null]}),o("div",{className:"modal-footer",children:[o("button",{className:"settings-button",disabled:g,onClick:T,type:"button",children:u?"Done":"Cancel"}),u?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:g||b,onClick:()=>{l?M():k()},type:"button",children:g?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Hf(e,t,n={}){Ge(o(_T,{inventoryError:n.inventoryError===!0,projects:t}),e)}function al(e){return Ur(String(e??"").trim())}function qr(e,t){const n=e.trim();return n?[...n].length>120?`${t} must use 120 characters or fewer.`:[...n].some(r=>/[\p{Cc}\p{Cf}]/u.test(r))?`${t} cannot include control or format characters.`:Bf(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function wT(e){return{...e,status:e.status==="pending_setup"?"pending_setup":void 0,setup_state:e.setup_state==="pending_inviter"||e.setup_state==="restart_required"?e.setup_state:void 0,restart_required:e.restart_required===!0,detail:typeof e.detail=="string"?e.detail:void 0,type:e.type==="project_share"?"project_share":void 0}}function Lo(e,t){return e instanceof Error?e.message==="reviewed_onboarding_stale"?"Invitation details changed. Review them again before creating it.":e.message==="recipient_invite_review_unavailable"?"The invitation review is unavailable. Ask the owner to create a new invitation.":e.message==="recipient_invite_intent_mismatch"?"The invitation details do not match the reviewed access. Ask the owner to create a new invitation.":e.message==="invite_identity_conflict"?"This device already belongs to a different Identity. Use a fresh device or ask the owner for the correct invitation.":e.message==="recipient_display_name_invalid"?"Enter a human-readable Identity name instead of an internal identifier.":e.message==="recipient_display_name_required"?"Enter an Identity display name before accepting.":e.message==="recipient_display_name_too_long"?"Use an Identity display name with 120 characters or fewer.":t:t}function Ki(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function ST({preview:e}){return e.projects.length===0?o("p",{className:"small",children:"No Projects are currently shared with this Team."}):o("ul",{children:e.projects.map(t=>o("li",{children:[o("strong",{children:t.displayName})," — ",Ki(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function CT({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),o(ST,{preview:e}),o("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),o("p",{children:o("strong",{children:"No other Projects will be shared through this invitation."})})]})}function NT({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"add-device-direct-projects",children:[o("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?o("ul",{children:t.map(r=>o("li",{children:[r.displayName," — ",Ki(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No Projects are shared directly."})]}),o("section",{"aria-labelledby":"add-device-team-projects",children:[o("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?o("ul",{children:n.map(r=>{const i=r.sources.filter(a=>a.kind==="team").map(a=>a.displayName);return o("li",{children:[r.displayName," — ",Ki(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):o("p",{className:"small",children:"No Projects are inherited through Teams."})]}),o("section",{"aria-labelledby":"add-device-excluded-projects",children:[o("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?o("ul",{children:e.excludedProjects.map(r=>o("li",{children:[r.displayName," — ",Ki(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No other Projects are excluded."}),o("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?o("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function qf({preview:e}){return e.journey==="team"?o(CT,{preview:e}):o(NT,{preview:e})}function TT({error:e,name:t,onChange:n}){return o("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[o("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),o("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?o("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function IT({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:a,recipientNameError:s}){const c=n.projects??[];return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"project-share-invitation-recipient",children:[o("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),o("p",{children:"Review these display names before importing the invitation."}),o("label",{className:"field",htmlFor:"project-share-recipient-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:a})]}),s?o("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,o("label",{className:"field",htmlFor:"project-share-device-name",children:[o("span",{children:"Device display name"}),o("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?o("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),o("section",{"aria-labelledby":"project-share-invitation-projects",children:[o("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?o("p",{children:["Invitation from ",n.inviter_name,"."]}):null,o("p",{children:["You will receive ",o("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?o("ul",{children:c.map((l,d)=>o("li",{children:[o("strong",{children:l.display_name})," —"," ",Ki(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):o("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),o("p",{children:o("strong",{children:"Accepting this invitation does not join a Team."})}),o("p",{children:o("strong",{children:"No other Projects are included."})})]})}function kT({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return o("div",{className:"sync-dialog-stack",children:[o("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):o("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function ET({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added";return o("section",{"aria-describedby":[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[o("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),o("div",{className:"recipient-policy-invitation-result-copy",children:[o("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?o("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?o("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Kf(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function PT({intent:e}){const t=e.teams.filter(G=>G.status==="active"),n=e.identities.filter(G=>G.status==="active"),[r,i]=x(null),[a,s]=x("team_member"),[c,l]=x(t[0]?.teamId??""),[d,u]=x(""),[p,m]=x(null),[f,g]=x(null),[h,v]=x(null),[w,b]=x(null),[S,C]=x(""),[T,P]=x(""),[k,M]=x(""),[U,E]=x(null),[j,O]=x(!1),[q,L]=x(""),[R,A]=x(""),I=B(null),D=B(0),F=B(""),K=B(!1);J(()=>{if(w){document.getElementById("recipient-invitation-result")?.focus();return}if(h){document.getElementById("project-share-invitation-result")?.focus();return}f?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[f,h,w]);const ce=()=>{D.current+=1,F.current="",K.current=!1,u(""),m(null),g(null),v(null),b(null),C(""),P(""),M(""),E(null),L(""),A("")},ie=(G,W)=>{ce(),I.current=W,i(G)},re=()=>{j||(i(null),ce())},ye=G=>{D.current+=1,F.current=G,u(G)},Y=G=>{s(G),l(G==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),ce()},he=async()=>{if(c){O(!0),A(""),L("Reviewing invitation…");try{m((await AS(Kf(a,c))).preview),L("Review ready. Confirm the invitation details.")}catch(G){A(Lo(G,"Unable to review this invitation.")),L("")}finally{O(!1)}}},ne=async()=>{if(p){O(!0),A(""),L("Creating invitation…");try{E(await xS({...Kf(a,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),L("Invitation created.")}catch(G){G instanceof Error&&G.message==="reviewed_onboarding_stale"&&m(null),A(Lo(G,"Unable to create this invitation.")),L("")}finally{O(!1)}}},ke=async()=>{const G=F.current.trim(),W=D.current;if(!G){A("Paste an invitation first.");return}const be=()=>D.current===W&&F.current.trim()===G;O(!0),A(""),L("Reviewing invitation…");try{const Ce=await Ep(G);if(!be())return;g(Ce),Ce.kind==="team_member"?C(al(Ce.recipient_name)):Ce.kind==="project_share_invite"&&(P(al(Ce.recipient_name)),M(al(Ce.device_name))),L(Ce.kind==="add_device"?(Ce.onboarding?.projects?.length??0)>0?"Review ready. Existing shared Projects sync to the invited device only after the owner’s device completes access setup. Confirm before accepting.":"Review ready. Confirm before accepting.":Ce.kind==="team_member"?"Review ready. Confirm before accepting.":Ce.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced Team administration to continue with this invitation.")}catch(Ce){if(!be())return;A(Lo(Ce,"Unable to review this invitation.")),L("")}finally{O(!1)}},ge=async()=>{if(!(j||K.current||w)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(qr(T,"Identity display name")||qr(k,"Device display name")))&&!(f.kind==="team_member"&&qr(S,"Identity display name"))){K.current=!0,O(!0),A(""),L("Accepting invitation…");try{const G=f.kind==="project_share_invite"?await yc(d.trim(),{recipient_name:T.trim(),device_name:k.trim()}):await yc(d.trim(),{...f.kind==="team_member"?{recipient_name:S.trim()}:{},device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest});if(f.kind==="project_share_invite")v(wT(G)),L("");else{const W=f.kind;b({kind:W,restartRequired:G.restart_required===!0||G.setup_state==="restart_required",detail:(typeof G.detail=="string"?G.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:W==="add_device"&&(f.onboarding?.projects?.length??0)>0}),L("")}}catch(G){K.current=!1;const W=G instanceof Error?G.message.trim():"";A(Lo(G,f.kind==="project_share_invite"&&W?W:"Unable to accept this invitation.")),L("")}finally{O(!1)}}},ae=async()=>{const G=U?.invite.link||U?.invite.encoded||"";if(!G){A("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(G),L("Invitation copied.")}catch{A("Unable to copy the invitation.")}},xe=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,de=f?.kind==="project_share_invite"?f:null,Te=f?.kind==="team_member"?qr(S,"Identity display name"):"",ue=de?qr(T,"Identity display name"):"",z=de?qr(k,"Device display name"):"";return o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Create an invitation"}),o("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),o("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:G=>{Y("team_member"),ie("create",G.currentTarget)},type:"button",children:"Invite Team member"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:G=>{Y("add_device"),ie("create",G.currentTarget)},type:"button",children:"Add a device"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>Do(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Accept an invitation"}),o("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:G=>ie("accept",G.currentTarget),type:"button",children:"Review invitation"}),o("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?o(Br,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:G=>{G.preventDefault(),I.current?.focus(),I.current=null},onOpenAutoFocus:G=>{G.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:G=>{G||re()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:o("div",{"aria-busy":j,className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-invitation-title",tabIndex:-1,children:w?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),o(Oi,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:j,onClick:re})]}),o("div",{className:"modal-body",children:[o("p",{className:"small",id:"recipient-invitation-description",children:w?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!U?o("label",{className:"field",htmlFor:"recipient-invitation-target",children:[o("span",{children:a==="team_member"?"Team":"Identity"}),o("select",{id:"recipient-invitation-target",onChange:G=>l(G.currentTarget.value),value:c,children:(a==="team_member"?t:n).map(G=>o("option",{value:"teamId"in G?G.teamId:G.identityId,children:G.displayName},"teamId"in G?G.teamId:G.identityId))})]}):r==="accept"&&!f&&!w?o("label",{className:"field",htmlFor:"recipient-invitation-value",children:[o("span",{children:"Invitation"}),o("textarea",{id:"recipient-invitation-value",onInput:G=>{ye(G.currentTarget.value),g(null),v(null),L(""),A("")},rows:5,value:d})]}):null,p?o(qf,{preview:p}):null,xe&&!w?o(qf,{preview:xe}):null,f?.kind==="team_member"&&!w?o(TT,{error:Te,name:S,onChange:G=>{C(G),A("")}}):null,de&&!h?o(IT,{deviceName:k,deviceNameError:z,invite:de,onDeviceNameChange:G=>{M(G),A("")},onRecipientNameChange:G=>{P(G),A("")},recipientName:T,recipientNameError:ue}):null,h?o(kT,{result:h}):null,w?o(ET,{result:w}):null,U?o("div",{children:[o("p",{children:"Share the invitation with the recipient."}),o("button",{className:"settings-button",onClick:()=>{ae()},type:"button",children:"Copy invitation"})]}):null,f?.kind==="legacy_team_invite"?o("p",{children:"Use Advanced Team administration to review and import this invitation."}):null,o("p",{"aria-live":"polite",className:"small",role:"status",children:q}),R?o("p",{"aria-live":"assertive",role:"alert",children:R}):null]}),o("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button",disabled:j,onClick:re,type:"button",children:U||h||w?"Done":"Cancel"}),r==="create"&&!U?o("button",{className:"settings-button sync-dialog-confirm",disabled:j||!c,onClick:()=>{p?ne():he()},type:"button",children:j?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!f&&!w?o("button",{className:"settings-button sync-dialog-confirm",disabled:j,onClick:()=>{ke()},type:"button",children:j?"Reviewing…":"Review invitation"}):xe&&!w||de&&!h?o("button",{className:"settings-button sync-dialog-confirm",disabled:j||!!(f?.kind==="team_member"&&Te)||!!(de&&(!de.projects?.length||ue||z)),onClick:()=>{ge()},type:"button",children:j?"Accepting…":de?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}var Vf={needs_setup:"Needs setup",in_progress:"In progress",stale:"Needs setup",ready:"Ready"},Wf={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention",ready:""},AT={role:"list"},xT={role:"listitem"};function RT(e){return typeof e=="string"&&Object.hasOwn(Vf,e)?Vf[e]:"Needs setup"}function DT(e){return typeof e=="string"&&Object.hasOwn(Wf,e)?Wf[e]:"needs_attention"}function LT(e){const t=new Map;for(const n of e){const r=n.displayName.trim().toLowerCase(),i=t.get(r);i?t.set(r,{...i,candidates:[...i.candidates,n]}):t.set(r,{displayName:n.displayName,candidates:[n]})}return[...t.values()].map(n=>({...n,candidates:[...n.candidates].sort((r,i)=>r.candidateRef<i.candidateRef?-1:r.candidateRef>i.candidateRef?1:0)}))}function $T({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=e.filter(i=>i.status!=="ready"),r=LT(e);return o("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-team-setup-heading",children:n.length>0?`${n.length} ${n.length===1?"Team needs":"Teams need"} setup`:"Team setup"}),n.length>0?o("p",{children:"Tell Codemem who uses each device before using these Teams for sharing."}):null,o("ul",{...AT,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:r.map(i=>y("li",{...xT,className:"recipient-policy-sharing-team-setup-group",key:i.displayName},i.candidates.length>1?o("div",{className:"recipient-policy-sharing-team-setup-group-title",children:[o("strong",{children:i.displayName}),o("span",{className:"small",children:[i.candidates.length," Teams"]})]}):null,o("div",{className:"recipient-policy-sharing-team-setup-rows",children:i.candidates.map((a,s)=>{const c=`${s+1} of ${i.candidates.length}`,l=`${un(a.deviceCount,"device")}, ${un(a.projectCount,"Project")}`,d=i.candidates.length>1?`Continue setup for ${i.displayName} ${c}: ${l}`:`Continue setup for ${a.displayName}`;return o("div",{className:"recipient-policy-sharing-team-setup-row",children:[o("span",{className:"recipient-policy-sharing-team-setup-label",children:[i.candidates.length>1?o("span",{className:"small",children:["Team ",c," · ",l]}):o("strong",{children:a.displayName}),o("span",{"aria-hidden":"true",className:"recipient-policy-sharing-team-setup-separator",children:[" ","—"," "]})]}),o("span",{className:"recipient-policy-sharing-team-setup-status",children:o("span",{className:`project-status-badge ${DT(a.status)}`.trim(),children:RT(a.status)})}),o("span",{className:"recipient-policy-sharing-team-setup-action",children:a.status!=="ready"&&t?o("button",{"aria-label":d,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t(a.candidateRef),type:"button",children:"Continue setup"}):null})]},a.candidateRef)})})))})]})}var tr=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function un(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Vi(e,t){return e.length?e.join(", "):t}function zf(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function Jf({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{qi({mode:"recipient-manage",recipient:r})},a=()=>{qi({mode:"recipient-add",recipient:r})};return o(Z,{children:[o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[o("button",{"aria-describedby":e,"aria-label":`Add Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick:a,type:"button",children:"Add projects"}),o("button",{"aria-label":`Manage Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick:i,type:"button",children:"Manage projects"})]}),o("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function MT({disableMutations:e,intent:t,projects:n}){const r=t.teams.filter(s=>s.status==="active"),i=new Map(t.identities.filter(s=>s.status==="active").map(s=>[s.identityId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=[...new Set(t.teamMemberships.filter(g=>g.status==="active"&&g.teamId===s.teamId&&i.has(g.identityId)).map(g=>g.identityId))],d=l.map(g=>i.get(g)?.displayName??""),u=new Set(t.identityDevices.filter(g=>g.status==="active"&&l.includes(g.identityId)).map(g=>g.deviceId)).size,p=zf(t.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="team"&&g.teamId===s.teamId).map(g=>g.canonicalProjectIdentity),a),m=`recipient-policy-sharing-team-title-${c}`,f=`recipient-policy-sharing-team-add-description-${c}`;return o("article",{"aria-labelledby":m,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:m,children:s.displayName}),o("span",{className:"badge actor-badge",children:"Team"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Current member Identities"}),o("dd",{children:[un(d.length,"active member")," —"," ",Vi(d,"No active members")]})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:un(u,"active registered device")})]}),o("div",{children:[o("dt",{children:"Shared Projects"}),o("dd",{children:[un(p.length,"active shared Project")," —"," ",Vi(p,"No Projects shared")]})]}),o("div",{children:[o("dt",{children:"Future Team members"}),o("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),o(Jf,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"team",teamId:s.teamId}})]},s.teamId)})})}function OT({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(f=>f.status==="active"&&f.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(f=>f.status==="active"&&f.identityId===s.identityId&&i.has(f.teamId)).map(f=>f.teamId))].map(f=>i.get(f)?.displayName??""),u=zf(t.projectRecipients.filter(f=>f.status==="active"&&f.recipientKind==="identity"&&f.identityId===s.identityId).map(f=>f.canonicalProjectIdentity),a),p=`recipient-policy-sharing-identity-title-${c}`,m=`recipient-policy-sharing-identity-add-description-${c}`;return o("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:p,children:s.displayName}),o("span",{className:"badge actor-badge local",children:"Local identity"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Verification"}),o("dd",{children:"Local identity"})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:[un(l.length,"active registered device")," —"," ",Vi(l.map(f=>f.displayName),"No active devices")]})]}),o("div",{children:[o("dt",{children:"Team memberships"}),o("dd",{children:[un(d.length,"active Team membership")," —"," ",Vi(d,"No active Team memberships")]})]}),o("div",{children:[o("dt",{children:"Directly shared Projects"}),o("dd",{children:[un(u.length,"directly shared active Project")," —"," ",Vi(u,"No Projects shared directly")]})]})]}),o("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),o(Jf,{descriptionId:m,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function jT({received:e}){return e.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return o("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:r,children:t.displayName}),o("span",{className:"badge actor-badge",children:"Received"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Memories on this device"}),o("dd",{children:un(t.existingMemoryCount,"memory","memories")})]}),o("div",{children:[o("dt",{children:"Latest activity"}),o("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),o("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function FT({intent:e,options:t,projects:n}){const[r,i]=x(()=>e.teams.some(f=>f.status==="active")?"teams":"identities"),a=B(t.loading===!0||t.loadError===!0),s=B([]),c=Ff(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(f=>f.status==="active");J(()=>{if(a.current&&!t.loading&&!t.loadError){a.current=!1,i(u?"teams":"identities");return}u||i(f=>f==="teams"?"identities":f)},[u,t.loadError,t.loading]);const p=f=>{const g=tr[f];g&&(i(g.id),s.current[f]?.focus())},m=(f,g)=>{let h=null;f.key==="ArrowRight"?h=(g+1)%tr.length:f.key==="ArrowLeft"?h=(g-1+tr.length)%tr.length:f.key==="Home"?h=0:f.key==="End"&&(h=tr.length-1),h!==null&&(f.preventDefault(),p(h))};return o("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("header",{className:"recipient-policy-sharing-header",children:[o("h2",{children:"Sharing"}),o("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),o($T,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is being refreshed. The previous Team setup status is being shown.":"Team setup status is loading."}):null,t.teamSetupUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?o("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),o("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),o("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review Devices"}):null]}):null,d>0?o("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),o("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),o("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review Devices"}):null]}):null,t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous Sharing details. Team and Identity Project changes are disabled until a refresh succeeds."}):null,o("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:tr.map((f,g)=>o("button",{"aria-controls":`recipient-policy-sharing-panel-${f.id}`,"aria-selected":r===f.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===f.id?" active":""}`,id:`recipient-policy-sharing-tab-${f.id}`,onClick:()=>i(f.id),onKeyDown:h=>m(h,g),ref:h=>{s.current[g]=h},role:"tab",tabIndex:r===f.id?0:-1,type:"button",children:f.label},f.id))}),tr.map(f=>o("div",{"aria-labelledby":`recipient-policy-sharing-tab-${f.id}`,className:"recipient-policy-sharing-panel",hidden:r!==f.id,id:`recipient-policy-sharing-panel-${f.id}`,role:"tabpanel",children:t.loading?r===f.id?o(jf,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===f.id?o("p",{"aria-live":"assertive",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:f.id==="teams"?o(MT,{disableMutations:t.refreshError===!0,intent:e,projects:n}):f.id==="identities"?o(OT,{disableMutations:t.refreshError===!0,intent:e,projects:n}):f.id==="received"?o(jT,{received:t.received??[]}):o(PT,{intent:e})},f.id))]})}function BT(e,t,n,r={}){Ge(o(FT,{intent:n,options:r,projects:t}),e)}var ol={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function UT(){const e=[];let t=0;for(;;){const n=await io({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:xo(e),received:uT(e)}}var GT={loadDeviceInventory:Sc,loadIntent:wc,loadProjects:UT,loadSyncStatus:to,loadTeamSetupSummary:Mp,mountManagement:Of,mountSharing:BT};function HT(e={},t={}){const n={...GT,...e};let r=0,i=null,a=0,s,c,l=!1,d=!1,u=!1,p=!1,m=null;const f=(h={})=>{const v=g(++r,h);return i=v,v};async function g(h,v){const w=document.getElementById("recipientPolicySharingMount");if(!w){if(!v.requireTeamSetupSummary)return!0;try{return await n.loadTeamSetupSummary(),!0}catch{return!1}}const b=document.getElementById("recipientPolicyManagementMount");l=!0,d=!1;let S=()=>{const A=m;n.mountSharing(w,A?.inventory.manageable??[],A?.intent??ol,A?{coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:A.inventory.received,...u?{refreshError:!0}:{},teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d}:{loading:!0,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};S();const C=Promise.resolve().then(()=>n.loadTeamSetupSummary()).then(A=>(h!==r||(c=A,l=!1,d=!1,S()),!0),()=>(h!==r||(l=!1,d=!0,S()),!1)),[T,P,k,M]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(h!==r)return v.requireTeamSetupSummary?(await C,!1):i??!1;const U=k.status==="rejected";k.status==="fulfilled"&&(s=k.value),M.status==="fulfilled"&&(a=Kp(M.value));let E,j,O;const q=T.status==="fulfilled"&&P.status==="fulfilled";if(u=!q,p=U,q){const A=T.value,I=P.value;m={intent:I,inventory:A},E=A.manageable,j=I,O={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:U,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:A.received},b&&n.mountManagement(b,A.manageable,I,{onCommitted:async()=>{await f()}})}else if(m){const A=m;E=A.inventory.manageable,j=A.intent,O={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:U,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:A.inventory.received,refreshError:!0}}else E=[],j=ol,O={deviceInventoryUnavailable:U,loadError:!0};const L=()=>{n.mountSharing(w,E,j,{...O,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if(L(),S=L,!q&&b&&n.mountManagement(b,[],ol,{loadError:!0}),!v.requireTeamSetupSummary)return q;const R=await C;return h!==r?!1:q&&R}return f}var qT=Symbol.for("preact-signals");function $o(){if(pn>1)pn--;else{var e,t=!1;for((function(){var i=Oo;for(Oo=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Wi!==void 0;){var n=Wi;for(Wi=void 0,Mo++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Qf(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(Mo=0,pn--,t)throw e}}function KT(e){if(pn>0)return e();cl=++VT,pn++;try{return e()}finally{$o()}}var Fe=void 0;function sl(e){var t=Fe;Fe=void 0;try{return e()}finally{Fe=t}}var Yf,Wi=void 0,pn=0,Mo=0,VT=0,cl=0,Oo=void 0,jo=0;function Xf(e){if(Fe!==void 0){var t=e.n;if(t===void 0||t.t!==Fe)return t={i:0,S:e,p:Fe.s,n:void 0,t:Fe,e:void 0,x:void 0,r:t},Fe.s!==void 0&&(Fe.s.n=t),Fe.s=t,e.n=t,32&Fe.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Fe.s,t.n=void 0,Fe.s.n=t,Fe.s=t),t}}function Ye(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}Ye.prototype.brand=qT,Ye.prototype.h=function(){return!0},Ye.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:sl(function(){var r;(r=t.W)==null||r.call(t)}))},Ye.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&sl(function(){var i;(i=t.Z)==null||i.call(t)}))}},Ye.prototype.subscribe=function(e){var t=this;return zi(function(){var n=t.value,r=Fe;Fe=void 0;try{e(n)}finally{Fe=r}},{name:"sub"})},Ye.prototype.valueOf=function(){return this.value},Ye.prototype.toString=function(){return this.value+""},Ye.prototype.toJSON=function(){return this.value},Ye.prototype.peek=function(){var e=this;return sl(function(){return e.value})},Object.defineProperty(Ye.prototype,"value",{get:function(){var e=Xf(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Mo>100)throw new Error("Cycle detected");(function(n){pn!==0&&Mo===0&&n.l!==cl&&(n.l=cl,Oo={S:n,v:n.v,i:n.i,o:Oo})})(this),this.v=e,this.i++,jo++,pn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{$o()}}}});function ll(e,t){return new Ye(e,t)}function Qf(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function Zf(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function eh(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function nr(e,t){Ye.call(this,void 0),this.x=e,this.s=void 0,this.g=jo-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}nr.prototype=new Ye,nr.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===jo))return!0;if(this.g=jo,this.f|=1,this.i>0&&!Qf(this))return this.f&=-2,!0;var e=Fe;try{Zf(this),Fe=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Fe=e,eh(this),this.f&=-2,!0},nr.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}Ye.prototype.S.call(this,e)},nr.prototype.U=function(e){if(this.t!==void 0&&(Ye.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},nr.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}},Object.defineProperty(nr.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Xf(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function th(e,t){return new nr(e,t)}function nh(e){var t=e.m;if(e.m=void 0,typeof t=="function"){pn++;var n=Fe;Fe=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,dl(e),r}finally{Fe=n,$o()}}}function dl(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,nh(e)}function WT(e){if(Fe!==this)throw new Error("Out-of-order effect");eh(this),Fe=e,this.f&=-2,8&this.f&&dl(this),$o()}function Kr(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Yf&&Yf.push(this)}Kr.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t=="function"&&(this.m=t)}finally{e()}},Kr.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,nh(this),Zf(this),pn++;var e=Fe;return Fe=this,WT.bind(this,e)},Kr.prototype.N=function(){2&this.f||(this.f|=2,this.u=Wi,Wi=this)},Kr.prototype.d=function(){this.f|=8,1&this.f||dl(this)},Kr.prototype.dispose=function(){this.d()};function zi(e,t){var n=new Kr(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var rh,ul,Fo,zT=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,tF=[],ih=[];zi(function(){rh=this.N})();function Vr(e,t){fe[e]=t.bind(null,fe[e]||function(){})}function Bo(e){if(Fo){var t=Fo;Fo=void 0,t()}Fo=e&&e.S()}function ah(e){var t=this,n=e.data,r=YT(n);r.value=n;var i=Re(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=th(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=th(function(){return!Array.isArray(d.value)&&!Wp(d.value)}),p=zi(function(){if(this.N=oh,u.value){var f=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=f)}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[u,d]},[]),a=i[0],s=i[1];return a.value?s.peek():s.value}ah.displayName="ReactiveTextNode",Object.defineProperties(Ye.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ah},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Vr("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var i in r)if(i!=="children"){var a=r[i];a instanceof Ye&&(n||(t.__np=n={}),n[i]=a,r[i]=a.peek())}}e(t)}),Vr("__r",function(e,t){if(e(t),t.type!==Z){Bo();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,a){var s;return zi(function(){s=this},{name:a}),s.c=i,s})(function(){var i;zT&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),ul=r,Bo(n)}}),Vr("__e",function(e,t,n,r){Bo(),ul=void 0,e(t,n,r)}),Vr("diffed",function(e,t){Bo(),ul=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props;if(r){var a=n.U;if(a)for(var s in a){var c=a[s];c!==void 0&&!(s in r)&&(c.d(),a[s]=void 0)}else a={},n.U=a;for(var l in r){var d=a[l],u=r[l];d===void 0?(d=JT(n,l,u),a[l]=d):d.o(u,i)}}}e(t)});function JT(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,a=ll(n),s=n.peek();return{o:function(c,l){a.value=c,s=c.peek()},d:zi(function(){this.N=oh;var c=a.value.value;s!==c?(s=void 0,i?e[t]=c:c!=null&&(c!==!1||t[4]==="-")?e.setAttribute(t,c):e.removeAttribute(t)):s=void 0})}}Vr("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var a=r[i];a&&a.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),Vr("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)}),Tt.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(r||a||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function YT(e,t){return Re(function(){return ll(e,t)},[])}var nF=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},XT=function(e){queueMicrotask(function(){queueMicrotask(e)})};function QT(){KT(function(){for(var e;e=ih.shift();)rh.call(e)})}function oh(){ih.push(this)===1&&(fe.requestAnimationFrame||XT)(QT)}function Uo(e){const t=e+"CollectionProvider",[n,r]=st(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:v,children:w}=h,b=dn.useRef(null),S=dn.useRef(new Map).current;return o(i,{scope:v,itemMap:S,collectionRef:b,children:w})};s.displayName=t;const c=e+"CollectionSlot",l=Xn(c),d=dn.forwardRef((h,v)=>{const{scope:w,children:b}=h;return o(l,{ref:Se(v,a(c,w).collectionRef),children:b})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=Xn(u),f=dn.forwardRef((h,v)=>{const{scope:w,children:b,...S}=h,C=dn.useRef(null),T=Se(v,C),P=a(u,w);return dn.useEffect(()=>(P.itemMap.set(C,{ref:C,...S}),()=>{P.itemMap.delete(C)})),o(m,{[p]:"",ref:T,children:b})});f.displayName=u;function g(h){const v=a(e+"CollectionConsumer",h);return dn.useCallback(()=>{const w=v.collectionRef.current;if(!w)return[];const b=Array.from(w.querySelectorAll(`[${p}]`));return Array.from(v.itemMap.values()).sort((S,C)=>b.indexOf(S.ref.current)-b.indexOf(C.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},g,r]}var sh=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),ZT="VisuallyHidden",Go=V((e,t)=>o(pe.span,{...e,ref:t,style:{...sh,...e.style}}));Go.displayName=ZT;var eI=Go,pl="ToastProvider",[ml,tI,nI]=Uo("Toast"),[ch,rF]=st("Toast",[nI]),[rI,Ho]=ch(pl),lh=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:a=50,children:s}=e,[c,l]=x(null),[d,u]=x(0),p=B(!1),m=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${pl}\`. Expected non-empty \`string\`.`),o(ml.Provider,{scope:t,children:o(rI,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:d,viewport:c,onViewportChange:l,onToastAdd:se(()=>u(f=>f+1),[]),onToastRemove:se(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:m,children:s})})};lh.displayName=pl;var dh="ToastViewport",iI=["F8"],fl="toast.viewportPause",hl="toast.viewportResume",uh=V((e,t)=>{const{__scopeToast:n,hotkey:r=iI,label:i="Notifications ({hotkey})",...a}=e,s=Ho(dh,n),c=tI(n),l=B(null),d=B(null),u=B(null),p=B(null),m=Se(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=s.toastCount>0;J(()=>{const v=w=>{r.length!==0&&r.every(b=>w[b]||w.code===b)&&p.current?.focus()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),J(()=>{const v=l.current,w=p.current;if(g&&v&&w){const b=()=>{if(!s.isClosePausedRef.current){const P=new CustomEvent(fl);w.dispatchEvent(P),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const P=new CustomEvent(hl);w.dispatchEvent(P),s.isClosePausedRef.current=!1}},C=P=>{v.contains(P.relatedTarget)||S()},T=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",b),v.addEventListener("focusout",C),v.addEventListener("pointermove",b),v.addEventListener("pointerleave",T),window.addEventListener("blur",b),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",b),v.removeEventListener("focusout",C),v.removeEventListener("pointermove",b),v.removeEventListener("pointerleave",T),window.removeEventListener("blur",b),window.removeEventListener("focus",S)}}},[g,s.isClosePausedRef]);const h=se(({tabbingDirection:v})=>{const w=c().map(b=>{const S=b.ref.current,C=[S,...bI(S)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?w.reverse():w).flat()},[c]);return J(()=>{const v=p.current;if(v){const w=b=>{const S=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!S){const C=document.activeElement,T=b.shiftKey;if(b.target===v&&T){d.current?.focus();return}const P=h({tabbingDirection:T?"backwards":"forwards"}),k=P.findIndex(M=>M===C);yl(P.slice(k+1))?b.preventDefault():T?d.current?.focus():u.current?.focus()}};return v.addEventListener("keydown",w),()=>v.removeEventListener("keydown",w)}},[c,h]),o(BC,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&o(gl,{ref:d,onFocusFromOutsideViewport:()=>{yl(h({tabbingDirection:"forwards"}))}}),o(ml.Slot,{scope:n,children:o(pe.ol,{tabIndex:-1,...a,ref:m})}),g&&o(gl,{ref:u,onFocusFromOutsideViewport:()=>{yl(h({tabbingDirection:"backwards"}))}})]})});uh.displayName=dh;var ph="ToastFocusProxy",gl=V((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,a=Ho(ph,n);return o(Go,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;a.viewport?.contains(c)||r()}})});gl.displayName=ph;var Ji="Toast",aI="toast.swipeStart",oI="toast.swipeMove",sI="toast.swipeCancel",cI="toast.swipeEnd",mh=V((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:a,...s}=e,[c,l]=It({prop:r,defaultProp:i??!0,onChange:a,caller:Ji});return o(nt,{present:n||c,children:o(uI,{open:c,...s,ref:t,onClose:()=>l(!1),onPause:lt(e.onPause),onResume:lt(e.onResume),onSwipeStart:Q(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Q(e.onSwipeMove,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:Q(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Q(e.onSwipeEnd,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});mh.displayName=Ji;var[lI,dI]=ch(Ji,{onClose(){}}),uI=V((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:a,onClose:s,onEscapeKeyDown:c,onPause:l,onResume:d,onSwipeStart:u,onSwipeMove:p,onSwipeCancel:m,onSwipeEnd:f,...g}=e,h=Ho(Ji,n),[v,w]=x(null),b=Se(t,L=>w(L)),S=B(null),C=B(null),T=i||h.duration,P=B(0),k=B(T),M=B(0),{onToastAdd:U,onToastRemove:E}=h,j=lt(()=>{v?.contains(document.activeElement)&&h.viewport?.focus(),s()}),O=se(L=>{!L||L===1/0||(window.clearTimeout(M.current),P.current=new Date().getTime(),M.current=window.setTimeout(j,L))},[j]);J(()=>{const L=h.viewport;if(L){const R=()=>{O(k.current),d?.()},A=()=>{const I=new Date().getTime()-P.current;k.current=k.current-I,window.clearTimeout(M.current),l?.()};return L.addEventListener(fl,A),L.addEventListener(hl,R),()=>{L.removeEventListener(fl,A),L.removeEventListener(hl,R)}}},[h.viewport,T,l,d,O]),J(()=>{a&&!h.isClosePausedRef.current&&O(T)},[a,T,h.isClosePausedRef,O]),J(()=>(U(),()=>E()),[U,E]);const q=Re(()=>v?yh(v):null,[v]);return h.viewport?o(Z,{children:[q&&o(pI,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:q}),o(lI,{scope:n,onClose:j,children:cn(o(ml.ItemSlot,{scope:n,children:o(FC,{asChild:!0,onEscapeKeyDown:Q(c,()=>{h.isFocusedToastEscapeKeyDownRef.current||j(),h.isFocusedToastEscapeKeyDownRef.current=!1}),children:o(pe.li,{tabIndex:0,"data-state":a?"open":"closed","data-swipe-direction":h.swipeDirection,...g,ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:Q(e.onKeyDown,L=>{L.key==="Escape"&&(c?.(L.nativeEvent),L.nativeEvent.defaultPrevented||(h.isFocusedToastEscapeKeyDownRef.current=!0,j()))}),onPointerDown:Q(e.onPointerDown,L=>{L.button===0&&(S.current={x:L.clientX,y:L.clientY})}),onPointerMove:Q(e.onPointerMove,L=>{if(!S.current)return;const R=L.clientX-S.current.x,A=L.clientY-S.current.y,I=!!C.current,D=["left","right"].includes(h.swipeDirection),F=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,K=D?F(0,R):0,ce=D?0:F(0,A),ie=L.pointerType==="touch"?10:2,re={x:K,y:ce},ye={originalEvent:L,delta:re};I?(C.current=re,qo(oI,p,ye,{discrete:!1})):bh(re,h.swipeDirection,ie)?(C.current=re,qo(aI,u,ye,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(R)>ie||Math.abs(A)>ie)&&(S.current=null)}),onPointerUp:Q(e.onPointerUp,L=>{const R=C.current,A=L.target;if(A.hasPointerCapture(L.pointerId)&&A.releasePointerCapture(L.pointerId),C.current=null,S.current=null,R){const I=L.currentTarget,D={originalEvent:L,delta:R};bh(R,h.swipeDirection,h.swipeThreshold)?qo(cI,f,D,{discrete:!0}):qo(sI,m,D,{discrete:!0}),I.addEventListener("click",F=>F.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),pI=e=>{const{__scopeToast:t,children:n,...r}=e,i=Ho(Ji,t),[a,s]=x(!1),[c,l]=x(!1);return vI(()=>s(!0)),J(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:o(Zn,{asChild:!0,children:o(Go,{...r,children:a&&o(Z,{children:[i.label," ",n]})})})},mI="ToastTitle",fI=V((e,t)=>{const{__scopeToast:n,...r}=e;return o(pe.div,{...r,ref:t})});fI.displayName=mI;var hI="ToastDescription",fh=V((e,t)=>{const{__scopeToast:n,...r}=e;return o(pe.div,{...r,ref:t})});fh.displayName=hI;var hh="ToastAction",gI=V((e,t)=>{const{altText:n,...r}=e;return n.trim()?o(vh,{altText:n,asChild:!0,children:o(vl,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${hh}\`. Expected non-empty \`string\`.`),null)});gI.displayName=hh;var gh="ToastClose",vl=V((e,t)=>{const{__scopeToast:n,...r}=e,i=dI(gh,n);return o(vh,{asChild:!0,children:o(pe.button,{type:"button",...r,ref:t,onClick:Q(e.onClick,i.onClose)})})});vl.displayName=gh;var vh=V((e,t)=>{const{__scopeToast:n,altText:r,...i}=e;return o(pe.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:t})});function yh(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),yI(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const a=n.dataset.radixToastAnnounceAlt;a&&t.push(a)}else t.push(...yh(n))}}),t}function qo(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Kc(i,a):i.dispatchEvent(a)}var bh=(e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t==="left"||t==="right"?a&&r>n:!a&&i>n};function vI(e=()=>{}){const t=lt(e);We(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function yI(e){return e.nodeType===e.ELEMENT_NODE}function bI(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function yl(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var _I=lh,wI=uh,SI=mh,CI=fh,NI=vl,Yi=ll([]),TI=1;function II(e,t="success",n=8e3){if(!e)return;const r=TI++;Yi.value=[...Yi.value,{id:r,message:e,variant:t,durationMs:n}]}function kI(e){Yi.value=Yi.value.filter(t=>t.id!==e)}function EI(){const e=Yi.value;return o(_I,{duration:8e3,swipeDirection:"right",children:[e.map(t=>o(SI,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||kI(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[o(CI,{className:"toast-message",children:t.message}),o(NI,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),o(wI,{className:"toast-viewport"})]})}function PI(e){Ge(o(EI,{}),e)}function Ko(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Oe(e){return document.getElementById(e)}function bl(e){return document.getElementById(e)}function _l(e){return document.getElementById(e)}function _h(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function AI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xI(e,t){const n=t.trim();if(!n)return _h(e);const r=_h(e);try{const i=new RegExp(`(${AI(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Xi(e,t){const n=t.textContent;try{await navigator.clipboard.writeText(e),t.textContent="Copied"}catch{t.textContent="Copy failed"}setTimeout(()=>{t.textContent=n||"Copy"},1200)}var RI=new Set(["BUTTON","A","SELECT"]),DI=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function LI(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function $I(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function MI(e){return e?RI.has(e.tagName)?!0:e instanceof HTMLInputElement&&DI.has(e.type):!1}function OI(e){return e.metaKey||e.ctrlKey}function Wr(e,t){if(t.disabled||e.defaultPrevented||e.isComposing||e.key!=="Enter"&&e.key!=="Escape")return;const n=e.target instanceof HTMLElement?e.target:null;if(!LI(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}MI(n)||$I(n)&&!OI(e)||(e.preventDefault(),t.onSubmit())}}var rr=["feed","projects","sharing","devices","health","advanced"],wh=["sync","coordinator-admin"],wl="codemem-tab",Sh="codemem-advanced-section",Ch="codemem-feed-filter",Nh="codemem-feed-scope",jI="codemem-sync-diagnostics",Th="codemem-sync-pairing",Ih="codemem-sync-redact",kh=["all","observations","summaries"],Eh=["all","mine","theirs"],_={activeTab:"feed",advancedSection:"sync",currentProject:"",refreshState:"idle",refreshInFlight:!1,refreshQueued:!1,refreshTimer:null,feedTypeFilter:"all",feedScopeFilter:"all",feedQuery:"",lastFeedItems:[],lastFeedFilteredCount:0,lastFeedSignature:"",pendingFeedItems:null,itemViewState:new Map,itemExpandState:new Map,newItemKeys:new Set,lastStatsPayload:null,lastUsagePayload:null,lastRawEventsPayload:null,lastUpdateStatus:null,lastSyncStatus:null,lastDeviceIdentityInventory:null,deviceIdentityInventoryLoadError:!1,pendingDeviceIdentityFocus:void 0,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,pendingCoordinatorApprovalsByDeviceId:new Map,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function FI(e){return[...rr]}function Qi(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":rr.includes(e)?e:"feed"}function Sl(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return wh.includes(t)?"advanced":rr.includes(t)?t:null}function Cl(e=window.location.hash){const[t,n]=e.replace(/^#/,"").split("/");return t==="sync"?"sync":t==="coordinator-admin"?"teams":t!=="advanced"?null:n==="teams"?"teams":"sync"}function BI(){const e=Sl();if(e)return Qi(e,_.lastCoordinatorAdminStatus);const t=localStorage.getItem(wl);return t&&(rr.includes(t)||wh.includes(t))?Qi(t,_.lastCoordinatorAdminStatus):"feed"}function UI(){const e=Cl();if(e)return e;const t=localStorage.getItem(wl);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(Sh)==="teams"?"teams":"sync"}function Nl(e,t=!1){_.advancedSection=e,localStorage.setItem(Sh,e),t&&(window.location.hash=`advanced/${e}`)}function Ph(e,t={}){const n=Qi(e,_.lastCoordinatorAdminStatus);_.activeTab=n,localStorage.setItem(wl,n);const r=Sl();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${_.advancedSection}`:n)}function GI(){const e=localStorage.getItem(Ch)||"all";return kh.includes(e)?e:"all"}function HI(){const e=localStorage.getItem(Nh)||"all";return Eh.includes(e)?e:"all"}function qI(e){_.feedTypeFilter=kh.includes(e)?e:"all",localStorage.setItem(Ch,_.feedTypeFilter)}function Ah(e){_.feedScopeFilter=Eh.includes(e)?e:"all",localStorage.setItem(Nh,_.feedScopeFilter)}function KI(){return localStorage.getItem(jI)==="1"}function VI(e){_.syncPairingOpen=e;try{localStorage.setItem(Th,e?"1":"0")}catch{}}function Zi(){return localStorage.getItem(Ih)!=="0"}function WI(e){localStorage.setItem(Ih,e?"1":"0")}function zI(){_.activeTab=BI(),_.advancedSection=UI(),_.feedTypeFilter=GI(),_.feedScopeFilter=HI(),_.syncDiagnosticsOpen=KI();try{_.syncPairingOpen=localStorage.getItem(Th)==="1"}catch{_.syncPairingOpen=!1}}var Tl=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],xh="codemem-theme";function Rh(e){const t=Tl.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return Tl.find(r=>r.id===n)||Tl[0]}function Il(){const e=localStorage.getItem(xh);return e?Rh(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Dh(e){const t=Rh(e);document.documentElement.setAttribute("data-theme",t.mode),document.documentElement.setAttribute("data-color-mode",t.mode),t.id===t.mode?document.documentElement.removeAttribute("data-theme-variant"):document.documentElement.setAttribute("data-theme-variant",t.id),localStorage.setItem(xh,t.id)}function JI(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const a=document.createElement("i");a.setAttribute("data-lucide",r),a.setAttribute("aria-hidden","true"),e.appendChild(a),globalThis.lucide?.createIcons?.()};t(Il()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Il()==="dark"?"light":"dark";Dh(n),t(n)})}var YI=Jn(void 0);function ea(e){const t=Tn(YI);return e||t||"ltr"}var kl="rovingFocusGroup.onEntryFocus",XI={bubbles:!1,cancelable:!0},ta="RovingFocusGroup",[El,Lh,QI]=Uo(ta),[ZI,zr]=st(ta,[QI]),[ek,tk]=ZI(ta),$h=V((e,t)=>o(El.Provider,{scope:e.__scopeRovingFocusGroup,children:o(El.Slot,{scope:e.__scopeRovingFocusGroup,children:o(nk,{...e,ref:t})})}));$h.displayName=ta;var nk=V((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...p}=e,m=B(null),f=Se(t,m),g=ea(a),[h,v]=It({prop:s,defaultProp:c??null,onChange:l,caller:ta}),[w,b]=x(!1),S=lt(d),C=Lh(n),T=B(!1),[P,k]=x(0);return J(()=>{const M=m.current;if(M)return M.addEventListener(kl,S),()=>M.removeEventListener(kl,S)},[S]),o(ek,{scope:n,orientation:r,dir:g,loop:i,currentTabStopId:h,onItemFocus:se(M=>v(M),[v]),onItemShiftTab:se(()=>b(!0),[]),onFocusableItemAdd:se(()=>k(M=>M+1),[]),onFocusableItemRemove:se(()=>k(M=>M-1),[]),children:o(pe.div,{tabIndex:w||P===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:Q(e.onMouseDown,()=>{T.current=!0}),onFocus:Q(e.onFocus,M=>{const U=!T.current;if(M.target===M.currentTarget&&U&&!w){const E=new CustomEvent(kl,XI);if(M.currentTarget.dispatchEvent(E),!E.defaultPrevented){const j=C().filter(O=>O.focusable);jh([j.find(O=>O.active),j.find(O=>O.id===h),...j].filter(Boolean).map(O=>O.ref.current),u)}}T.current=!1}),onBlur:Q(e.onBlur,()=>b(!1))})})}),Mh="RovingFocusGroupItem",Oh=V((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:s,...c}=e,l=ct(),d=a||l,u=tk(Mh,n),p=u.currentTabStopId===d,m=Lh(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:h}=u;return J(()=>{if(r)return f(),()=>g()},[r,f,g]),o(El.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:o(pe.span,{tabIndex:p?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:Q(e.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:Q(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:Q(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const w=ak(v,u.orientation,u.dir);if(w!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let b=m().filter(S=>S.focusable).map(S=>S.ref.current);if(w==="last")b.reverse();else if(w==="prev"||w==="next"){w==="prev"&&b.reverse();const S=b.indexOf(v.currentTarget);b=u.loop?ok(b,S+1):b.slice(S+1)}setTimeout(()=>jh(b))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});Oh.displayName=Mh;var rk={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ik(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function ak(e,t,n){const r=ik(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return rk[r]}function jh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function ok(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Pl=$h,Al=Oh,Vo="Tabs",[sk,iF]=st(Vo,[zr]),Fh=zr(),[ck,xl]=sk(Vo),Bh=V((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:a,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=ea(c),[p,m]=It({prop:r,onChange:i,defaultProp:a??"",caller:Vo});return o(ck,{scope:n,baseId:ct(),value:p,onValueChange:m,orientation:s,dir:u,activationMode:l,children:o(pe.div,{dir:u,"data-orientation":s,...d,ref:t})})});Bh.displayName=Vo;var Uh="TabsList",Gh=V((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,a=xl(Uh,n),s=Fh(n);return o(Pl,{asChild:!0,...s,orientation:a.orientation,dir:a.dir,loop:r,children:o(pe.div,{role:"tablist","aria-orientation":a.orientation,...i,ref:t})})});Gh.displayName=Uh;var Hh="TabsTrigger",qh=V((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...a}=e,s=xl(Hh,n),c=Fh(n),l=Wh(s.baseId,r),d=zh(s.baseId,r),u=r===s.value;return o(Al,{asChild:!0,...c,focusable:!i,active:u,children:o(pe.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...a,ref:t,onMouseDown:Q(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:Q(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:Q(e.onFocus,()=>{const p=s.activationMode!=="manual";!u&&!i&&p&&s.onValueChange(r)})})})});qh.displayName=Hh;var Kh="TabsContent",Vh=V((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:a,...s}=e,c=xl(Kh,n),l=Wh(c.baseId,r),d=zh(c.baseId,r),u=r===c.value,p=B(u);return J(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),o(nt,{present:i||u,children:({present:m})=>o(pe.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:d,tabIndex:0,...s,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&a})})});Vh.displayName=Kh;function Wh(e,t){return`${e}-trigger-${t}`}function zh(e,t){return`${e}-content-${t}`}var lk=Bh,dk=Gh,uk=qh,pk=Vh;function Jh({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:a,value:s}){return o(lk,{onValueChange:r,value:s,children:[o(dk,{"aria-label":e,className:n,children:i.map(c=>o(uk,{className:a,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function ir({children:e,className:t,forceMount:n=!1,value:r}){return o(pk,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Ne(e){return o("input",{...e})}function mk(e,t){const n=String(e.device_id||"").trim(),r=String(e.group_id||t||"").trim(),i=String(e.display_name||n||"Unnamed device"),a=e.enabled!==!1&&e.enabled!==0,s=[`Device ID ${n||"unknown"}`];return r&&s.push(`Team ID ${r}`),{advancedDetail:`Advanced: ${s.join(" · ")}`,deviceId:n,displayName:i,statusLabel:a?"Enabled in this Team":"Disabled in this Team",teamId:r}}var fk="codemem-coordinator-admin-target-group",H={activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",groupRenameDrafts:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function hk(e){const{summary:t,runDevice:n}=e,r=Array.isArray(_.lastCoordinatorAdminDevices)?_.lastCoordinatorAdminDevices:[];return y(ir,{className:"coordinator-admin-panel",value:"devices"},y("h3",null,"Enrolled devices"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove Team devices here. Space access is granted from Spaces below; Team membership alone does not share memories.":"Finish setup first. Device administration stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const a=mk(i,String(_.lastCoordinatorAdminStatus?.active_group||"")),{deviceId:s,displayName:c,teamId:l}=a,d=H.deviceActionPendingId===s,u=H.deviceRenameDrafts.get(s)??String(i.display_name||""),p=i.enabled!==!1&&i.enabled!==0,m=!s||d||t.readiness!=="ready";return y("div",{class:"peer-card peer-card--padded",key:s||String(i.fingerprint||"unknown")},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-submeta"},a.statusLabel),y("div",{class:"peer-meta"},a.advancedDetail),y("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!m&&n(s,l,c,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Ne,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:f=>{H.deviceRenameDrafts.set(s,String(f.currentTarget.value||""))},type:"text",value:u}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:m,type:"submit"},d&&H.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&H.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:m,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&H.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&H.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No enrolled devices found for the active coordinator group.":"Device administration will appear here once setup is complete."))}var Wo="Collapsible",[gk,aF]=st(Wo),[vk,Rl]=gk(Wo),Yh=V((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:a,onOpenChange:s,...c}=e,[l,d]=It({prop:r,defaultProp:i??!1,onChange:s,caller:Wo});return o(vk,{scope:n,disabled:a,contentId:ct(),open:l,onOpenToggle:se(()=>d(u=>!u),[d]),children:o(pe.div,{"data-state":Ll(l),"data-disabled":a?"":void 0,...c,ref:t})})});Yh.displayName=Wo;var Xh="CollapsibleTrigger",Qh=V((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=Rl(Xh,n);return o(pe.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":Ll(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:Q(e.onClick,i.onOpenToggle)})});Qh.displayName=Xh;var Dl="CollapsibleContent",Zh=V((e,t)=>{const{forceMount:n,...r}=e,i=Rl(Dl,e.__scopeCollapsible);return o(nt,{present:n||i.open,children:({present:a})=>o(yk,{...r,ref:t,present:a})})});Zh.displayName=Dl;var yk=V((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...a}=e,s=Rl(Dl,n),[c,l]=x(r),d=B(null),u=Se(t,d),p=B(0),m=p.current,f=B(0),g=f.current,h=s.open||c,v=B(h),w=B(void 0);return J(()=>{const b=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(b)},[]),We(()=>{const b=d.current;if(b){w.current=w.current||{transitionDuration:b.style.transitionDuration,animationName:b.style.animationName},b.style.transitionDuration="0s",b.style.animationName="none";const S=b.getBoundingClientRect();p.current=S.height,f.current=S.width,v.current||(b.style.transitionDuration=w.current.transitionDuration,b.style.animationName=w.current.animationName),l(r)}},[s.open,r]),o(pe.div,{"data-state":Ll(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...a,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&i})});function Ll(e){return e?"open":"closed"}var zo=Yh,eg=Qh,Jo=Zh,bk=["top","right","bottom","left"],kn=Math.min,_t=Math.max,Yo=Math.round,Xo=Math.floor,Vt=e=>({x:e,y:e}),_k={left:"right",right:"left",bottom:"top",top:"bottom"};function $l(e,t,n){return _t(e,kn(t,n))}function mn(e,t){return typeof e=="function"?e(t):e}function fn(e){return e.split("-")[0]}function Jr(e){return e.split("-")[1]}function Ml(e){return e==="x"?"y":"x"}function Ol(e){return e==="y"?"height":"width"}function Wt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function jl(e){return Ml(Wt(e))}function wk(e,t,n){n===void 0&&(n=!1);const r=Jr(e),i=jl(e),a=Ol(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=Qo(s)),[s,Qo(s)]}function Sk(e){const t=Qo(e);return[Fl(e),t,Fl(t)]}function Fl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var tg=["left","right"],ng=["right","left"],Ck=["top","bottom"],Nk=["bottom","top"];function Tk(e,t,n){switch(e){case"top":case"bottom":return n?t?ng:tg:t?tg:ng;case"left":case"right":return t?Ck:Nk;default:return[]}}function Ik(e,t,n,r){const i=Jr(e);let a=Tk(fn(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(Fl)))),a}function Qo(e){const t=fn(e);return _k[t]+e.slice(t.length)}function kk(e){return{top:0,right:0,bottom:0,left:0,...e}}function rg(e){return typeof e!="number"?kk(e):{top:e,right:e,bottom:e,left:e}}function Zo(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function ig(e,t,n){let{reference:r,floating:i}=e;const a=Wt(t),s=jl(t),c=Ol(s),l=fn(t),d=a==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,m=r[c]/2-i[c]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:p};break;case"left":f={x:r.x-i.width,y:p};break;default:f={x:r.x,y:r.y}}switch(Jr(t)){case"start":f[s]-=m*(n&&d?-1:1);break;case"end":f[s]+=m*(n&&d?-1:1);break}return f}async function Ek(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:m=!1,padding:f=0}=mn(t,e),g=rg(f),h=c[m?p==="floating"?"reference":"floating":p],v=Zo(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(h)))==null||n?h:h.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),w=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,b=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),S=await(a.isElement==null?void 0:a.isElement(b))?await(a.getScale==null?void 0:a.getScale(b))||{x:1,y:1}:{x:1,y:1},C=Zo(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:w,offsetParent:b,strategy:l}):w);return{top:(v.top-C.top+g.top)/S.y,bottom:(C.bottom-v.bottom+g.bottom)/S.y,left:(v.left-C.left+g.left)/S.x,right:(C.right-v.right+g.right)/S.x}}var Pk=50,Ak=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:Ek},l=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:p}=ig(d,r,l),m=r,f=0;const g={};for(let h=0;h<a.length;h++){const v=a[h];if(!v)continue;const{name:w,fn:b}=v,{x:S,y:C,data:T,reset:P}=await b({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:g,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=C??p,g[w]={...g[w],...T},P&&f<Pk&&(f++,typeof P=="object"&&(P.placement&&(m=P.placement),P.rects&&(d=P.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):P.rects),{x:u,y:p}=ig(d,m,l)),h=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:g}},xk=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=mn(e,t)||{};if(d==null)return{};const p=rg(u),m={x:n,y:r},f=jl(i),g=Ol(f),h=await s.getDimensions(d),v=f==="y",w=v?"top":"left",b=v?"bottom":"right",S=v?"clientHeight":"clientWidth",C=a.reference[g]+a.reference[f]-m[f]-a.floating[g],T=m[f]-a.reference[f],P=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let k=P?P[S]:0;(!k||!await(s.isElement==null?void 0:s.isElement(P)))&&(k=c.floating[S]||a.floating[g]);const M=C/2-T/2,U=k/2-h[g]/2-1,E=kn(p[w],U),j=kn(p[b],U),O=E,q=k-h[g]-j,L=k/2-h[g]/2+M,R=$l(O,L,q),A=!l.arrow&&Jr(i)!=null&&L!==R&&a.reference[g]/2-(L<O?E:j)-h[g]/2<0,I=A?L<O?L-O:L-q:0;return{[f]:m[f]+I,data:{[f]:R,centerOffset:L-R-I,...A&&{alignmentOffset:I}},reset:A}}}),Rk=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...v}=mn(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const w=fn(i),b=Wt(c),S=fn(c)===c,C=await(l.isRTL==null?void 0:l.isRTL(d.floating)),T=m||(S||!h?[Qo(c)]:Sk(c)),P=g!=="none";!m&&P&&T.push(...Ik(c,h,g,C));const k=[c,...T],M=await l.detectOverflow(t,v),U=[];let E=((r=a.flip)==null?void 0:r.overflows)||[];if(u&&U.push(M[w]),p){const L=wk(i,s,C);U.push(M[L[0]],M[L[1]])}if(E=[...E,{placement:i,overflows:U}],!U.every(L=>L<=0)){var j,O;const L=(((j=a.flip)==null?void 0:j.index)||0)+1,R=k[L];if(R&&(!(p==="alignment"&&b!==Wt(R))||E.every(I=>Wt(I.placement)===b?I.overflows[0]>0:!0)))return{data:{index:L,overflows:E},reset:{placement:R}};let A=(O=E.filter(I=>I.overflows[0]<=0).sort((I,D)=>I.overflows[1]-D.overflows[1])[0])==null?void 0:O.placement;if(!A)switch(f){case"bestFit":{var q;const I=(q=E.filter(D=>{if(P){const F=Wt(D.placement);return F===b||F==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(F=>F>0).reduce((F,K)=>F+K,0)]).sort((D,F)=>D[1]-F[1])[0])==null?void 0:q[0];I&&(A=I);break}case"initialPlacement":A=c;break}if(i!==A)return{reset:{placement:A}}}return{}}}};function ag(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function og(e){return bk.some(t=>e[t]>=0)}var Dk=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=mn(e,t);switch(i){case"referenceHidden":{const s=ag(await r.detectOverflow(t,{...a,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:og(s)}}}case"escaped":{const s=ag(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:og(s)}}}default:return{}}}}},sg=new Set(["left","top"]);async function Lk(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=fn(n),c=Jr(n),l=Wt(n)==="y",d=sg.has(s)?-1:1,u=a&&l?-1:1,p=mn(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof g=="number"&&(f=c==="end"?g*-1:g),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var $k=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:c}=t,l=await Lk(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:a+l.y,data:{...l,placement:s}}}}},Mk=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:w=>{let{x:b,y:S}=w;return{x:b,y:S}}},...d}=mn(e,t),u={x:n,y:r},p=await a.detectOverflow(t,d),m=Wt(fn(i)),f=Ml(m);let g=u[f],h=u[m];if(s){const w=f==="y"?"top":"left",b=f==="y"?"bottom":"right",S=g+p[w],C=g-p[b];g=$l(S,g,C)}if(c){const w=m==="y"?"top":"left",b=m==="y"?"bottom":"right",S=h+p[w],C=h-p[b];h=$l(S,h,C)}const v=l.fn({...t,[f]:g,[m]:h});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:s,[m]:c}}}}}},Ok=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:a,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=mn(e,t),u={x:n,y:r},p=Wt(i),m=Ml(p);let f=u[m],g=u[p];const h=mn(c,t),v=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const S=m==="y"?"height":"width",C=a.reference[m]-a.floating[S]+v.mainAxis,T=a.reference[m]+a.reference[S]-v.mainAxis;f<C?f=C:f>T&&(f=T)}if(d){var w,b;const S=m==="y"?"width":"height",C=sg.has(fn(i)),T=a.reference[p]-a.floating[S]+(C&&((w=s.offset)==null?void 0:w[p])||0)+(C?0:v.crossAxis),P=a.reference[p]+a.reference[S]+(C?0:((b=s.offset)==null?void 0:b[p])||0)-(C?v.crossAxis:0);g<T?g=T:g>P&&(g=P)}return{[m]:f,[p]:g}}}},jk=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:a,platform:s,elements:c}=t,{apply:l=()=>{},...d}=mn(e,t),u=await s.detectOverflow(t,d),p=fn(i),m=Jr(i),f=Wt(i)==="y",{width:g,height:h}=a.floating;let v,w;p==="top"||p==="bottom"?(v=p,w=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(w=p,v=m==="end"?"top":"bottom");const b=h-u.top-u.bottom,S=g-u.left-u.right,C=kn(h-u[v],b),T=kn(g-u[w],S),P=!t.middlewareData.shift;let k=C,M=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(k=b),P&&!m){const E=_t(u.left,0),j=_t(u.right,0),O=_t(u.top,0),q=_t(u.bottom,0);f?M=g-2*(E!==0||j!==0?E+j:_t(u.left,u.right)):k=h-2*(O!==0||q!==0?O+q:_t(u.top,u.bottom))}await l({...t,availableWidth:M,availableHeight:k});const U=await s.getDimensions(c.floating);return g!==U.width||h!==U.height?{reset:{rects:!0}}:{}}}};function es(){return typeof window<"u"}function Yr(e){return cg(e)?(e.nodeName||"").toLowerCase():"#document"}function wt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function zt(e){var t;return(t=(cg(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function cg(e){return es()?e instanceof Node||e instanceof wt(e).Node:!1}function Lt(e){return es()?e instanceof Element||e instanceof wt(e).Element:!1}function hn(e){return es()?e instanceof HTMLElement||e instanceof wt(e).HTMLElement:!1}function lg(e){return!es()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof wt(e).ShadowRoot}function na(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=$t(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Fk(e){return/^(table|td|th)$/.test(Yr(e))}function ts(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var Bk=/transform|translate|scale|rotate|perspective|filter/,Uk=/paint|layout|strict|content/,ar=e=>!!e&&e!=="none",Bl;function Ul(e){const t=Lt(e)?$t(e):e;return ar(t.transform)||ar(t.translate)||ar(t.scale)||ar(t.rotate)||ar(t.perspective)||!Gl()&&(ar(t.backdropFilter)||ar(t.filter))||Bk.test(t.willChange||"")||Uk.test(t.contain||"")}function Gk(e){let t=En(e);for(;hn(t)&&!Xr(t);){if(Ul(t))return t;if(ts(t))return null;t=En(t)}return null}function Gl(){return Bl==null&&(Bl=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bl}function Xr(e){return/^(html|body|#document)$/.test(Yr(e))}function $t(e){return wt(e).getComputedStyle(e)}function ns(e){return Lt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function En(e){if(Yr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||lg(e)&&e.host||zt(e);return lg(t)?t.host:t}function dg(e){const t=En(e);return Xr(t)?e.ownerDocument?e.ownerDocument.body:e.body:hn(t)&&na(t)?t:dg(t)}function ra(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=dg(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=wt(i);if(a){const c=Hl(s);return t.concat(s,s.visualViewport||[],na(i)?i:[],c&&n?ra(c):[])}else return t.concat(i,ra(i,[],n))}function Hl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ug(e){const t=$t(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=hn(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=Yo(n)!==a||Yo(r)!==s;return c&&(n=a,r=s),{width:n,height:r,$:c}}function ql(e){return Lt(e)?e:e.contextElement}function Qr(e){const t=ql(e);if(!hn(t))return Vt(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=ug(t);let s=(a?Yo(n.width):n.width)/r,c=(a?Yo(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var Hk=Vt(0);function pg(e){const t=wt(e);return!Gl()||!t.visualViewport?Hk:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function qk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==wt(e)?!1:t}function or(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=ql(e);let s=Vt(1);t&&(r?Lt(r)&&(s=Qr(r)):s=Qr(e));const c=qk(a,n,r)?pg(a):Vt(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(a){const m=wt(a),f=r&&Lt(r)?wt(r):r;let g=m,h=Hl(g);for(;h&&r&&f!==g;){const v=Qr(h),w=h.getBoundingClientRect(),b=$t(h),S=w.left+(h.clientLeft+parseFloat(b.paddingLeft))*v.x,C=w.top+(h.clientTop+parseFloat(b.paddingTop))*v.y;l*=v.x,d*=v.y,u*=v.x,p*=v.y,l+=S,d+=C,g=wt(h),h=Hl(g)}}return Zo({width:u,height:p,x:l,y:d})}function rs(e,t){const n=ns(e).scrollLeft;return t?t.left+n:or(zt(e)).left+n}function mg(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-rs(e,n),y:n.top+t.scrollTop}}function Kk(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=zt(r),c=t?ts(t.floating):!1;if(r===s||c&&a)return n;let l={scrollLeft:0,scrollTop:0},d=Vt(1);const u=Vt(0),p=hn(r);if((p||!p&&!a)&&((Yr(r)!=="body"||na(s))&&(l=ns(r)),p)){const f=or(r);d=Qr(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!a?mg(s,l):Vt(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-l.scrollTop*d.y+u.y+m.y}}function Vk(e){return Array.from(e.getClientRects())}function Wk(e){const t=zt(e),n=ns(e),r=e.ownerDocument.body,i=_t(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),a=_t(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+rs(e);const c=-n.scrollTop;return $t(r).direction==="rtl"&&(s+=_t(t.clientWidth,r.clientWidth)-i),{width:i,height:a,x:s,y:c}}var fg=25;function zk(e,t){const n=wt(e),r=zt(e),i=n.visualViewport;let a=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){a=i.width,s=i.height;const u=Gl();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=rs(r);if(d<=0){const u=r.ownerDocument,p=u.body,m=getComputedStyle(p),f=u.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(r.clientWidth-p.clientWidth-f);g<=fg&&(a-=g)}else d<=fg&&(a+=d);return{width:a,height:s,x:c,y:l}}function Jk(e,t){const n=or(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=hn(e)?Qr(e):Vt(1);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function hg(e,t,n){let r;if(t==="viewport")r=zk(e,n);else if(t==="document")r=Wk(zt(e));else if(Lt(t))r=Jk(t,n);else{const i=pg(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Zo(r)}function gg(e,t){const n=En(e);return n===t||!Lt(n)||Xr(n)?!1:$t(n).position==="fixed"||gg(n,t)}function Yk(e,t){const n=t.get(e);if(n)return n;let r=ra(e,[],!1).filter(c=>Lt(c)&&Yr(c)!=="body"),i=null;const a=$t(e).position==="fixed";let s=a?En(e):e;for(;Lt(s)&&!Xr(s);){const c=$t(s),l=Ul(s);!l&&c.position==="fixed"&&(i=null),(a?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||na(s)&&!l&&gg(e,s))?r=r.filter(d=>d!==s):i=c,s=En(s)}return t.set(e,r),r}function Xk(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const a=[...n==="clippingAncestors"?ts(t)?[]:Yk(t,this._c):[].concat(n),r],s=hg(t,a[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<a.length;p++){const m=hg(t,a[p],i);c=_t(m.top,c),l=kn(m.right,l),d=kn(m.bottom,d),u=_t(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function Qk(e){const{width:t,height:n}=ug(e);return{width:t,height:n}}function Zk(e,t,n){const r=hn(t),i=zt(t),a=n==="fixed",s=or(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Vt(0);function d(){l.x=rs(i)}if(r||!r&&!a)if((Yr(t)!=="body"||na(i))&&(c=ns(t)),r){const p=or(t,!0,a,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();a&&!r&&i&&d();const u=i&&!r&&!a?mg(i,c):Vt(0);return{x:s.left+c.scrollLeft-l.x-u.x,y:s.top+c.scrollTop-l.y-u.y,width:s.width,height:s.height}}function Kl(e){return $t(e).position==="static"}function vg(e,t){if(!hn(e)||$t(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return zt(e)===n&&(n=n.ownerDocument.body),n}function yg(e,t){const n=wt(e);if(ts(e))return n;if(!hn(e)){let i=En(e);for(;i&&!Xr(i);){if(Lt(i)&&!Kl(i))return i;i=En(i)}return n}let r=vg(e,t);for(;r&&Fk(r)&&Kl(r);)r=vg(r,t);return r&&Xr(r)&&Kl(r)&&!Ul(r)?n:r||Gk(e)||n}var eE=async function(e){const t=this.getOffsetParent||yg,n=this.getDimensions,r=await n(e.floating);return{reference:Zk(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function tE(e){return $t(e).direction==="rtl"}var nE={convertOffsetParentRelativeRectToViewportRelativeRect:Kk,getDocumentElement:zt,getClippingRect:Xk,getOffsetParent:yg,getElementRects:eE,getClientRects:Vk,getDimensions:Qk,getScale:Qr,isElement:Lt,isRTL:tE};function bg(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rE(e,t){let n=null,r;const i=zt(e);function a(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:u,top:p,width:m,height:f}=d;if(c||t(),!m||!f)return;const g=Xo(p),h=Xo(i.clientWidth-(u+m)),v=Xo(i.clientHeight-(p+f)),w=Xo(u),b={rootMargin:-g+"px "+-h+"px "+-v+"px "+-w+"px",threshold:_t(0,kn(1,l))||1};let S=!0;function C(T){const P=T[0].intersectionRatio;if(P!==l){if(!S)return s();P?s(!1,P):r=setTimeout(()=>{s(!1,1e-7)},1e3)}P===1&&!bg(d,e.getBoundingClientRect())&&s(),S=!1}try{n=new IntersectionObserver(C,{...b,root:i.ownerDocument})}catch{n=new IntersectionObserver(C,b)}n.observe(e)}return s(!0),a}function iE(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=ql(e),u=i||a?[...d?ra(d):[],...t?ra(t):[]]:[];u.forEach(w=>{i&&w.addEventListener("scroll",n,{passive:!0}),a&&w.addEventListener("resize",n)});const p=d&&c?rE(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(w=>{let[b]=w;b&&b.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!l&&f.observe(d),t&&f.observe(t));let g,h=l?or(e):null;l&&v();function v(){const w=or(e);h&&!bg(h,w)&&n(),h=w,g=requestAnimationFrame(v)}return n(),()=>{var w;u.forEach(b=>{i&&b.removeEventListener("scroll",n),a&&b.removeEventListener("resize",n)}),p?.(),(w=f)==null||w.disconnect(),f=null,l&&cancelAnimationFrame(g)}}var aE=$k,oE=Mk,sE=Rk,cE=jk,lE=Dk,_g=xk,dE=Ok,uE=(e,t,n)=>{const r=new Map,i={platform:nE,...n},a={...i.platform,_c:r};return Ak(e,t,{...i,platform:a})},is=typeof document<"u"?bt:function(){};function as(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!as(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!as(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function wg(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Sg(e,t){const n=wg(e);return Math.round(t*n)/n}function Vl(e){const t=B(e);return is(()=>{t.current=e}),t}function pE(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=x({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=x(r);as(m,r)||f(r);const[g,h]=x(null),[v,w]=x(null),b=se(D=>{D!==P.current&&(P.current=D,h(D))},[]),S=se(D=>{D!==k.current&&(k.current=D,w(D))},[]),C=a||g,T=s||v,P=B(null),k=B(null),M=B(u),U=l!=null,E=Vl(l),j=Vl(i),O=Vl(d),q=se(()=>{if(!P.current||!k.current)return;const D={placement:t,strategy:n,middleware:m};j.current&&(D.platform=j.current),uE(P.current,k.current,D).then(F=>{const K={...F,isPositioned:O.current!==!1};L.current&&!as(M.current,K)&&(M.current=K,ho(()=>{p(K)}))})},[m,t,n,j,O]);is(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[d]);const L=B(!1);is(()=>(L.current=!0,()=>{L.current=!1}),[]),is(()=>{if(C&&(P.current=C),T&&(k.current=T),C&&T){if(E.current)return E.current(C,T,q);q()}},[C,T,q,E,U]);const R=Re(()=>({reference:P,floating:k,setReference:b,setFloating:S}),[b,S]),A=Re(()=>({reference:C,floating:T}),[C,T]),I=Re(()=>{const D={position:n,left:0,top:0};if(!A.floating)return D;const F=Sg(A.floating,u.x),K=Sg(A.floating,u.y);return c?{...D,transform:"translate("+F+"px, "+K+"px)",...wg(A.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:K}},[n,c,A.floating,u.x,u.y]);return Re(()=>({...u,update:q,refs:R,elements:A,floatingStyles:I}),[u,q,R,A,I])}var mE=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?_g({element:r.current,padding:i}).fn(n):{}:r?_g({element:r,padding:i}).fn(n):{}}}},fE=(e,t)=>{const n=aE(e);return{name:n.name,fn:n.fn,options:[e,t]}},hE=(e,t)=>{const n=oE(e);return{name:n.name,fn:n.fn,options:[e,t]}},gE=(e,t)=>({fn:dE(e).fn,options:[e,t]}),vE=(e,t)=>{const n=sE(e);return{name:n.name,fn:n.fn,options:[e,t]}},yE=(e,t)=>{const n=cE(e);return{name:n.name,fn:n.fn,options:[e,t]}},bE=(e,t)=>{const n=lE(e);return{name:n.name,fn:n.fn,options:[e,t]}},_E=(e,t)=>{const n=mE(e);return{name:n.name,fn:n.fn,options:[e,t]}},wE="Arrow",Cg=V((e,t)=>{const{children:n,width:r=10,height:i=5,...a}=e;return o(pe.svg,{...a,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o("polygon",{points:"0,0 30,0 15,10"})})});Cg.displayName=wE;var SE=Cg;function Wl(e){const[t,n]=x(void 0);return We(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var zl="Popper",[Ng,Pn]=st(zl),[CE,Tg]=Ng(zl),Ig=e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null);return o(CE,{scope:t,anchor:r,onAnchorChange:i,children:n})};Ig.displayName=zl;var kg="PopperAnchor",Eg=V((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,a=Tg(kg,n),s=B(null),c=Se(t,s),l=B(null);return J(()=>{const d=l.current;l.current=r?.current||s.current,d!==l.current&&a.onAnchorChange(l.current)}),r?null:o(pe.div,{...i,ref:c})});Eg.displayName=kg;var Jl="PopperContent",[NE,TE]=Ng(Jl),Pg=V((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:a="center",alignOffset:s=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:p="partial",hideWhenDetached:m=!1,updatePositionStrategy:f="optimized",onPlaced:g,...h}=e,v=Tg(Jl,n),[w,b]=x(null),S=Se(t,ne=>b(ne)),[C,T]=x(null),P=Wl(C),k=P?.width??0,M=P?.height??0,U=r+(a!=="center"?"-"+a:""),E=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},j=Array.isArray(d)?d:[d],O=j.length>0,q={padding:E,boundary:j.filter(kE),altBoundary:O},{refs:L,floatingStyles:R,placement:A,isPositioned:I,middlewareData:D}=pE({strategy:"fixed",placement:U,whileElementsMounted:(...ne)=>iE(...ne,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[fE({mainAxis:i+M,alignmentAxis:s}),l&&hE({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?gE():void 0,...q}),l&&vE({...q}),yE({...q,apply:({elements:ne,rects:ke,availableWidth:ge,availableHeight:ae})=>{const{width:xe,height:de}=ke.reference,Te=ne.floating.style;Te.setProperty("--radix-popper-available-width",`${ge}px`),Te.setProperty("--radix-popper-available-height",`${ae}px`),Te.setProperty("--radix-popper-anchor-width",`${xe}px`),Te.setProperty("--radix-popper-anchor-height",`${de}px`)}}),C&&_E({element:C,padding:c}),EE({arrowWidth:k,arrowHeight:M}),m&&bE({strategy:"referenceHidden",...q})]}),[F,K]=Rg(A),ce=lt(g);We(()=>{I&&ce?.()},[I,ce]);const ie=D.arrow?.x,re=D.arrow?.y,ye=D.arrow?.centerOffset!==0,[Y,he]=x();return We(()=>{w&&he(window.getComputedStyle(w).zIndex)},[w]),o("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...R,transform:I?R.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[D.transformOrigin?.x,D.transformOrigin?.y].join(" "),...D.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o(NE,{scope:n,placedSide:F,onArrowChange:T,arrowX:ie,arrowY:re,shouldHideArrow:ye,children:o(pe.div,{"data-side":F,"data-align":K,...h,ref:S,style:{...h.style,animation:I?void 0:"none"}})})})});Pg.displayName=Jl;var Ag="PopperArrow",IE={top:"bottom",right:"left",bottom:"top",left:"right"},xg=V(function(t,n){const{__scopePopper:r,...i}=t,a=TE(Ag,r),s=IE[a.placedSide];return o("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:o(SE,{...i,ref:n,style:{...i.style,display:"block"}})})});xg.displayName=Ag;function kE(e){return e!==null}var EE=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[l,d]=Rg(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,m=(i.arrow?.y??0)+c/2;let f="",g="";return l==="bottom"?(f=a?u:`${p}px`,g=`${-c}px`):l==="top"?(f=a?u:`${p}px`,g=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,g=a?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,g=a?u:`${m}px`),{data:{x:f,y:g}}}});function Rg(e){const[t,n="center"]=e.split("-");return[t,n]}var ia=Ig,aa=Eg,os=Pg,ss=xg,cs="Popover",[Dg,oF]=st(cs,[Pn]),oa=Pn(),[PE,An]=Dg(cs),Lg=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,c=oa(t),l=B(null),[d,u]=x(!1),[p,m]=It({prop:r,defaultProp:i??!1,onChange:a,caller:cs});return o(ia,{...c,children:o(PE,{scope:t,contentId:ct(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:se(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:se(()=>u(!0),[]),onCustomAnchorRemove:se(()=>u(!1),[]),modal:s,children:n})})};Lg.displayName=cs;var $g="PopoverAnchor",Mg=V((e,t)=>{const{__scopePopover:n,...r}=e,i=An($g,n),a=oa(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return J(()=>(s(),()=>c()),[s,c]),o(aa,{...a,...r,ref:t})});Mg.displayName=$g;var Og="PopoverTrigger",jg=V((e,t)=>{const{__scopePopover:n,...r}=e,i=An(Og,n),a=oa(n),s=Se(t,i.triggerRef),c=o(pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Hg(i.open),...r,ref:s,onClick:Q(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:o(aa,{asChild:!0,...a,children:c})});jg.displayName=Og;var Yl="PopoverPortal",[AE,xE]=Dg(Yl,{forceMount:void 0}),Fg=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=An(Yl,t);return o(AE,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Zn,{asChild:!0,container:i,children:r})})})};Fg.displayName=Yl;var Zr="PopoverContent",Bg=V((e,t)=>{const n=xE(Zr,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=An(Zr,e.__scopePopover);return o(nt,{present:r||a.open,children:a.modal?o(DE,{...i,ref:t}):o(LE,{...i,ref:t})})});Bg.displayName=Zr;var RE=Xn("PopoverContent.RemoveScroll"),DE=V((e,t)=>{const n=An(Zr,e.__scopePopover),r=B(null),i=Se(t,r),a=B(!1);return J(()=>{const s=r.current;if(s)return Io(s)},[]),o(Ui,{as:RE,allowPinchZoom:!0,children:o(Ug,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Q(e.onCloseAutoFocus,s=>{s.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Q(e.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;a.current=c.button===2||l},{checkForDefaultPrevented:!1}),onFocusOutside:Q(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),LE=V((e,t)=>{const n=An(Zr,e.__scopePopover),r=B(!1),i=B(!1);return o(Ug,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||n.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;n.triggerRef.current?.contains(s)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Ug=V((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=An(Zr,n),f=oa(n);return yo(),o(Fi,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o(Qn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:o(os,{"data-state":Hg(m.open),role:"dialog",id:m.contentId,...f,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Gg="PopoverClose",$E=V((e,t)=>{const{__scopePopover:n,...r}=e,i=An(Gg,n);return o(pe.button,{type:"button",...r,ref:t,onClick:Q(e.onClick,()=>i.onOpenChange(!1))})});$E.displayName=Gg;var ME="PopoverArrow",OE=V((e,t)=>{const{__scopePopover:n,...r}=e,i=oa(n);return o(ss,{...i,...r,ref:t})});OE.displayName=ME;function Hg(e){return e?"open":"closed"}var qg=Lg,jE=Mg,FE=jg,Kg=Fg,Vg=Bg;function Xl(e){return e.trim()}function Wg({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:a,"aria-labelledby":s}){const[c,l]=x(!1),[d,u]=x(""),[p,m]=x(0),f=B(null),g=Re(()=>{const E=new Set,j=[];for(const O of[...n,...e]){const q=Xl(O);!q||E.has(q)||(E.add(q),j.push(q))}return j.sort((O,q)=>O.localeCompare(q))},[n,e]),h=Xl(d),v=h.toLowerCase(),w=Re(()=>v?g.filter(E=>E.toLowerCase().includes(v)):g,[g,v]),b=h?g.some(E=>E.toLowerCase()===v):!1,S=!!h&&!b,C=w.length+(S?1:0);J(()=>{p>=C&&m(Math.max(0,C-1))},[C,p]),J(()=>{if(!c)return;const E=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(E)},[c]);const T=E=>{e.includes(E)?t(e.filter(j=>j!==E)):t(Array.from(new Set([...e,E])))},P=E=>{const j=Xl(E);j&&(t(Array.from(new Set([...e,j]))),u(""),m(0))},k=E=>{if(E<w.length){const j=w[E];j&&T(j);return}S&&P(h)},M=E=>{if(E.key==="ArrowDown"){E.preventDefault(),m(j=>Math.min(C-1,j+1));return}if(E.key==="ArrowUp"){E.preventDefault(),m(j=>Math.max(0,j-1));return}if(E.key==="Enter"){E.preventDefault(),k(p);return}},U=E=>{t(e.filter(j=>j!==E))};return o("div",{class:"project-scope-picker",children:[o("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?o("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(E=>o("li",{class:"project-scope-picker-selected-chip",children:[o("span",{children:E}),a?null:o("button",{"aria-label":`Remove ${E}`,class:"project-scope-picker-selected-remove",onClick:()=>U(E),type:"button",children:"×"})]},E))}),o(qg,{onOpenChange:E=>{l(E),E||(u(""),m(0))},open:c,children:[o(FE,{asChild:!0,children:o("button",{class:"project-scope-picker-trigger settings-button",disabled:a,type:"button",children:[o("span",{"aria-hidden":"true",children:"+"}),o("span",{children:r||"Add project"})]})}),o(Kg,{children:o(Vg,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[o("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:E=>{u(E.currentTarget.value),m(0)},onKeyDown:M,placeholder:"Search or create…",ref:f,type:"text",value:d}),o("div",{class:"project-scope-picker-results",role:"listbox",children:[w.length===0&&!S?o("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,w.map((E,j)=>{const O=e.includes(E);return o("button",{"aria-selected":O,class:j===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(j),T(E)},onMouseEnter:()=>m(j),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:O?"✓":""}),o("span",{class:"project-scope-picker-row-label",children:E})]},E)}),S?o("button",{"aria-selected":!1,class:p===w.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>P(h),onMouseEnter:()=>m(w.length),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),o("span",{class:"project-scope-picker-row-label",children:`Create "${h}"`})]}):null]})]})})]})]})}function Ql(e){const t=B({value:e,previous:e});return Re(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var ls="Switch",[BE,sF]=st(ls),[UE,GE]=BE(ls),zg=V((e,t)=>{const{__scopeSwitch:n,name:r,checked:i,defaultChecked:a,required:s,disabled:c,value:l="on",onCheckedChange:d,form:u,...p}=e,[m,f]=x(null),g=Se(t,S=>f(S)),h=B(!1),v=m?u||!!m.closest("form"):!0,[w,b]=It({prop:i,defaultProp:a??!1,onChange:d,caller:ls});return o(UE,{scope:n,checked:w,disabled:c,children:[o(pe.button,{type:"button",role:"switch","aria-checked":w,"aria-required":s,"data-state":Qg(w),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:g,onClick:Q(e.onClick,S=>{b(C=>!C),v&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),v&&o(Xg,{control:m,bubbles:!h.current,name:r,value:l,checked:w,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});zg.displayName=ls;var Jg="SwitchThumb",Yg=V((e,t)=>{const{__scopeSwitch:n,...r}=e,i=GE(Jg,n);return o(pe.span,{"data-state":Qg(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Yg.displayName=Jg;var HE="SwitchBubbleInput",Xg=V(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=B(null),c=Se(s,a),l=Ql(n),d=Wl(t);return J(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Xg.displayName=HE;function Qg(e){return e?"checked":"unchecked"}var qE=zg,KE=Yg;function ei({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:a,onCheckedChange:s,thumbClassName:c}){return o(qE,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:a,onCheckedChange:s,children:o(KE,{className:c})})}function oe(e,t="success"){II(e,t)}function Zg(e){return`${fk}:${String(e||"").trim()}`}function VE(e){try{return localStorage.getItem(Zg(e))||""}catch{return""}}function WE(e,t){try{localStorage.setItem(Zg(e),t)}catch{}}function sr(){return String(_.coordinatorAdminTargetGroup||"").trim()}function Zl(e){_.coordinatorAdminTargetGroup=e,WE(_.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function ti(){return(Array.isArray(_.lastCoordinatorAdminGroups)?_.lastCoordinatorAdminGroups:[]).map(e=>({archived_at:e.archived_at??null,display_name:e.display_name??null,group_id:String(e.group_id||"").trim()})).filter(e=>e.group_id)}function zE(){const e=new Map;for(const t of ti())e.set(t.group_id,t.display_name||t.group_id);H.groupRenameDrafts.clear();for(const[t,n]of e.entries())H.groupRenameDrafts.set(t,n)}function JE(){const e=sr();return ti().find(t=>t.group_id===e)||null}function ev(){const e=_.lastCoordinatorAdminStatus,t=ti(),n=String(e?.active_group||"").trim(),r=VE(e?.coordinator_url||null),i=sr(),a=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(a.size===0||a.has(s))?s:n||t[0]?.group_id||"";return Zl(c),c}function YE(){const e=new Map,t=new Map,n=Array.isArray(_.lastCoordinatorAdminDevices)?_.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const a=String(r.display_name||""),s=H.deviceRenameDrafts.get(i),c=H.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:a),t.set(i,a)}H.deviceRenameDrafts.clear();for(const[r,i]of e.entries())H.deviceRenameDrafts.set(r,i);H.deviceRenameServerNames.clear();for(const[r,i]of t.entries())H.deviceRenameServerNames.set(r,i)}function XE(e,t){return t&&t.groupId===e?t:null}function QE(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open Team defaults to inspect"}function ZE(e,t){return e?.loaded?e.auto_grant_default_space_on_join?"On for the default Space":"Off — Space access stays explicit":t?.autoGrantDefaultSpaceOnJoin===!0?"On for the default Space":t?.autoGrantDefaultSpaceOnJoin===!1?"Off — Space access stays explicit":"Open Team defaults to inspect"}function eP(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function tP(e){const t=eP(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function nP(e){const t=XE(e.groupId,e.setupGuide);return{autoGrant:ZE(e.preferences,t),defaultSpace:QE(e.preferences,t),spaces:tP(e.scopeManagement)}}var ed=null,ds=null,td=null;function rP(){return ed}function nd(e){ds=e}function tv(e){td=e}function iP(e){return td===e}function aP(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function rd(e){return!ed||!ds?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function us(e){ed=e,td?.(e)}function xn(e){const t=ds;ds=null,us(null),t?.(e)}function oP(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var sP=V(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:a=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=B(null);po(p,()=>m.current,[]);const[f,g]=x(!1),[h,v]=x(-1),w=Re(()=>{const T=t.trim().toLowerCase();return(T?r.filter(P=>P.toLowerCase().includes(T)):r).slice(0,a)},[t,r,a]);J(()=>{h>=w.length&&v(w.length-1)},[w.length,h]);const b=f&&w.length>0,S=T=>{n(T),g(!1),v(-1),m.current?.focus()};return o(qg,{open:b,onOpenChange:g,children:[o(jE,{asChild:!0,children:o("input",{...u,ref:m,className:d,value:t,onInput:T=>{n(T.currentTarget.value),g(!0),v(-1)},onFocus:T=>{c?.(T)},onBlur:T=>{window.setTimeout(()=>g(!1),120),l?.(T)},onKeyDown:T=>{if(T.key==="ArrowDown"){T.preventDefault(),g(!0),v(P=>w.length===0?-1:Math.min(P+1,w.length-1));return}if(T.key==="ArrowUp"){T.preventDefault(),f||g(!0),v(P=>Math.max(P-1,-1));return}if(T.key==="Escape"&&b){T.preventDefault(),g(!1),v(-1);return}if((T.key==="Tab"||T.key==="Enter")&&h>=0){const P=w[h];if(P){T.preventDefault(),S(P);return}}if(T.key==="Enter"&&i){T.preventDefault(),i();return}s?.(T)},role:"combobox","aria-autocomplete":"list","aria-expanded":b,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),o(Kg,{children:o(Vg,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:T=>T.preventDefault(),onCloseAutoFocus:T=>T.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:o("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:w.map((T,P)=>{const k=P===h;return o("div",{"aria-selected":k,className:k?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${P}`,onMouseDown:M=>{M.preventDefault(),S(T)},onMouseEnter:()=>v(P),role:"option",tabIndex:-1,children:T},T)})})})})]})}),id="Radio",[cP,nv]=st(id),[lP,dP]=cP(id),rv=V((e,t)=>{const{__scopeRadio:n,name:r,checked:i=!1,required:a,disabled:s,value:c="on",onCheck:l,form:d,...u}=e,[p,m]=x(null),f=Se(t,v=>m(v)),g=B(!1),h=p?d||!!p.closest("form"):!0;return o(lP,{scope:n,checked:i,disabled:s,children:[o(pe.button,{type:"button",role:"radio","aria-checked":i,"data-state":sv(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:Q(e.onClick,v=>{i||l?.(),h&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),h&&o(ov,{control:p,bubbles:!g.current,name:r,value:c,checked:i,required:a,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});rv.displayName=id;var iv="RadioIndicator",av=V((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,a=dP(iv,n);return o(nt,{present:r||a.checked,children:o(pe.span,{"data-state":sv(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:t})})});av.displayName=iv;var uP="RadioBubbleInput",ov=V(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=B(null),c=Se(s,a),l=Ql(n),d=Wl(t);return J(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o(pe.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});ov.displayName=uP;function sv(e){return e?"checked":"unchecked"}var pP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],ps="RadioGroup",[mP,cF]=st(ps,[zr,nv]),cv=zr(),lv=nv(),[fP,hP]=mP(ps),dv=V((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:i,value:a,required:s=!1,disabled:c=!1,orientation:l,dir:d,loop:u=!0,onValueChange:p,...m}=e,f=cv(n),g=ea(d),[h,v]=It({prop:a,defaultProp:i??null,onChange:p,caller:ps});return o(fP,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:v,children:o(Pl,{asChild:!0,...f,orientation:l,dir:g,loop:u,children:o(pe.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:g,...m,ref:t})})})});dv.displayName=ps;var uv="RadioGroupItem",pv=V((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,a=hP(uv,n),s=a.disabled||r,c=cv(n),l=lv(n),d=B(null),u=Se(t,d),p=a.value===i.value,m=B(!1);return J(()=>{const f=h=>{pP.includes(h.key)&&(m.current=!0)},g=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),o(Al,{asChild:!0,...c,focusable:!s,active:p,children:o(rv,{disabled:s,required:a.required,checked:p,...l,...i,name:a.name,ref:u,onCheck:()=>a.onValueChange(i.value),onKeyDown:Q(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:Q(i.onFocus,()=>{m.current&&d.current?.click()})})})});pv.displayName=uv;var gP="RadioGroupIndicator",mv=V((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return o(av,{...lv(n),...r,ref:t})});mv.displayName=gP;var vP=dv,yP=pv,bP=mv;function _P({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:a,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return o(vP,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,m)=>{const f=`radio-option-input-${m}`,g=`radio-option-label-${m}`;return o("label",{className:i,htmlFor:f,children:[o(yP,{id:f,"aria-labelledby":g,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:o(bP,{className:r})}),o("span",{className:a,id:g,children:p.label})]},p.value)})})}function fv(e,[t,n]){return Math.min(n,Math.max(t,e))}var wP=[" ","Enter","ArrowUp","ArrowDown"],SP=[" ","Enter"],cr="Select",[ms,fs,CP]=Uo(cr),[ni,lF]=st(cr,[CP,Pn]),hs=Pn(),[NP,Rn]=ni(cr),[TP,IP]=ni(cr),hv=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:a,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:m,required:f,form:g}=e,h=hs(t),[v,w]=x(null),[b,S]=x(null),[C,T]=x(!1),P=ea(d),[k,M]=It({prop:r,defaultProp:i??!1,onChange:a,caller:cr}),[U,E]=It({prop:s,defaultProp:c,onChange:l,caller:cr}),j=B(null),O=v?g||!!v.closest("form"):!0,[q,L]=x(new Set),R=Array.from(q).map(A=>A.props.value).join(";");return o(ia,{...h,children:o(NP,{required:f,scope:t,trigger:v,onTriggerChange:w,valueNode:b,onValueNodeChange:S,valueNodeHasChildren:C,onValueNodeHasChildrenChange:T,contentId:ct(),value:U,onValueChange:E,open:k,onOpenChange:M,dir:P,triggerPointerDownPosRef:j,disabled:m,children:[o(ms.Provider,{scope:t,children:o(TP,{scope:e.__scopeSelect,onNativeOptionAdd:se(A=>{L(I=>new Set(I).add(A))},[]),onNativeOptionRemove:se(A=>{L(I=>{const D=new Set(I);return D.delete(A),D})},[]),children:n})}),O?o($v,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:U,onChange:A=>E(A.target.value),disabled:m,form:g,children:[U===void 0?o("option",{value:""}):null,Array.from(q)]},R):null]})})};hv.displayName=cr;var gv="SelectTrigger",vv=V((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,a=hs(n),s=Rn(gv,n),c=s.disabled||r,l=Se(t,s.onTriggerChange),d=fs(n),u=B("touch"),[p,m,f]=Ov(h=>{const v=d().filter(b=>!b.disabled),w=jv(v,h,v.find(b=>b.value===s.value));w!==void 0&&s.onValueChange(w.value)}),g=h=>{c||(s.onOpenChange(!0),f()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return o(aa,{asChild:!0,...a,children:o(pe.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Mv(s.value)?"":void 0,...i,ref:l,onClick:Q(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&g(h)}),onPointerDown:Q(i.onPointerDown,h=>{u.current=h.pointerType;const v=h.target;v.hasPointerCapture(h.pointerId)&&v.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:Q(i.onKeyDown,h=>{const v=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(v&&h.key===" ")&&wP.includes(h.key)&&(g(),h.preventDefault())})})})});vv.displayName=gv;var yv="SelectValue",bv=V((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:a,placeholder:s="",...c}=e,l=Rn(yv,n),{onValueNodeHasChildrenChange:d}=l,u=a!==void 0,p=Se(t,l.onValueNodeChange);return We(()=>{d(u)},[d,u]),o(pe.span,{...c,ref:p,style:{pointerEvents:"none"},children:Mv(l.value)?o(Z,{children:s}):a})});bv.displayName=yv;var kP="SelectIcon",_v=V((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return o(pe.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});_v.displayName=kP;var EP="SelectPortal",wv=e=>o(Zn,{asChild:!0,...e});wv.displayName=EP;var lr="SelectContent",Sv=V((e,t)=>{const n=Rn(lr,e.__scopeSelect),[r,i]=x();if(We(()=>{i(new DocumentFragment)},[]),!n.open){const a=r;return a?cn(o(Cv,{scope:e.__scopeSelect,children:o(ms.Slot,{scope:e.__scopeSelect,children:o("div",{children:e.children})})}),a):null}return o(Nv,{...e,ref:t})});Sv.displayName=lr;var Mt=10,[Cv,Dn]=ni(lr),PP="SelectContentImpl",AP=Xn("SelectContent.RemoveScroll"),Nv=V((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:s,side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v,...w}=e,b=Rn(lr,n),[S,C]=x(null),[T,P]=x(null),k=Se(t,ne=>C(ne)),[M,U]=x(null),[E,j]=x(null),O=fs(n),[q,L]=x(!1),R=B(!1);J(()=>{if(S)return Io(S)},[S]),yo();const A=se(ne=>{const[ke,...ge]=O().map(de=>de.ref.current),[ae]=ge.slice(-1),xe=document.activeElement;for(const de of ne)if(de===xe||(de?.scrollIntoView({block:"nearest"}),de===ke&&T&&(T.scrollTop=0),de===ae&&T&&(T.scrollTop=T.scrollHeight),de?.focus(),document.activeElement!==xe))return},[O,T]),I=se(()=>A([M,S]),[A,M,S]);J(()=>{q&&I()},[q,I]);const{onOpenChange:D,triggerPointerDownPosRef:F}=b;J(()=>{if(S){let ne={x:0,y:0};const ke=ae=>{ne={x:Math.abs(Math.round(ae.pageX)-(F.current?.x??0)),y:Math.abs(Math.round(ae.pageY)-(F.current?.y??0))}},ge=ae=>{ne.x<=10&&ne.y<=10?ae.preventDefault():S.contains(ae.target)||D(!1),document.removeEventListener("pointermove",ke),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",ke),document.addEventListener("pointerup",ge,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ke),document.removeEventListener("pointerup",ge,{capture:!0})}}},[S,D,F]),J(()=>{const ne=()=>D(!1);return window.addEventListener("blur",ne),window.addEventListener("resize",ne),()=>{window.removeEventListener("blur",ne),window.removeEventListener("resize",ne)}},[D]);const[K,ce]=Ov(ne=>{const ke=O().filter(ae=>!ae.disabled),ge=jv(ke,ne,ke.find(ae=>ae.ref.current===document.activeElement));ge&&setTimeout(()=>ge.ref.current.focus())}),ie=se((ne,ke,ge)=>{const ae=!R.current&&!ge;(b.value!==void 0&&b.value===ke||ae)&&(U(ne),ae&&(R.current=!0))},[b.value]),re=se(()=>S?.focus(),[S]),ye=se((ne,ke,ge)=>{const ae=!R.current&&!ge;(b.value!==void 0&&b.value===ke||ae)&&j(ne)},[b.value]),Y=r==="popper"?ad:Tv,he=Y===ad?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v}:{};return o(Cv,{scope:n,content:S,viewport:T,onViewportChange:P,itemRefCallback:ie,selectedItem:M,onItemLeave:re,itemTextRefCallback:ye,focusSelectedItem:I,selectedItemText:E,position:r,isPositioned:q,searchRef:K,children:o(Ui,{as:AP,allowPinchZoom:!0,children:o(Fi,{asChild:!0,trapped:b.open,onMountAutoFocus:ne=>{ne.preventDefault()},onUnmountAutoFocus:Q(i,ne=>{b.trigger?.focus({preventScroll:!0}),ne.preventDefault()}),children:o(Qn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:ne=>ne.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:o(Y,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:ne=>ne.preventDefault(),...w,...he,onPlaced:()=>L(!0),ref:k,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:Q(w.onKeyDown,ne=>{const ke=ne.ctrlKey||ne.altKey||ne.metaKey;if(ne.key==="Tab"&&ne.preventDefault(),!ke&&ne.key.length===1&&ce(ne.key),["ArrowUp","ArrowDown","Home","End"].includes(ne.key)){let ge=O().filter(ae=>!ae.disabled).map(ae=>ae.ref.current);if(["ArrowUp","End"].includes(ne.key)&&(ge=ge.slice().reverse()),["ArrowUp","ArrowDown"].includes(ne.key)){const ae=ne.target,xe=ge.indexOf(ae);ge=ge.slice(xe+1)}setTimeout(()=>A(ge)),ne.preventDefault()}})})})})})})});Nv.displayName=PP;var xP="SelectItemAlignedPosition",Tv=V((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,a=Rn(lr,n),s=Dn(lr,n),[c,l]=x(null),[d,u]=x(null),p=Se(t,P=>u(P)),m=fs(n),f=B(!1),g=B(!0),{viewport:h,selectedItem:v,selectedItemText:w,focusSelectedItem:b}=s,S=se(()=>{if(a.trigger&&a.valueNode&&c&&d&&h&&v&&w){const P=a.trigger.getBoundingClientRect(),k=d.getBoundingClientRect(),M=a.valueNode.getBoundingClientRect(),U=w.getBoundingClientRect();if(a.dir!=="rtl"){const ge=U.left-k.left,ae=M.left-ge,xe=P.left-ae,de=P.width+xe,Te=Math.max(de,k.width),ue=window.innerWidth-Mt,z=fv(ae,[Mt,Math.max(Mt,ue-Te)]);c.style.minWidth=de+"px",c.style.left=z+"px"}else{const ge=k.right-U.right,ae=window.innerWidth-M.right-ge,xe=window.innerWidth-P.right-ae,de=P.width+xe,Te=Math.max(de,k.width),ue=window.innerWidth-Mt,z=fv(ae,[Mt,Math.max(Mt,ue-Te)]);c.style.minWidth=de+"px",c.style.right=z+"px"}const E=m(),j=window.innerHeight-Mt*2,O=h.scrollHeight,q=window.getComputedStyle(d),L=parseInt(q.borderTopWidth,10),R=parseInt(q.paddingTop,10),A=parseInt(q.borderBottomWidth,10),I=parseInt(q.paddingBottom,10),D=L+R+O+I+A,F=Math.min(v.offsetHeight*5,D),K=window.getComputedStyle(h),ce=parseInt(K.paddingTop,10),ie=parseInt(K.paddingBottom,10),re=P.top+P.height/2-Mt,ye=j-re,Y=v.offsetHeight/2,he=v.offsetTop+Y,ne=L+R+he,ke=D-ne;if(ne<=re){const ge=E.length>0&&v===E[E.length-1].ref.current;c.style.bottom="0px";const ae=d.clientHeight-h.offsetTop-h.offsetHeight,xe=ne+Math.max(ye,Y+(ge?ie:0)+ae+A);c.style.height=xe+"px"}else{const ge=E.length>0&&v===E[0].ref.current;c.style.top="0px";const ae=Math.max(re,L+h.offsetTop+(ge?ce:0)+Y)+ke;c.style.height=ae+"px",h.scrollTop=ne-re+h.offsetTop}c.style.margin=`${Mt}px 0`,c.style.minHeight=F+"px",c.style.maxHeight=j+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,a.trigger,a.valueNode,c,d,h,v,w,a.dir,r]);We(()=>S(),[S]);const[C,T]=x();return We(()=>{d&&T(window.getComputedStyle(d).zIndex)},[d]),o(DP,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:se(P=>{P&&g.current===!0&&(S(),b?.(),g.current=!1)},[S,b]),children:o("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:o(pe.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});Tv.displayName=xP;var RP="SelectPopperPosition",ad=V((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Mt,...a}=e,s=hs(n);return o(os,{...s,...a,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});ad.displayName=RP;var[DP,od]=ni(lr,{}),sd="SelectViewport",Iv=V((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,a=Dn(sd,n),s=od(sd,n),c=Se(t,a.onViewportChange),l=B(0);return o(Z,{children:[o("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),o(ms.Slot,{scope:n,children:o(pe.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Q(i.onScroll,d=>{const u=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=s;if(m?.current&&p){const f=Math.abs(l.current-u.scrollTop);if(f>0){const g=window.innerHeight-Mt*2,h=parseFloat(p.style.minHeight),v=parseFloat(p.style.height),w=Math.max(h,v);if(w<g){const b=w+f,S=Math.min(g,b),C=b-S;p.style.height=S+"px",p.style.bottom==="0px"&&(u.scrollTop=C>0?C:0,p.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});Iv.displayName=sd;var kv="SelectGroup",[LP,$P]=ni(kv),MP=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=ct();return o(LP,{scope:n,id:i,children:o(pe.div,{role:"group","aria-labelledby":i,...r,ref:t})})});MP.displayName=kv;var Ev="SelectLabel",OP=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=$P(Ev,n);return o(pe.div,{id:i.id,...r,ref:t})});OP.displayName=Ev;var gs="SelectItem",[jP,Pv]=ni(gs),Av=V((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:a,...s}=e,c=Rn(gs,n),l=Dn(gs,n),d=c.value===r,[u,p]=x(a??""),[m,f]=x(!1),g=Se(t,b=>l.itemRefCallback?.(b,r,i)),h=ct(),v=B("touch"),w=()=>{i||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return o(jP,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:se(b=>{p(S=>S||(b?.textContent??"").trim())},[]),children:o(ms.ItemSlot,{scope:n,value:r,disabled:i,textValue:u,children:o(pe.div,{role:"option","aria-labelledby":h,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...s,ref:g,onFocus:Q(s.onFocus,()=>f(!0)),onBlur:Q(s.onBlur,()=>f(!1)),onClick:Q(s.onClick,()=>{v.current!=="mouse"&&w()}),onPointerUp:Q(s.onPointerUp,()=>{v.current==="mouse"&&w()}),onPointerDown:Q(s.onPointerDown,b=>{v.current=b.pointerType}),onPointerMove:Q(s.onPointerMove,b=>{v.current=b.pointerType,i?l.onItemLeave?.():v.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Q(s.onPointerLeave,b=>{b.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:Q(s.onKeyDown,b=>{l.searchRef?.current!==""&&b.key===" "||(SP.includes(b.key)&&w(),b.key===" "&&b.preventDefault())})})})})});Av.displayName=gs;var sa="SelectItemText",xv=V((e,t)=>{const{__scopeSelect:n,className:r,style:i,...a}=e,s=Rn(sa,n),c=Dn(sa,n),l=Pv(sa,n),d=IP(sa,n),[u,p]=x(null),m=Se(t,w=>p(w),l.onItemTextChange,w=>c.itemTextRefCallback?.(w,l.value,l.disabled)),f=u?.textContent,g=Re(()=>o("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:v}=d;return We(()=>(h(g),()=>v(g)),[h,v,g]),o(Z,{children:[o(pe.span,{id:l.textId,...a,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?cn(a.children,s.valueNode):null]})});xv.displayName=sa;var Rv="SelectItemIndicator",Dv=V((e,t)=>{const{__scopeSelect:n,...r}=e;return Pv(Rv,n).isSelected?o(pe.span,{"aria-hidden":!0,...r,ref:t}):null});Dv.displayName=Rv;var cd="SelectScrollUpButton",FP=V((e,t)=>{const n=Dn(cd,e.__scopeSelect),r=od(cd,e.__scopeSelect),[i,a]=x(!1),s=Se(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){a(l.scrollTop>0)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Lv,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});FP.displayName=cd;var ld="SelectScrollDownButton",BP=V((e,t)=>{const n=Dn(ld,e.__scopeSelect),r=od(ld,e.__scopeSelect),[i,a]=x(!1),s=Se(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight;a(Math.ceil(l.scrollTop)<d)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Lv,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});BP.displayName=ld;var Lv=V((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,a=Dn("SelectScrollButton",n),s=B(null),c=fs(n),l=se(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return J(()=>()=>l(),[l]),We(()=>{c().find(d=>d.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),o(pe.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:Q(i.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:Q(i.onPointerMove,()=>{a.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:Q(i.onPointerLeave,()=>{l()})})}),UP="SelectSeparator",GP=V((e,t)=>{const{__scopeSelect:n,...r}=e;return o(pe.div,{"aria-hidden":!0,...r,ref:t})});GP.displayName=UP;var dd="SelectArrow",HP=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=hs(n),a=Rn(dd,n),s=Dn(dd,n);return a.open&&s.position==="popper"?o(ss,{...i,...r,ref:t}):null});HP.displayName=dd;var qP="SelectBubbleInput",$v=V(({__scopeSelect:e,value:t,...n},r)=>{const i=B(null),a=Se(r,i),s=Ql(t);return J(()=>{const c=i.current;if(!c)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==t&&d){const u=new Event("change",{bubbles:!0});d.call(c,t),c.dispatchEvent(u)}},[s,t]),o(pe.select,{...n,style:{...sh,...n.style},ref:a,defaultValue:t})});$v.displayName=qP;function Mv(e){return e===""||e===void 0}function Ov(e){const t=lt(e),n=B(""),r=B(0),i=se(s=>{const c=n.current+s;t(c),(function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=se(()=>{n.current="",window.clearTimeout(r.current)},[]);return J(()=>()=>window.clearTimeout(r.current),[]),[n,i,a]}function jv(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=KP(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function KP(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var VP=hv,WP=vv,zP=bv,JP=_v,YP=wv,XP=Sv,QP=Iv,ZP=Av,eA=xv,tA=Dv,Fv="__codemem-empty-select__";function nA(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Open"}),o("path",{d:"m6 9 6 6 6-6"})]})}function rA(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Selected"}),o("path",{d:"M20 6 9 17l-5-5"})]})}function ud(e){return e===""?Fv:e}function iA(e){return e===Fv?"":e}function Ln({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:a,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const m=u?ud(u):void 0;return o(VP,{disabled:r,onValueChange:f=>s(iA(f)),value:m,children:[o(WP,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[o(zP,{placeholder:l}),o(JP,{className:"sync-radix-select-icon","aria-hidden":"true",children:o(nA,{})})]}),o(YP,{children:o(XP,{className:n,position:"popper",children:o(QP,{className:p,children:c.map(f=>o(ZP,{className:a,disabled:f.disabled,value:ud(f.value),children:[o(eA,{children:f.label}),o(tA,{className:"sync-radix-select-indicator",children:o(rA,{})})]},ud(f.value)))})})})]})}function aA({descriptionId:e,request:t}){const[n,r]=x("choice"),[i,a]=x(t.actors.find(v=>v.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=x("");J(()=>{r("choice");const v=t.actors.find(b=>b.isLocal)?.actorId||t.actors[0]?.actorId||"",w=t.actors.find(b=>b.actorId!==v)?.actorId||"";a(v),c(w)},[t]);const l=t.actors.find(v=>v.actorId===i)||t.actors[0],d=t.actors.filter(v=>v.actorId!==i),u=d.find(v=>v.actorId===s)||d[0],p=t.actors.map(v=>({label:o(Z,{children:[v.label,v.isLocal?" (You)":""]}),value:v.actorId})),m=d.map(v=>({label:`${v.label}${v.isLocal?" (You)":""}`,value:v.actorId})),f=!!(l?.actorId&&u?.actorId),g=()=>{!l?.actorId||!u?.actorId||xn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=v=>{const w=v.target instanceof HTMLElement?v.target:null;v.defaultPrevented||v.isComposing||v.key!=="Enter"||w?.closest(".sync-dialog-radio-list")&&f&&(v.preventDefault(),g())};return n==="choice"?o("div",{className:"sync-dialog-stack",children:o("ul",{className:"sync-dialog-choice-list",children:[o("li",{children:o("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>xn({action:"different-people"}),type:"button",children:"These are different people"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>xn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):o("div",{className:"sync-dialog-stack",onKeyDown:v=>{h(v),Wr(v,{onSubmit:g,disabled:!f})},children:[o("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),o(_P,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:i,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:a,options:p,rootClassName:"sync-dialog-radio-list",value:i}),o("div",{className:"field",children:[o("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),o(Ln,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:c,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:u?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),o("button",{className:"settings-button","data-primary-action":"true",disabled:!f,onClick:g,type:"button",children:"Combine people"})]})]})}function oA({descriptionId:e,request:t,titleId:n}){const[r,i]=x(t.kind==="input"&&t.initialValue||""),[a,s]=x(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";J(()=>{t.kind==="input"&&(i(t.initialValue||""),s(null))},[t]);const d=c&&t.cancelLabel||"Cancel",u=c?t.confirmLabel||(t.kind==="confirm"?"Confirm":"Save"):"Confirm",p=()=>{if(t.kind==="confirm"){xn(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}xn(m)};return o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:n,children:t.title}),o(Oi,{ariaLabel:`Close ${t.title}`,onClick:()=>xn(t.kind==="confirm"?!1:null)})]}),o("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?o("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?o("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?o("div",{className:"field",children:[t.suggestions?.length?o(sP,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:m=>{i(m),a&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):o(Ne,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:m=>{i(m.currentTarget.value),a&&s(null)},onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),a?o("div",{className:"sync-field-hint",id:l,children:a}):null]}):null,t.kind==="duplicate-person"?o(aA,{descriptionId:e,request:t}):null]}),o("div",{className:"modal-footer",children:[o("div",{className:"small"}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>xn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?o("button",{autoFocus:!0,className:`settings-button ${oP(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function sA(){const[e,t]=x(rP());J(()=>(tv(t),()=>{iP(t)&&tv(null)}),[]);const n=!!e,r=Re(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Re(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?o(Br,{ariaDescribedby:i,ariaLabelledby:r,contentClassName:"modal",contentId:"syncDialog",onInteractOutside:l=>{const d=l.detail?.originalEvent?.target;d instanceof Element&&d.closest(".autocomplete-popover")&&l.preventDefault()},onOpenAutoFocus:l=>{const d=document.querySelector('#syncDialog [data-sync-primary-action="true"]');if(e?.kind==="input"&&d){l.preventDefault(),d.focus();return}const u=(e?.kind==="confirm"?e.autoFocusAction??"confirm":"confirm")==="cancel"?'#syncDialog [data-sync-dialog-action="cancel"]':'#syncDialog [data-sync-dialog-action="confirm"]',p=document.querySelector(u);p&&(l.preventDefault(),p.focus())},onOpenChange:l=>{l||xn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?o(oA,{descriptionId:i,request:e,titleId:r}):null}):null}var dr=null;function vs(){dr?.isConnected||(dr=document.getElementById("syncDialogMount"),dr||(dr=document.createElement("div"),dr.id="syncDialogMount",document.body.appendChild(dr)),Ge(o(sA,{}),dr))}function Jt(e){return vs(),rd("confirm")?new Promise(t=>{nd(n=>t(!!n)),us({kind:"confirm",...e})}):Promise.resolve(!1)}function pd(e){return vs(),rd("input")?new Promise(t=>{nd(n=>t(typeof n=="string"?n:null)),us({kind:"input",...e})}):Promise.resolve(null)}function cA(e){return vs(),rd("duplicate-person")?new Promise(t=>{nd(n=>t(n||{action:"cancel"})),us({kind:"duplicate-person",...e})}):Promise.resolve(aP({kind:"duplicate-person",...e}))}function lA(e){return e.readiness==="ready"?null:"Space management needs the coordinator URL, target Team, and admin secret before it can list Spaces or change memberships."}function dA(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Bv(e){const t=String(e.label||"").trim()||"Untitled Space",n=dA(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",a=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Advanced: Space ID ${i} · Membership epoch ${a}`}}function uA(e){const t={active:"Space access active",revoked:"Space access revoked",not_member:"No Space access"},n=e.role.replaceAll("_"," "),r=e.status==="not_member"?t[e.status]:`${t[e.status]} · ${n}`,i=e.membershipEpoch==null?"—":String(e.membershipEpoch);return{statusLabel:t[e.status],detail:r,advancedDetail:`Advanced: membership epoch ${i}`}}function pA(e,t,n){return`Revoke ${t||n||"this device"} from ${Bv(e).title}?`}function mA(e,t){const n=new Map(t.map(r=>[String(r.device_id||"").trim(),r]).filter(([r])=>r.length>0));return e.map(r=>{const i=String(r.device_id||"").trim();if(!i)return null;const a=n.get(i),s=String(a?.status||"").trim(),c=a?s==="revoked"?"revoked":"active":"not_member",l=typeof a?.membership_epoch=="number"&&Number.isFinite(a.membership_epoch)?Math.trunc(a.membership_epoch):null;return{deviceId:i,displayName:String(r.display_name||i||"Unnamed device"),enabled:r.enabled!==!1&&r.enabled!==0,status:c,role:String(a?.role||"member"),membershipEpoch:l,updatedAt:a?.updated_at?String(a.updated_at):null}}).filter(r=>r!==null).sort((r,i)=>{const a={active:0,revoked:1,not_member:2};return a[r.status]-a[i.status]||r.displayName.localeCompare(i.displayName)})}function fA(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(a=>String(a.group_id||"").trim()===i)}function hA(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function md(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function dt(e){let t=H.groupScopeManagementDrafts.get(e);return t||(t=hA(),H.groupScopeManagementDrafts.set(e,t)),t}function St(e,t){H.groupScopeManagementDrafts.set(e,t)}async function ri(e,t,n=dt(e).includeInactive){St(e,{...dt(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([Gw(e,n),Np(e,!0)]),a=md(r),s=md(i),c=await Promise.all(a.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,md(await qw(e,d,!0))]:[d,[]]}));St(e,{...dt(e),loaded:!0,loading:!1,error:"",includeInactive:n,devicesLoaded:!0,scopes:a,devices:s,membersByScope:new Map(c.filter(([l])=>l.length>0)),actionPendingKey:"",actionPendingKind:""})}catch(r){St(e,{...dt(e),loaded:!0,loading:!1,error:r instanceof Error?r.message:"Failed to load Spaces."})}t()}function fd(e,t){H.groupScopeManagementOpen.add(e),dt(e),t(),ri(e,t)}function Uv(e,t){H.groupScopeManagementOpen.delete(e),H.groupScopeManagementDrafts.delete(e),t()}async function gA(e,t){const n=dt(e);if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),a=n.createKind.trim()||"team";if(!r||!i){oe("Enter a Space id and label before creating a Space.","warning");return}St(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await Hw(e,{scope_id:r,label:i,kind:a});const s=dt(e);St(e,{...s,createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}),oe("Space created. Grant devices explicitly before data can sync."),await ri(e,t,s.includeInactive)}catch(s){St(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to create Space."}),t()}}async function vA(e,t,n,r){const i=dt(e),a=`grant:${t}:${n}`;if(!i.actionPendingKey){St(e,{...i,actionPendingKey:a,actionPendingKind:"grant",error:""}),r();try{await Kw(e,t,{device_id:n,role:"member"}),oe("Device granted access to the Space."),await ri(e,r,i.includeInactive)}catch(s){St(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to grant Space access."}),r()}}}async function yA(e,t,n,r,i){const a=String(t.scope_id||"").trim();if(!a||!await Jt({title:pA(t,r,n),description:"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.",confirmLabel:"Revoke membership",cancelLabel:"Keep membership",tone:"danger"}))return;const s=dt(e),c=`revoke:${a}:${n}`;if(!s.actionPendingKey){St(e,{...s,actionPendingKey:c,actionPendingKind:"revoke",error:""}),i();try{await Vw(e,a,n),oe("Space access revoked. Future sync is blocked for that device."),await ri(e,i,s.includeInactive)}catch(l){St(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:l instanceof Error?l.message:"Failed to revoke Space access."}),i()}}}function bA(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=mA(fA(n.devices,_.lastCoordinatorAdminDevices,e,n.devicesLoaded),n.membersByScope.get(a)??[]);return s.length?y("div",{class:"coordinator-admin-scope-member-list"},s.map(c=>{const l=`${n.actionPendingKind}:${a}:${c.deviceId}`,d=n.actionPendingKey===l,u=c.enabled&&c.status!=="active",p=c.status==="active",m=uA(c);return y("div",{class:"coordinator-admin-scope-member-row",key:c.deviceId},y("div",{class:"coordinator-admin-scope-member-copy"},y("strong",null,c.displayName),y("span",null,m.detail),y("span",{class:"peer-meta"},m.advancedDetail),c.enabled?null:y("span",null,"Device is disabled in this Team.")),y("div",{class:"peer-actions"},u?y("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{vA(e,a,c.deviceId,i)},type:"button"},d&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,p?y("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{yA(e,t,c.deviceId,c.displayName,i)},type:"button"},d&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):y("div",{class:"peer-submeta coordinator-admin-empty-state"},"No enrolled devices in this Team yet. Enroll a device before granting this Space.")}function _A(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=Bv(t);return y("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:a||s.title},y("div",{class:"peer-title"},y("strong",null,s.title)),y("div",{class:"peer-submeta"},s.summary),y("div",{class:"peer-meta"},s.advancedDetail),y("div",{class:"peer-submeta"},"Devices below are enrolled in the Team; only active Space members can sync this data boundary."),bA(e,t,n,r,i))}function wA(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,a=H.groupScopeManagementDrafts.get(t);if(!a)return null;const s=lA(r);if(s)return y("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(!a.loaded)return y("div",{class:"peer-submeta"},"Loading Spaces…");const c=!n||!!a.actionPendingKey||a.loading;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Teams discover and enroll devices. Spaces grant data access. Granting a device here is explicit; Team membership alone does not share memories."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),y(ei,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:a.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{ri(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),y("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&gA(t,i)}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Space id"),y(Ne,{class:"peer-scope-input",disabled:c,onInput:l=>{St(t,{...dt(t),createScopeId:String(l.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:a.createScopeId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Ne,{class:"peer-scope-input",disabled:c,onInput:l=>{St(t,{...dt(t),createLabel:String(l.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:a.createLabel})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Ne,{class:"peer-scope-input",disabled:c,onInput:l=>{St(t,{...dt(t),createKind:String(l.currentTarget.value||"")})},placeholder:"team",type:"text",value:a.createKind}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:c,type:"submit"},a.actionPendingKind==="create"?"Creating…":"Create Space"),y("button",{class:"settings-button",disabled:c,onClick:()=>{ri(t,i,a.includeInactive)},type:"button"},a.loading?"Refreshing…":"Refresh"))),a.error?y("div",{class:"peer-submeta coordinator-admin-error"},a.error):null,a.scopes.length?y("div",{class:"coordinator-admin-scope-card-list"},a.scopes.map(l=>_A(t,l,a,n,i))):y("div",{class:"peer-meta coordinator-admin-empty-state"},"No Spaces are defined for this Team yet. Create a Space, then grant specific devices. Projects stay local-only until assigned to a Space."))}function Gv(){return y("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},y("title",null,"Chevron"),y("path",{d:"m9 18 6-6-6-6"}))}function SA(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,saving:!1,error:""}}async function hd(e,t){const n=SA();H.groupPreferencesDrafts.set(e,n),H.groupPreferencesOpen.add(e),t();try{const r=await qS(e);H.groupPreferencesDrafts.set(e,{projects_include:Array.isArray(r.projects_include)?[...r.projects_include]:[],projects_exclude:Array.isArray(r.projects_exclude)?[...r.projects_exclude]:[],auto_seed_scope:r.auto_seed_scope,default_space_scope_id:r.default_space_scope_id||"",auto_grant_default_space_on_join:r.auto_grant_default_space_on_join===!0,loaded:!0,saving:!1,error:""})}catch(r){H.groupPreferencesDrafts.set(e,{...n,loaded:!0,error:r instanceof Error?r.message:"Failed to load preferences."})}t()}function ys(e,t){H.groupPreferencesOpen.delete(e),H.groupPreferencesDrafts.delete(e),t()}async function CA(e,t){const n=H.groupPreferencesDrafts.get(e);if(!n||n.saving)return;const r={projects_include:n.projects_include.length>0?[...n.projects_include]:null,projects_exclude:n.projects_exclude.length>0?[...n.projects_exclude]:null,auto_seed_scope:n.auto_seed_scope,default_space_scope_id:n.default_space_scope_id||null,auto_grant_default_space_on_join:n.auto_grant_default_space_on_join};H.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await KS(e,r),oe("Team defaults saved. New devices use these filters and Space settings."),ys(e,t)}catch(i){const a=H.groupPreferencesDrafts.get(e);if(!a)return;H.groupPreferencesDrafts.set(e,{...a,saving:!1,error:i instanceof Error?i.message:"Failed to save preferences."}),t()}}function NA(e,t,n){const r=H.groupPreferencesDrafts.get(e);if(!r)return null;if(!r.loaded)return y("div",{class:"peer-submeta"},"Loading project defaults…");const i=`coord-admin-scope-autoseed-${e}`,a=`coord-admin-default-space-autogrant-${e}`,s=`coord-admin-scope-include-${e}`,c=`coord-admin-scope-exclude-${e}`,l=!n||r.saving||!r.auto_seed_scope;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Team defaults"),y("div",{class:"peer-submeta"},"Space access grants decide what new devices can sync. Advanced sharing rules only narrow future writes after Space access already exists."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:i},"Auto-apply advanced rules to new devices"),y(ei,{"aria-labelledby":i,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!n||r.saving,onCheckedChange:d=>{const u=H.groupPreferencesDrafts.get(e)??r;H.groupPreferencesDrafts.set(e,{...u,auto_seed_scope:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:a},"Auto-grant default Space on join"),y(ei,{"aria-labelledby":a,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!n||r.saving||!r.default_space_scope_id,onCheckedChange:d=>{const u=H.groupPreferencesDrafts.get(e)??r;H.groupPreferencesDrafts.set(e,{...u,auto_grant_default_space_on_join:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?y("div",{class:"peer-submeta"},"Default Space configured."):y("div",{class:"peer-submeta"},"No default Space has been created yet."),y("div",{class:"coordinator-admin-field"},y("span",{id:s},"Include template"),y(Wg,{"aria-labelledby":s,availableProjects:H.availableProjects,disabled:l,emptyLabel:"All projects allowed.",onValuesChange:d=>{const u=H.groupPreferencesDrafts.get(e)??r;H.groupPreferencesDrafts.set(e,{...u,projects_include:d}),t()},placeholder:"Add project",values:r.projects_include}),y("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),y("div",{class:"coordinator-admin-field"},y("span",{id:c},"Exclude template"),y(Wg,{"aria-labelledby":c,availableProjects:H.availableProjects,disabled:l,emptyLabel:"Nothing excluded.",onValuesChange:d=>{const u=H.groupPreferencesDrafts.get(e)??r;H.groupPreferencesDrafts.set(e,{...u,projects_exclude:d}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?y("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||r.saving,onClick:()=>{CA(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>ys(e,t),type:"button"},"Cancel")))}function TA(e){const t=H.teamSetupGuide;if(!t)return null;const n=t.displayName||t.groupId,r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return y("div",{class:"peer-meta coordinator-admin-empty-state"},y("h4",{class:"coordinator-admin-drawer-title"},`Set up ${n}`),y("div",{class:"peer-submeta"},"A Team organizes people and devices. The default Space is the memory boundary; Team membership only grants data access when default Space auto-grant is enabled."),t.setupWarning?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`Team created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create access manually before inviting teammates.`):y("div",{class:"peer-submeta"},t.defaultSpaceScopeId?t.defaultSpaceLabel?`Default Space ready: ${t.defaultSpaceLabel}. New devices can receive this Space when auto-grant is enabled.`:"Default Space ready. New devices can receive this Space when auto-grant is enabled.":"Default Space status is unknown. Check Spaces before inviting teammates."),y("ol",{class:"peer-submeta"},y("li",null,"Review Team defaults and the auto-grant default Space setting."),y("li",null,"Invite teammates or other devices."),y("li",null,"Assign projects to Spaces from the Projects tab.")),y("div",{class:"peer-actions"},y("button",{class:"settings-button",onClick:()=>{H.groupPreferencesOpen.add(t.groupId),hd(t.groupId,e)},type:"button"},"Review Team defaults"),y("button",{class:"settings-button",onClick:()=>{fd(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{H.inviteGroup=t.groupId,H.activeSection="invites",e()},type:"button"},"Invite devices"),y("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Assign projects"),y("button",{class:"settings-button",onClick:()=>{H.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function IA(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function kA(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:a}=e,s=String(_.lastCoordinatorAdminStatus?.active_group||"").trim(),c=sr(),l=ti(),d=l.filter(g=>!g.archived_at),u=l.filter(g=>g.archived_at),p=H.showArchivedGroups?l:d,m=c?l.some(g=>g.group_id===c):!1,f=[`${d.length} active`];return u.length&&f.push(`${u.length} archived`),y(ir,{className:"coordinator-admin-panel",value:"groups"},y("h3",null,"Teams"),y("p",{class:"peer-submeta"},c?`Managing ${c}${s&&s!==c?` · this node uses ${s} for discovery`:""}`:s?`This node uses ${s} for discovery. Select a Team below to manage it.`:"No Team selected yet. Create one or select an existing Team to manage."),l.length?y("p",{class:"peer-submeta"},f.join(" · ")):null,!m&&c?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`The selected Team (${c}) is configured locally but does not exist in the coordinator yet. Create it below or switch to another Team once one exists.`):null,TA(i),(()=>{const g=t.readiness!=="ready"||H.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!g&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Team id"),y(Ne,{class:"peer-scope-input",disabled:g,onInput:h=>{H.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:H.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Ne,{class:"peer-scope-input",disabled:g,onInput:h=>{H.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:H.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:g,type:"submit"},H.groupActionPendingKind==="create"?"Creating…":"Create Team")),y("div",{class:"coordinator-admin-secondary-actions"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),y(ei,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:H.showArchivedGroups,className:"coordinator-admin-switch",disabled:t.readiness!=="ready",onCheckedChange:h=>{H.showArchivedGroups=h,i()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),p.length?y("div",{class:"peer-list"},p.map(g=>{const h=g.group_id===c,v=H.groupActionPendingId===g.group_id,w=!!g.archived_at,b=H.groupRenameDrafts.get(g.group_id)??g.display_name??g.group_id,S=H.groupPreferencesOpen.has(g.group_id),C=H.groupScopeManagementOpen.has(g.group_id),T=w?"unarchive":"archive",P=IA(w,v&&H.groupActionPendingKind===T),k=nP({groupId:g.group_id,preferences:H.groupPreferencesDrafts.get(g.group_id),scopeManagement:H.groupScopeManagementDrafts.get(g.group_id),setupGuide:H.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:g.group_id},y("div",{class:"peer-title"},y("strong",null,b)),y("div",{class:"peer-submeta"},w?"Archived Team":"Active Team"),y("div",{class:"peer-meta"},`Advanced: Team ID ${g.group_id}`),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Default Space"),y("strong",null,k.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,k.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,k.spaces))),s===g.group_id?y("div",{class:"peer-submeta"},"This node uses this Team for coordinator-backed discovery."):null,y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Ne,{class:"peer-scope-input",disabled:t.readiness!=="ready"||v,onInput:M=>{H.groupRenameDrafts.set(g.group_id,String(M.currentTarget.value||""))},type:"text",value:b})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{Zl(g.group_id),a()},type:"button"},h?"Managing":"Manage Team"),y("button",{class:"settings-button",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,b,"rename"),type:"button"},v&&H.groupActionPendingKind==="rename"?"Renaming…":"Rename"),y("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{S?ys(g.group_id,i):hd(g.group_id,i)},type:"button"},y("span",null,"Team defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Gv,null))),y("button",{"aria-expanded":C,"aria-controls":`coord-admin-spaces-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":C?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{C?Uv(g.group_id,i):fd(g.group_id,i)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(Gv,null))),y("button",{class:w?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,g.display_name||g.group_id,T),type:"button"},P)),y(zo,{open:S,onOpenChange:M=>{M?hd(g.group_id,i):ys(g.group_id,i)}},y(Jo,{"aria-label":`Project defaults for ${b}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${g.group_id}`},S?NA(g.group_id,i,t.readiness==="ready"):null)),y(zo,{open:C,onOpenChange:M=>{M?fd(g.group_id,i):Uv(g.group_id,i)}},y(Jo,{"aria-label":`Spaces for ${b}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${g.group_id}`},C?wA({groupId:g.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):y("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?H.showArchivedGroups?"No Teams are available yet.":"No active Teams yet. Create one to get started.":"Team browsing will appear here once setup is complete."))}function ii(e){return o("textarea",{...e})}function EA(e){const{summary:t,createInvite:n,renderShell:r}=e,i=_.lastCoordinatorAdminStatus,a=sr()||String(i?.active_group||"").trim(),s=H.inviteGroup.trim()||a,c=String(_.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||H.invitePending;return y(ir,{className:"coordinator-admin-panel",value:"invites"},y("h3",null,"Legacy Team invites"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Legacy Team invites enroll a device in the selected Team. They do not grant project access; share projects from Projects instead.":"Finish setup first. Invite creation stays disabled until the local Teams configuration is ready."),y("form",{class:"coordinator-admin-form",onSubmit:u=>{u.preventDefault(),!d&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Team"),y(Ne,{class:"peer-scope-input",disabled:t.readiness!=="ready",onInput:u=>{H.inviteGroup=String(u.currentTarget.value||""),r()},placeholder:a||"team-alpha",type:"text",value:H.inviteGroup})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(Ln,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:t.readiness!=="ready",id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:u=>{H.invitePolicy=u==="approval_required"?"approval_required":"auto_admit",r()},options:[{value:"auto_admit",label:"Auto-admit to Team"},{value:"approval_required",label:"Require approval to join Team"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:H.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Ne,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{H.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:H.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:d,type:"submit"},H.invitePending?"Creating…":"Create legacy Team invite"),s?y("span",{class:"peer-submeta"},`Using Team ${s}`):null)),c?y("label",{class:"coordinator-admin-field"},y("span",null,"Generated invite"),y(ii,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Xi(c,u.currentTarget)},"Copy")):null,l?.length?y("div",{class:"peer-meta coordinator-admin-warning-list"},l.join(" · ")):null,y("h3",null,"Project sharing operations"),y("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),_.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},..._.lastShareOperations.map(u=>y("li",{key:u.operation_id},y("strong",null,u.person.display_name),y("span",null,` — ${u.projects.map(p=>p.display_name).join(", ")} — ${u.lifecycle.label}`)))):y("div",{class:"peer-meta"},"No project sharing operations yet."))}function PA(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.lastCoordinatorAdminJoinRequests:[];return y(ir,{className:"coordinator-admin-panel",value:"join-requests"},y("h3",null,"Pending join requests"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this Team. Default Space access is handled by Team defaults and can be reviewed in Spaces.":"Finish setup first. Join request review stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const a=String(i.request_id||"").trim(),s=String(i.device_id||"unknown-device"),c=String(i.display_name||s).trim()||s,l=String(i.fingerprint||"").trim(),d=[`Device ID ${s}`];l&&d.push(`Fingerprint ${l}`);const u=H.joinReviewPendingId===a;return y("div",{class:"peer-card peer-card--padded",key:a||s},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-meta"},`Advanced: ${d.join(" · ")}`),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!a||u,onClick:()=>n(a,"approve"),type:"button"},u&&H.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!a||u,onClick:()=>n(a,"deny"),type:"button"},u&&H.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."))}function AA(e){const{renderShell:t,reloadData:n}=e;async function r(){if(H.groupActionPendingKind)return;const l=H.createGroupId.trim();if(!l){oe("Enter a Team id before creating a Team.","warning");return}const d=H.createGroupDisplayName.trim();H.groupActionPendingKind="create",t();try{const u=await jw({group_id:l,display_name:d||null}),p=u.default_space,m=(p&&"scope"in p?p.scope:p)??{},f=p&&"preferences"in p?p.preferences:null,g=String(m?.scope_id||"");H.createGroupId="",H.createGroupDisplayName="",H.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:g,defaultSpaceLabel:String(m?.label||""),autoGrantDefaultSpaceOnJoin:typeof f?.auto_grant_default_space_on_join=="boolean"?f.auto_grant_default_space_on_join:null,setupWarning:u.setup_warning||null},await n(),Zl(l),await n(),u.setup_warning?oe("Team created, but default Space setup needs repair.","warning"):g?oe("Team created with a default Space.","success"):oe("Team created, but default Space status is unknown.","warning")}catch(u){oe(u instanceof Error?u.message:"Failed to create Team.","warning")}finally{H.groupActionPendingKind="",t()}}async function i(l,d,u){if(!(!l||H.groupActionPendingId)&&!((u==="archive"||u==="unarchive")&&!await Jt({title:`${u==="archive"?"Archive":"Unarchive"} ${d||l}?`,description:u==="archive"?"Archived Teams stay visible and restorable, but they stop being operational for new invites and joins.":"This Team will become operational again for invites and coordinator-backed joins.",confirmLabel:u==="archive"?"Archive Team":"Unarchive Team",cancelLabel:u==="archive"?"Keep Team active":"Keep Team archived",tone:"danger"}))){H.groupActionPendingId=l,H.groupActionPendingKind=u,t();try{u==="rename"&&(await Fw(l,d),oe("Team renamed.","success")),u==="archive"&&(await Bw(l),oe("Team archived.","success")),u==="unarchive"&&(await Uw(l),oe("Team unarchived.","success")),await n()}catch(p){oe(p instanceof Error?p.message:`Failed to ${u} Team.`,"warning")}finally{H.groupActionPendingId="",H.groupActionPendingKind="",t()}}}async function a(){if(H.invitePending)return;const l=_.lastCoordinatorAdminStatus,d=sr()||String(l?.active_group||"").trim(),u=H.inviteGroup.trim()||d,p=Number(H.inviteTtlHours);if(!u){oe("Choose a Team before creating an invite.","warning");return}if(!Number.isFinite(p)||p<1){oe("Invite lifetime must be at least 1 hour.","warning");return}H.invitePending=!0,t();try{const m=await Tp({group_id:u,policy:H.invitePolicy,ttl_hours:p});_.lastTeamInvite=m,H.inviteGroup=u;const f=Array.isArray(m.warnings)?m.warnings:[];oe(f.length?`Invite created. Review ${f.length===1?"the warning":`${f.length} warnings`} before sharing it.`:"Invite created. Copy it from Teams and share it with your teammate.",f.length?"warning":"success")}catch(m){oe(m instanceof Error?m.message:"Failed to create invite.","warning")}finally{H.invitePending=!1,t()}}async function s(l,d){if(!H.joinReviewPendingId){H.joinReviewPendingId=l,H.joinReviewPendingAction=d,t();try{const u=await zw(l,d);d==="approve"&&u.setup_warning?oe("Join request approved, but default Space access needs repair.","warning"):oe(d==="approve"?"Join request approved.":"Join request denied.","success"),await n()}catch(u){oe(u instanceof Error?u.message:"Failed to review join request.","warning")}finally{H.joinReviewPendingId="",H.joinReviewPendingAction="",t()}}}async function c(l,d,u,p){if(!(!l||H.deviceActionPendingId)&&!((p==="disable"||p==="remove")&&!await Jt({title:`${p==="disable"?"Disable":"Remove"} ${u||l}?`,description:p==="disable"?"This device will stay enrolled but can no longer participate until you re-enable it.":"This removes the enrolled device record from the coordinator. The teammate would need a fresh invite or re-enrollment path to come back.",confirmLabel:p==="disable"?"Disable device":"Remove device",cancelLabel:p==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))){H.deviceActionPendingId=l,H.deviceActionPendingKind=p,t();try{if(p==="rename"){const m=String(H.deviceRenameDrafts.get(l)||"").trim();if(!m){oe("Enter a device name before renaming it.","warning");return}await Jw(l,d,m),oe("Device renamed.","success")}p==="disable"&&(await Yw(l,d),oe("Device disabled.","success")),p==="enable"&&(await Xw(l,d),oe("Device enabled.","success")),p==="remove"&&(await Qw(l,d),oe("Device removed.","success")),await n()}catch(m){oe(m instanceof Error?m.message:`Failed to ${p} device.`,"warning")}finally{H.deviceActionPendingId="",H.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:r,runGroupAction:i,createInviteFromAdminPanel:a,reviewJoinRequestFromAdminPanel:s,runDeviceAction:c}}function xA(){const e=_.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Teams is ready",detail:"This viewer can use the local Teams admin configuration to manage invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Teams setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using Teams invite and device actions.":"Finish configuring the coordinator target and Team before using Teams actions."}:{readiness:"not_configured",title:"Teams is not configured",detail:"Set a coordinator URL, Team, and admin secret locally to enable remote Teams administration from this viewer."}:{readiness:"partial",title:"Checking Teams readiness…",detail:"Loading local Teams configuration from the viewer server."}}var{createGroupFromAdminPanel:RA,runGroupAction:DA,createInviteFromAdminPanel:LA,reviewJoinRequestFromAdminPanel:$A,runDeviceAction:MA}=AA({renderShell:()=>ur(),reloadData:()=>gd()});function ur(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=_.lastCoordinatorAdminStatus,n=xA(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!JE()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=sr(),m=ti().filter(w=>!w.archived_at).length,f=ti().filter(w=>w.archived_at).length,g=Array.isArray(_.lastCoordinatorAdminJoinRequests)?_.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(_.lastCoordinatorAdminDevices)?_.lastCoordinatorAdminDevices.length:0,v=n.readiness!=="ready"?n.detail:s?"The selected Team is archived. Restore it or switch Teams before creating invites.":"";(H.activeSection==="invites"&&!l||H.activeSection==="groups"&&!c||H.activeSection==="join-requests"&&!d||H.activeSection==="devices"&&!u)&&(H.activeSection=n.readiness==="ready"?"groups":"invites"),Ge(y("div",{class:"coordinator-admin-shell"},y("div",{class:"card coordinator-admin-header"},y("div",{class:"section-header"},y("h2",null,"Teams")),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Team admin target"),y("strong",null,p||"None selected")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Node discovery Team"),y("strong",null,i||"None")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Teams"),y("strong",null,`${m} active${f?` · ${f} archived`:""}`)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected Team activity"),y("strong",null,`${g} join requests · ${h} devices`))),v?y("div",{class:"peer-meta coordinator-admin-inline-warning"},v):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(Jh,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:w=>{H.activeSection=w||"groups",ur()},tabs:[{value:"groups",label:"Teams",disabled:!c},{value:"invites",label:"Invites",disabled:!l},{value:"join-requests",label:"Join requests",disabled:!d},{value:"devices",label:"Devices",disabled:!u}],triggerClassName:"coordinator-admin-tab-trigger",value:H.activeSection},kA({summary:n,createGroup:()=>{RA()},runGroup:(w,b,S)=>{DA(w,b,S)},renderShell:ur,reloadData:()=>{gd()}}),EA({summary:n,createInvite:()=>{LA()},renderShell:ur}),PA({summary:n,reviewJoinRequest:(w,b)=>{$A(w,b)}}),hk({summary:n,runDevice:(w,b,S,C)=>{MA(w,b,S,C)}})),y("div",{class:"section-meta coordinator-admin-context-line"},s?`Selected Team ${p||"—"} is archived. Switch or restore it to enable invite operations.`:p?`Actions below apply to ${p}.`:"Select a Team to start managing people, Spaces, and access."))),e)}function OA(){ur()}async function gd(){try{_.lastCoordinatorAdminStatus=await Za()}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],H.deviceRenameDrafts.clear(),H.deviceRenameServerNames.clear(),ur();return}const e=String(_.lastCoordinatorAdminStatus?.active_group||"").trim();if(ev(),_.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await Hp();_.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await Cp(H.showArchivedGroups);_.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],zE(),ev()}catch{_.lastCoordinatorAdminGroups=[],H.groupRenameDrafts.clear()}const t=sr();try{const n=await Ww(t||e);_.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{_.lastCoordinatorAdminJoinRequests=[]}try{const n=await Np(t||e,!0);_.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],YE()}catch{_.lastCoordinatorAdminDevices=[]}try{H.availableProjects=await eo()}catch{H.availableProjects=[]}}else _.lastCoordinatorAdminGroups=[],H.groupRenameDrafts.clear(),_.lastCoordinatorAdminJoinRequests=[],_.lastCoordinatorAdminDevices=[],H.deviceRenameDrafts.clear(),H.deviceRenameServerNames.clear();ur()}function vd(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var yd=new WeakMap,Hv={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},jA={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},FA={available:"Available",offline:"Offline",unknown:"Availability unknown"};function BA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function UA(e,t){return t.get(e)??jA}function GA(e){return e.reduce((t,n)=>!t||Hv[n.state]>Hv[t.state]?n:t,null)}function HA(e,t){return t==="needs_attention"?{label:"Review sharing",target:"sharing"}:e!=="available"?{label:"Check device health",target:"health"}:t==="waiting"||t==="pending"||t==="verifying"?{label:"View sharing status",target:"sharing"}:null}function qA(e,t,n,r,i=[]){const a=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&a.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),m=BA(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===u.identityId).map(S=>S.canonicalProjectIdentity)),f=S=>{const C=s.get(S);if(!C)return null;const T=UA(S,d);return{canonicalProjectIdentity:S,displayName:C,state:T.state,statusLabel:T.label,statusCopy:T.explanation,deliveredCopiesMayRemain:T.deliveredCopiesMayRemain}},g=m.flatMap(S=>{const C=f(S);return C?[C]:[]}),h=[],v=[...g,...h],w=GA(v),b=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:a.get(u.identityId)??"Identity unavailable",availability:b,availabilityLabel:FA[b],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:g,inheritedProjects:h,unavailableProjectCount:m.length-g.length,statusState:w?.state??"no_projects",statusLabel:w?.statusLabel??"No directly shared Projects",statusCopy:w?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:v.some(S=>S.deliveredCopiesMayRemain),action:HA(b,w?.state??"no_projects")}}).sort((u,p)=>u.displayName.localeCompare(p.displayName)||u.identityName.localeCompare(p.identityName)),revokedDeviceCount:e.identityDevices.filter(u=>u.status==="revoked"&&a.has(u.identityId)).length}}function qv({empty:e,projects:t}){return t.length===0?o("p",{className:"small",children:e}):o("ul",{children:t.map(n=>o("li",{children:[o("strong",{children:n.displayName}),o("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function ca(e){if(!(e instanceof bc))return"Identity setup is unavailable. Refresh Devices and try again.";const t={binding_preview_busy:"Identity setup is busy. Wait a moment, then retry.",binding_commit_busy:"Identity setup is busy. Wait a moment, then retry.",binding_evidence_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_retry_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_rebind_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_unchanged_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_write_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",device_pairing_required:"Pair this device before assigning an Identity.",device_rebind_confirmation_required:"Reassignment requires a separate confirmation of the previous and target Identities.",device_inventory_incomplete:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",device_inventory_truncated:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",binding_write_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",binding_commit_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",device_evidence_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",target_identity_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_not_found:"A selected device or Identity is no longer available. Refresh Devices and choose again.",deciding_identity_unavailable:"The deciding Identity is unavailable. Open Identity administration to restore or replace it, then try again."}[e.errorCode];return t||(e.statusCode===503?"Identity setup is busy. Wait a moment, then retry.":e.statusCode===409?"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.":e.statusCode===404?"A selected device or Identity is no longer available. Refresh Devices and choose again.":"Identity setup could not be completed. Refresh Devices and try again.")}function bs(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:la(e)}}function la(e){return JSON.stringify({deviceId:e.deviceId,evidenceDeviceIds:[...e.evidenceDeviceIds].sort(),state:e.state,identityId:e.identityId,suggestedIdentityId:e.suggestedIdentityId,validatedFingerprint:e.validatedFingerprint,isLocal:e.isLocal,sources:[...e.sources].sort(),conflictCodes:[...e.conflictCodes].sort()})}function _s(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(a=>{const s=n.find(l=>l.deviceId===a.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===a.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var Kv="devices-commit-status";function gn(e){const t=document.getElementById(Kv);t&&(t.textContent=e)}function KA({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter(R=>R.status==="active"&&R.mergedIntoIdentityId===null),a=new Map(i.map(R=>[R.identityId,R.displayName])),s=new Set(a.keys()),[c,l]=x(()=>Object.fromEntries(n.map(R=>[R.deviceId,bs(R,s)]))),[d,u]=x(null),[p,m]=x(!1),[f,g]=x(!1),[h,v]=x(""),w=B(null),b=B(0),S=r.previewBindings??jp,C=r.commitBindings??Fp,T=vd(r),P=d!==null&&_s(d.preview,d.request,n,"bind"),k=Re(()=>n.filter(R=>R.state==="setup_required"&&c[R.deviceId]?.selected),[c,n]),M=JSON.stringify({items:t.items.map(la),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),U=i.map(R=>`${R.identityId}:${R.displayName}`).sort().join("|");J(()=>{d&&w.current?.focus()},[d]),J(()=>{b.current+=1,g(!1),l(R=>Object.fromEntries(n.map(A=>{const I=R[A.deviceId];if(!I)return[A.deviceId,bs(A,s)];if(A.state!=="setup_required")return[A.deviceId,bs(A,s)];const D=I.targetIdentityId!==""&&s.has(I.targetIdentityId);return I.itemSignature===la(A)&&D?[A.deviceId,I]:I.explicit&&D?[A.deviceId,{...I,selected:!1,itemSignature:la(A)}]:[A.deviceId,bs(A,s)]}))),u(null),m(!1)},[M,U]);const E=(R,A)=>{b.current+=1,g(!1),l(I=>({...I,[R]:{...I[R],...A}})),u(null),m(!1),v(""),gn("")},j=R=>({bindings:R.map(A=>{const I=c[A.deviceId];return{deviceId:A.deviceId,targetIdentityId:I?.targetIdentityId??"",confirmed:!0}})}),O=async R=>{if(T){v("Refresh Devices before reviewing Identity setup.");return}if(R.some(D=>D.state!=="setup_required")){v("Only devices that require Identity setup can be reviewed here.");return}const A=R.find(D=>Ro(t,D).blocked);if(A){v(Ro(t,A).recovery??"Identity setup is unavailable.");return}if(R.length===0||R.some(D=>!c[D.deviceId]?.targetIdentityId)){v("Choose an Identity for every selected device before review.");return}g(!0),v(""),gn("");const I=b.current;try{const D=j(R),F=await S(D);I===b.current&&(_s(F,D,R,"bind")?u({preview:F,request:D}):v("Identity setup preview was incomplete. Refresh and try again."))}catch(D){I===b.current&&v(ca(D))}I===b.current&&g(!1)},q=async()=>{if(!(!d||!p||T||!P)){g(!0),v("");try{await C({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),m(!1),gn("Identity setup completed.");const R=await r.onCommitted?.();gn(R===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":R===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch(R){v(ca(R))}g(!1)}},L=n.filter(R=>R.state==="setup_required");return n.length===0?null:o(Z,{children:[h?o("p",{role:"alert",children:h}):null,L.length>1?o("div",{className:"device-identity-setup-summary",children:[o("strong",{children:[L.length.toLocaleString()," devices need Identity setup"]}),o("button",{className:"settings-button",disabled:f||T||k.length===0,onClick:()=>{O(k)},type:"button",children:["Review ",k.length.toLocaleString()," selected"]})]}):null,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map((R,A)=>{const I=c[R.deviceId],D=Ro(t,R),F=D.blocked||T,K=`device-inventory-title-${A}`;return o("li",{children:o("article",{"aria-labelledby":K,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${R.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:K,children:[R.displayName,R.isLocal?" (this device)":""]}),o("span",{className:"badge actor-badge",children:R.state==="setup_required"?"Setup required":R.state==="pairing_required"?"Pairing required":R.state==="conflicted"?"Review required":"Configured"})]}),R.state==="setup_required"?o(Z,{children:[o("fieldset",{children:[o("legend",{children:"Assign an existing Identity"}),i.length===0?o("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,L.length>1?o("label",{children:[o("input",{"aria-label":`Select for setup: ${R.displayName}`,checked:I?.selected??!1,disabled:F,onInput:ce=>E(R.deviceId,{selected:ce.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,o("label",{htmlFor:`${K}-identity`,children:"Identity"}),o("select",{"aria-label":`Choose an Identity for ${R.displayName}`,disabled:F,id:`${K}-identity`,onInput:ce=>E(R.deviceId,{targetIdentityId:ce.currentTarget.value,explicit:!0}),value:I?.targetIdentityId??"",children:[o("option",{value:"",children:"Choose Identity…"}),i.map(ce=>o("option",{value:ce.identityId,children:ce.displayName},ce.identityId))]}),R.suggestedIdentityId&&a.has(R.suggestedIdentityId)?o("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,D.recovery?o("p",{className:"small",children:D.recovery}):null]}),o("div",{className:"device-identity-card-actions",children:[i.length===0?o("button",{"aria-label":`Open Identity administration for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,o("button",{"aria-label":`Review this device: ${R.displayName}`,className:"settings-button",disabled:f||F||!I?.targetIdentityId,onClick:()=>{O([R])},type:"button",children:"Review this device"})]})]}):R.state==="pairing_required"?o(Z,{children:[o("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Go to pairing for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):R.state==="conflicted"?o(Z,{children:[o("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Open Advanced review for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},R.deviceId)})}),d?o("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[o("h3",{id:"device-identity-review-heading",ref:w,tabIndex:-1,children:"Review Identity setup"}),o("ul",{children:d.preview.outcomes.map(R=>o("li",{children:[o("strong",{children:[R.displayName,":"]})," ",R.previousIdentityId?a.get(R.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",a.get(R.targetIdentityId)??"Unavailable Identity"]},R.deviceId))}),o("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:p,disabled:T,onInput:R=>m(R.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),o("div",{className:"peer-actions",children:[o("button",{className:"settings-button",disabled:f,onClick:()=>{u(null),m(!1)},type:"button",children:"Back"}),o("button",{className:"settings-button sync-dialog-confirm",disabled:f||T||!p||!P,onClick:()=>{q()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function Vv({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const a=e.identities.filter(R=>R.status==="active"&&R.mergedIntoIdentityId===null&&R.identityId!==n.identityId),[s,c]=x(!1),[l,d]=x(""),[u,p]=x(!1),[m,f]=x(null),[g,h]=x(!1),[v,w]=x(!1),[b,S]=x(""),C=B(0),T=i,P=new Map(e.identities.map(R=>[R.identityId,R.displayName])),k=m?.preview.status==="ready"&&m.preview.outcomes.length===1?m.preview.outcomes[0]:null,M=m!==null&&_s(m.preview,m.request,[n],"rebind"),U=Ro(t,n),E=U.blocked||vd(r),j=`configured-rebind-trigger-${n.deviceId}`,O=a.find(R=>R.identityId===l)?.displayName??"";J(()=>{C.current+=1,w(!1),l&&!a.some(R=>R.identityId===l)&&(d(""),p(!1)),f(null),h(!1)},[a.map(R=>R.identityId).sort().join("|"),la(n)]);const q=async()=>{if(E){S(U.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){S("Choose a target Identity and confirm the reassignment before review.");return}w(!0),S(""),gn("");const R=C.current;try{const A={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},I=await(r.previewBindings??jp)(A);R===C.current&&(I.status!=="ready"?S(ca(new bc(409,I.errorCode??"binding_preview_unavailable",I))):_s(I,A,[n],"rebind")?f({preview:I,request:A}):S("Identity reassignment preview was incomplete. Refresh and try again."))}catch(A){R===C.current&&S(ca(A))}R===C.current&&w(!1)},L=async()=>{if(!(!m||!g||E||!M)){w(!0),S("");try{await(r.commitBindings??Fp)({...m.request,reviewedInventoryDigest:m.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),f(null),h(!1),gn("Identity reassignment completed.");const R=await r.onCommitted?.();gn(R===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":R===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(j)??document.getElementById("devices-heading"))?.focus()}catch(R){S(ca(R))}w(!1)}};return o("div",{className:"device-identity-rebind",children:[o("button",{"aria-expanded":s,className:"settings-button",disabled:E,id:j,onClick:()=>{C.current+=1,w(!1),c(!s),f(null),h(!1),S(""),gn("")},type:"button",children:"Change Identity…"}),U.recovery?o("p",{className:"small",children:U.recovery}):null,s?o("fieldset",{children:[o("legend",{children:"Reassign this configured device"}),o("p",{children:[o("strong",{children:"Suggested current Identity (unconfirmed):"})," ",T]}),o("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),o("select",{disabled:E,id:`configured-rebind-${n.deviceId}`,onInput:R=>{C.current+=1,w(!1),d(R.currentTarget.value),p(!1),f(null),h(!1)},value:l,children:[o("option",{value:"",children:"Choose a different Identity…"}),a.map(R=>o("option",{value:R.identityId,children:R.displayName},R.identityId))]}),o("label",{children:[o("input",{checked:u,disabled:E||!l,onInput:R=>{C.current+=1,w(!1),p(R.currentTarget.checked),f(null),h(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",O||"the selected Identity"]}),o("button",{className:"settings-button",disabled:v||E,onClick:()=>{q()},type:"button",children:"Review reassignment"}),m?o("div",{className:"device-identity-rebind-review",children:[o("h4",{children:"Review reassignment"}),o("p",{children:[k?.displayName,":"," ",k?.previousIdentityId?P.get(k.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",P.get(k?.targetIdentityId??"")??"Unavailable Identity"]}),o("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:g,disabled:E,onInput:R=>h(R.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),o("button",{className:"settings-button sync-dialog-confirm",disabled:v||E||!g||!M,onClick:()=>{L()},type:"button",children:"Reassign Identity"})]}):null,b?o("p",{"aria-live":"assertive",role:"alert",children:b}):null]}):null]})}function VA({intent:e,options:t,projection:n}){if(t.loading)return o(jf,{label:"Loading Devices"});if(t.loadError)return o("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(m=>!t.inventory?.items.some(f=>f.state!=="configured"&&f.evidenceDeviceIds.includes(m.deviceId))),a=new Set(i.map(m=>m.deviceId)),s=t.inventoryUnavailable?o("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=Ff(t.inventory),l=t.inventory?.items.filter(m=>m.state==="configured"&&!m.evidenceDeviceIds.some(f=>a.has(f)))??[],d=t.inventory?o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((m,f)=>{const g=`configured-inventory-title-${f}`,h=e.identities.find(v=>v.identityId===m.identityId)?.displayName??"Unavailable Identity";return o("li",{children:o("article",{"aria-labelledby":g,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:g,children:m.displayName}),o("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),o("p",{children:[o("strong",{children:"Owning Identity:"})," ",h]}),o(Vv,{intent:e,inventory:t.inventory,item:m,options:t,previousIdentityName:h})]})},m.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?o("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),o("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),o("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?o(Z,{children:[t.inventory.truncated?o("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?o("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,o(KA,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?o(Z,{children:[r,s,u,p,d,o("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):o(Z,{children:[r,s,u,p,d,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((m,f)=>{const g=`devices-card-title-${f}`,h=m.action,v=t.inventory?.items.find(w=>w.state==="configured"&&w.evidenceDeviceIds.includes(m.deviceId));return o("li",{children:o("article",{"aria-labelledby":g,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:g,children:m.displayName}),o("span",{className:"badge actor-badge",children:[vd(t)?"Device":"Configured"," ·"," ",m.availabilityLabel]})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Owning Identity"}),o("dd",{children:m.identityName})]}),o("div",{children:[o("dt",{children:"Availability"}),o("dd",{children:m.availabilityLabel})]}),m.isPairedPeer?o("div",{children:[o("dt",{children:"Codemem version"}),o("dd",{children:m.reportedRuntimeVersion??"Not reported"})]}):null,o("div",{children:[o("dt",{children:"Sharing status"}),o("dd",{children:[o("strong",{children:m.statusLabel})," — ",m.statusCopy]})]})]}),o("section",{"aria-labelledby":`${g}-direct`,children:[o("h4",{id:`${g}-direct`,children:"Direct Projects"}),o(qv,{empty:"No Projects are shared directly.",projects:m.directProjects})]}),o("section",{"aria-labelledby":`${g}-teams`,children:[o("h4",{id:`${g}-teams`,children:"Projects through Teams"}),o(qv,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:m.inheritedProjects})]}),m.unavailableProjectCount>0?o("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,m.deliveredCopiesMayRemain?o("p",{className:"small",children:[o("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,h&&t.onNavigate?o("button",{"aria-label":`${h.label} for ${m.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(h.target),ref:w=>{w&&yd.set(w,{deviceId:m.deviceId,target:h.target})},type:"button",children:h.label}):null,v&&t.inventory?o(Vv,{intent:e,inventory:t.inventory,item:v,options:t,previousIdentityName:m.identityName}):null]})},m.deviceId)})}),n.revokedDeviceCount>0?o("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function ws(e,t,n,r,i,a={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?yd.get(s):void 0,d=qA(t,n,r,i,a.peerRuntimeMetadata);if(Ge(o("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("div",{className:"recipient-policy-sharing-header",children:[o("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),o("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),o(VA,{intent:t,options:a,projection:d}),o("p",{"aria-live":"polite",id:Kv,role:"status"})]}),e),gn(""),!a.loading&&_.pendingDeviceIdentityFocus!==void 0){const u=_.pendingDeviceIdentityFocus,p=a.inventory?.items.find(f=>f.deviceId===u||f.evidenceDeviceIds.includes(u??"")),m=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(f=>document.getElementById(`device-identity-card-${f}`)).find(f=>f instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)_.pendingDeviceIdentityFocus=void 0;else if(m){_.pendingDeviceIdentityFocus=void 0,m.focus();return}else if(!a.inventoryUnavailable&&!a.refreshError){_.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=yd.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function WA(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function pr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function zA(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.round(i/60);if(a<60)return`${a}m ago`;const s=Math.round(a/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function ai(e){if(!e)return null;const t=new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.floor((Date.now()-t)/1e3);return n>=0?n:0}function $n(e){return e==null?"n/a":e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}d`}function Wv(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function JA(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return"n/a";const i=(n+r)/r;return!Number.isFinite(i)||i<=0?"n/a":`${i.toFixed(i>=10?0:1)}x`}function bd(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const a=n/i;return Number.isFinite(a)?`${Math.round(a*100)}%`:"n/a"}function da(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:a}=n[r],s=t/a,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function YA(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function ua(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Ss(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]}function zv(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function XA(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function QA(e,t=2){if(!e.length)return"";const n=e.map(a=>String(a).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function Jv(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function ZA(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function ex(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,a=0;for(;a<n.length-1&&r(i)>=1024;)i/=1024,a+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[a]}`}function Yv(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===_.lastStatsPayload?.identity?.actor_id)}function Cs(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function tx(e){if(!e)return[];const t=String(e).split(`
|
|
46
|
-
`).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function nx(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of r)if(!(a.length<18)&&(i.push(a),i.length>=t))break;return i}function Xv(e){const t=ua(e.title),n=ua(e.body_text);if(!t&&!n)return!0;const r=n||t;if(r.length<10||t&&n&&t===n&&r.length<40)return!0;const i=t.charAt(0);return!!((i==="└"||i==="›")&&r.length<40||t.startsWith("list ")&&r.length<20||r==="ls"||r==="list ls")}function Qv(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function ft(e){return`${String(e.kind||"").toLowerCase()}:${Qv(e)}`}function rx(e){if(e.tags!=null)return Ss(e.tags);const t=Ss(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function ix(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function ax(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function ox(e){if(Yv(e))return"You";const t=String(e.actor_id||"").trim(),n=Ur(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function sx(e,t={}){if(Yv(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Ur(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Zv(e,t){const n=new Map;return e.forEach(r=>{n.set(ft(r),r)}),t.forEach(r=>{n.set(ft(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function cx(e,t){const n=new Set(t.map(ft));return Zv(e.filter(r=>!n.has(ft(r))),t)}var dF=560;function lx(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Ns(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Ts(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function dx(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[Is,uF]=st("Tooltip",[Pn]),ks=Pn(),ey="TooltipProvider",ux=700,_d="tooltip.open",[px,wd]=Is(ey),ty=e=>{const{__scopeTooltip:t,delayDuration:n=ux,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,s=B(!0),c=B(!1),l=B(0);return J(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),o(px,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:se(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:se(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:se(d=>{c.current=d},[]),disableHoverableContent:i,children:a})};ty.displayName=ey;var pa="Tooltip",[mx,ma]=Is(pa),ny=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:s,delayDuration:c}=e,l=wd(pa,e.__scopeTooltip),d=ks(t),[u,p]=x(null),m=ct(),f=B(0),g=s??l.disableHoverableContent,h=c??l.delayDuration,v=B(!1),[w,b]=It({prop:r,defaultProp:i??!1,onChange:k=>{k?(l.onOpen(),document.dispatchEvent(new CustomEvent(_d))):l.onClose(),a?.(k)},caller:pa}),S=Re(()=>w?v.current?"delayed-open":"instant-open":"closed",[w]),C=se(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,b(!0)},[b]),T=se(()=>{window.clearTimeout(f.current),f.current=0,b(!1)},[b]),P=se(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,b(!0),f.current=0},h)},[h,b]);return J(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),o(ia,{...d,children:o(mx,{scope:t,contentId:m,open:w,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:se(()=>{l.isOpenDelayedRef.current?P():C()},[l.isOpenDelayedRef,P,C]),onTriggerLeave:se(()=>{g?T():(window.clearTimeout(f.current),f.current=0)},[T,g]),onOpen:C,onClose:T,disableHoverableContent:g,children:n})})};ny.displayName=pa;var Sd="TooltipTrigger",ry=V((e,t)=>{const{__scopeTooltip:n,...r}=e,i=ma(Sd,n),a=wd(Sd,n),s=ks(n),c=Se(t,B(null),i.onTriggerChange),l=B(!1),d=B(!1),u=se(()=>l.current=!1,[]);return J(()=>()=>document.removeEventListener("pointerup",u),[u]),o(aa,{asChild:!0,...s,children:o(pe.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:c,onPointerMove:Q(e.onPointerMove,p=>{p.pointerType!=="touch"&&!d.current&&!a.isPointerInTransitRef.current&&(i.onTriggerEnter(),d.current=!0)}),onPointerLeave:Q(e.onPointerLeave,()=>{i.onTriggerLeave(),d.current=!1}),onPointerDown:Q(e.onPointerDown,()=>{i.open&&i.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:Q(e.onFocus,()=>{l.current||i.onOpen()}),onBlur:Q(e.onBlur,i.onClose),onClick:Q(e.onClick,i.onClose)})})});ry.displayName=Sd;var Cd="TooltipPortal",[fx,hx]=Is(Cd,{forceMount:void 0}),iy=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=ma(Cd,t);return o(fx,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Zn,{asChild:!0,container:i,children:r})})})};iy.displayName=Cd;var oi="TooltipContent",ay=V((e,t)=>{const n=hx(oi,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...a}=e,s=ma(oi,e.__scopeTooltip);return o(nt,{present:r||s.open,children:s.disableHoverableContent?o(oy,{side:i,...a,ref:t}):o(gx,{side:i,...a,ref:t})})}),gx=V((e,t)=>{const n=ma(oi,e.__scopeTooltip),r=wd(oi,e.__scopeTooltip),i=B(null),a=Se(t,i),[s,c]=x(null),{trigger:l,onClose:d}=n,u=i.current,{onPointerInTransitChange:p}=r,m=se(()=>{c(null),p(!1)},[p]),f=se((g,h)=>{const v=g.currentTarget,w={x:g.clientX,y:g.clientY},b=wx(w,_x(w,v.getBoundingClientRect())),S=Sx(h.getBoundingClientRect());c(Nx([...b,...S])),p(!0)},[p]);return J(()=>()=>m(),[m]),J(()=>{if(l&&u){const g=v=>f(v,u),h=v=>f(v,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",h)}}},[l,u,f,m]),J(()=>{if(s){const g=h=>{const v=h.target,w={x:h.clientX,y:h.clientY},b=l?.contains(v)||u?.contains(v),S=!Cx(w,s);b?m():S&&(m(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,s,d,m]),o(oy,{...e,ref:a})}),[vx,yx]=Is(pa,{isInside:!1}),bx=EC("TooltipContent"),oy=V((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:s,...c}=e,l=ma(oi,n),d=ks(n),{onClose:u}=l;return J(()=>(document.addEventListener(_d,u),()=>document.removeEventListener(_d,u)),[u]),J(()=>{if(l.trigger){const p=m=>{m.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,u]),o(Qn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:o(os,{"data-state":l.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o(bx,{children:r}),o(vx,{scope:n,isInside:!0,children:o(eI,{id:l.contentId,role:"tooltip",children:i||r})})]})})});ay.displayName=oi;var sy="TooltipArrow",cy=V((e,t)=>{const{__scopeTooltip:n,...r}=e,i=ks(n);return yx(sy,n).isInside?null:o(ss,{...i,...r,ref:t})});cy.displayName=sy;function _x(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function wx(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Sx(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function Cx(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function Nx(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Tx(t)}function Tx(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const a=t[t.length-1],s=t[t.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const a=n[n.length-1],s=n[n.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Ix=ty,kx=ny,Ex=ry,Px=iy,Ax=ay,xx=cy;function Nd({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return o(Ix,{delayDuration:t,skipDelayDuration:n,children:e})}function Es({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:a=!0,disabled:s=!1}){return s?o(Z,{children:e}):o(kx,{children:[o(Ex,{asChild:a,children:e}),o(Px,{children:o(Ax,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,o(xx,{className:"tooltip-arrow"})]})})]})}function Rx(e){e.dataset.feedRenderRoot="preact"}function Dx(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function Lx(e,t){Rx(e),Ge(y(Nd,null,t),e)}function $x(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function Mx(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function Td(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function Ox(e){const t=Cs(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=ua(n),a=ua(r),s=!!r&&a!==i,c=Ss(e?.facts||t?.facts||[]),l=c.length?c:tx(r||n),d=l.length?l:nx(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function jx(e){const t=[];return e.hasSummary&&t.push({id:"summary",label:"Summary"}),e.hasFacts&&t.push({id:"facts",label:"Facts"}),e.hasNarrative&&t.push({id:"narrative",label:"Narrative"}),t}function Fx(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function Bx(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function Ux(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function Gx(e,t){const n=_.feedTypeFilter==="observations"?" · observations":_.feedTypeFilter==="summaries"?" · session summaries":"",r=ix(_.feedScopeFilter),i=!_.feedQuery.trim()&&_.lastFeedFilteredCount?` · ${_.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${_.feedQuery.trim()?` · matching "${_.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Ps({label:e,candidates:t}){return t.length===0?null:y("div",{className:"trace-group"},y("div",{className:"section-meta"},e),y("div",{className:"feed-list"},t.map(n=>y("div",{className:"feed-card",key:`${e}:${n.id}`},y("div",{className:"feed-card-header"},[y("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),y("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),y("div",{className:"feed-card-body"},[y("div",null,n.preview||"No preview available."),n.reasons.length?y("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function Hx({open:e}){const[t,n]=x(()=>String(_.feedQuery||"")),[r,i]=x(!1),[a,s]=x(!1),[c,l]=x(""),[d,u]=x(!1),[p,m]=x(""),[f,g]=x(""),[h,v]=x(null),w=B(0),b=String(_.feedQuery||""),S=String(t||"").trim(),C=_.currentProject||null,T=Mx(c),P=Td({project:C,query:S,workingSetFiles:T}),k=h&&Td({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===P?h:null,M=p&&f===P?p:"";J(()=>{w.current+=1,u(!1),m(""),g(""),v(L=>!L||L.inputs.query!==S||L.inputs.project!==C?null:L)},[P]),J(()=>{e&&!r&&(n($x({feedQuery:b,hasInspectorOverride:a,inspectorQuery:t})),i(!0))},[b,a,r,t,e]);const U=async()=>{const L=S,R=C,A=T,I=Td({project:R,query:L,workingSetFiles:A}),D=w.current+1;if(w.current=D,!L){m("Enter a query to inspect."),g(I),v(null);return}u(!0),m(""),g("");try{const F=await nS({context:L,project:R,working_set_files:A});if(D!==w.current)return;v(F)}catch(F){if(D!==w.current)return;m(F instanceof Error?F.message:String(F)),g(I),v(null)}finally{D===w.current&&u(!1)}},E=k?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],j=k?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],O=k?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],q=k?.retrieval.candidates.filter(L=>L.disposition==="trimmed")||[];return e?y("div",{className:"feed-inspector"},y("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[y("div",{className:"feed-card-header"},[y("div",{className:"feed-card-title"},"Context Inspector"),y("div",{className:"feed-card-meta"},a?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),y("div",{className:"feed-card-body"},[y("input",{className:"feed-search",onInput:L=>{n(String(L.currentTarget.value||"")),s(!0),v(null),m(""),g("")},placeholder:"Trace a pack query…",value:t}),y("div",{className:"section-meta",style:"margin-top:8px;"},a?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),y("textarea",{className:"feed-inspector-files",onInput:L=>l(String(L.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),y("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},y("button",{className:"toggle-button active",disabled:d,onClick:()=>{U()},type:"button"},d?"Tracing…":"Run trace"),k?y("span",{className:"section-meta"},`mode=${k.mode.selected} · candidates=${k.retrieval.candidate_count} · tokens=${k.output.estimated_tokens}`):null),h&&!k?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,M?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},M):null]),k?y(Z,null,[y(Ps,{label:"Selected",candidates:E}),y(Ps,{label:"Dropped",candidates:j}),y(Ps,{label:"Deduped",candidates:O}),y(Ps,{label:"Trimmed",candidates:q}),y("div",{className:"feed-card-body"},[k.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${k.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.dropped.join(", ")}]`).join(" · ")}`):null,k.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${k.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},k.output.pack_text)])]):null])):null}var qx={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function Id({variant:e,tone:t,title:n,children:r}){const i=qx[e];return o("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function ly(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Kx(e){if(Array.isArray(e))return e}function Vx(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,s,c=[],l=!0,d=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(l=(r=a.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function Wx(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
47
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function zx(e,t){return Kx(e)||Vx(e,t)||Jx(e,t)||Wx()}function Jx(e,t){if(e){if(typeof e=="string")return ly(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ly(e,t):void 0}}var dy=Object.entries,uy=Object.setPrototypeOf,Yx=Object.isFrozen,Xx=Object.getPrototypeOf,Qx=Object.getOwnPropertyDescriptor,Xe=Object.freeze,Qe=Object.seal,si=Object.create,py=typeof Reflect<"u"&&Reflect,kd=py.apply,Ed=py.construct;Xe||(Xe=function(t){return t}),Qe||(Qe=function(t){return t}),kd||(kd=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];return t.apply(n,i)}),Ed||(Ed=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new t(...r)});var fa=Ve(Array.prototype.forEach),Zx=Ve(Array.prototype.lastIndexOf),my=Ve(Array.prototype.pop),ci=Ve(Array.prototype.push),eR=Ve(Array.prototype.splice),Mn=Array.isArray,ha=Ve(String.prototype.toLowerCase),Pd=Ve(String.prototype.toString),fy=Ve(String.prototype.match),ga=Ve(String.prototype.replace),hy=Ve(String.prototype.indexOf),tR=Ve(String.prototype.trim),nR=Ve(Number.prototype.toString),rR=Ve(Boolean.prototype.toString),gy=typeof BigInt>"u"?null:Ve(BigInt.prototype.toString),vy=typeof Symbol>"u"?null:Ve(Symbol.prototype.toString),ze=Ve(Object.prototype.hasOwnProperty),va=Ve(Object.prototype.toString),Ze=Ve(RegExp.prototype.test),mr=iR(TypeError);function Ve(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return kd(e,t,r)}}function iR(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Ed(e,n)}}function Ee(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ha;if(uy&&uy(e,null),!Mn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const a=n(i);a!==i&&(Yx(t)||(t[r]=a),i=a)}e[i]=!0}return e}function aR(e){for(let t=0;t<e.length;t++)ze(e,t)||(e[t]=null);return e}function ut(e){const t=si(null);for(const r of dy(e)){var n=zx(r,2);const i=n[0],a=n[1];ze(e,i)&&(Mn(a)?t[i]=aR(a):a&&typeof a=="object"&&a.constructor===Object?t[i]=ut(a):t[i]=a)}return t}function oR(e){switch(typeof e){case"string":return e;case"number":return nR(e);case"boolean":return rR(e);case"bigint":return gy?gy(e):"0";case"symbol":return vy?vy(e):"Symbol()";case"undefined":return va(e);case"function":case"object":{if(e===null)return va(e);const t=e,n=Yt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:va(r)}return va(e)}default:return va(e)}}function Yt(e,t){for(;e!==null;){const r=Qx(e,t);if(r){if(r.get)return Ve(r.get);if(typeof r.value=="function")return Ve(r.value)}e=Xx(e)}function n(){return null}return n}function sR(e){try{return Ze(e,""),!0}catch{return!1}}var yy=Xe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ad=Xe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),xd=Xe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),cR=Xe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Rd=Xe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),lR=Xe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),by=Xe(["#text"]),_y=Xe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Dd=Xe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),wy=Xe(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),As=Xe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),dR=Qe(/{{[\w\W]*|^[\w\W]*}}/g),uR=Qe(/<%[\w\W]*|^[\w\W]*%>/g),pR=Qe(/\${[\w\W]*/g),mR=Qe(/^data-[\-\w.\u00B7-\uFFFF]+$/),fR=Qe(/^aria-[\-\w]+$/),Sy=Qe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),hR=Qe(/^(?:\w+script|data):/i),gR=Qe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),vR=Qe(/^html$/i),yR=Qe(/^[a-z][.\w]*(-[.\w]+)+$/i),Cy=Qe(/<[/\w!]/g),bR=Qe(/<[/\w]/g),_R=Qe(/<\/no(script|embed|frames)/i),wR=Qe(/\/>/i),Xt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},SR=function(){return typeof window>"u"?null:window},CR=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const a="dompurify"+(r?"#"+r:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Ny=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},On=function(t,n,r,i){return ze(t,n)&&Mn(t[n])?Ee(i.base?ut(i.base):{},t[n],i.transform):r};function Ty(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:SR();const t=te=>Ty(te);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Xt.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,i=r.currentScript;e.DocumentFragment;const a=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,m=Yt(p,"cloneNode"),f=Yt(p,"remove"),g=Yt(p,"nextSibling"),h=Yt(p,"childNodes"),v=Yt(p,"parentNode"),w=Yt(p,"shadowRoot"),b=Yt(p,"attributes"),S=s&&s.prototype?Yt(s.prototype,"nodeType"):null,C=s&&s.prototype?Yt(s.prototype,"nodeName"):null;if(typeof a=="function"){const te=n.createElement("template");te.content&&te.content.ownerDocument&&(n=te.content.ownerDocument)}let T,P="",k,M=!1,U=0;const E=function(){if(U>0)throw mr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},j=function(N){E(),U++;try{return T.createHTML(N)}finally{U--}},O=function(N){E(),U++;try{return T.createScriptURL(N)}finally{U--}},q=function(){return M||(k=CR(u,i),M=!0),k},L=n,R=L.implementation,A=L.createNodeIterator,I=L.createDocumentFragment,D=L.getElementsByTagName,F=r.importNode;let K=Ny();t.isSupported=typeof dy=="function"&&typeof v=="function"&&R&&R.createHTMLDocument!==void 0;const ce=dR,ie=uR,re=pR,ye=mR,Y=fR,he=hR,ne=gR,ke=yR;let ge=Sy,ae=null;const xe=Ee({},[...yy,...Ad,...xd,...Rd,...by]);let de=null;const Te=Ee({},[..._y,...Dd,...wy,...As]);let ue=Object.seal(si(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),z=null,G=null;const W=Object.seal(si(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let be=!0,Ce=!0,ht=!1,Ft=!0,gt=!1,yn=!0,ve=!1,vt=!1,Nt=null,Ii=null,Ya=!1,bn=!1,Pr=!1,Vn=!1,yt=!0,Wn=!1;const yw="user-content-";let sp=!0,cp=!1,ki={},tn=null;const lp=Ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let bw=null;const _w=Ee({},["audio","video","img","source","image","track"]);let dp=null;const ww=Ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),mc="http://www.w3.org/1998/Math/MathML",fc="http://www.w3.org/2000/svg",nn="http://www.w3.org/1999/xhtml";let Ei=nn,up=!1,pp=null;const L1=Ee({},[mc,fc,nn],Pd),Sw=Xe(["mi","mo","mn","ms","mtext"]);let mp=Ee({},Sw);const Cw=Xe(["annotation-xml"]);let fp=Ee({},Cw);const $1=Ee({},["title","style","font","a","script"]);let Xa=null;const M1=["application/xhtml+xml","text/html"],O1="text/html";let Ke=null,Pi=null;const j1=n.createElement("form"),Nw=function(N){return N instanceof RegExp||N instanceof Function},hp=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Pi&&Pi===N)return;(!N||typeof N!="object")&&(N={}),N=ut(N),Xa=M1.indexOf(N.PARSER_MEDIA_TYPE)===-1?O1:N.PARSER_MEDIA_TYPE,Ke=Xa==="application/xhtml+xml"?Pd:ha,ae=On(N,"ALLOWED_TAGS",xe,{transform:Ke}),de=On(N,"ALLOWED_ATTR",Te,{transform:Ke}),pp=On(N,"ALLOWED_NAMESPACES",L1,{transform:Pd}),dp=On(N,"ADD_URI_SAFE_ATTR",ww,{transform:Ke,base:ww}),bw=On(N,"ADD_DATA_URI_TAGS",_w,{transform:Ke,base:_w}),tn=On(N,"FORBID_CONTENTS",lp,{transform:Ke}),z=On(N,"FORBID_TAGS",ut({}),{transform:Ke}),G=On(N,"FORBID_ATTR",ut({}),{transform:Ke}),ki=ze(N,"USE_PROFILES")?N.USE_PROFILES&&typeof N.USE_PROFILES=="object"?ut(N.USE_PROFILES):N.USE_PROFILES:!1,be=N.ALLOW_ARIA_ATTR!==!1,Ce=N.ALLOW_DATA_ATTR!==!1,ht=N.ALLOW_UNKNOWN_PROTOCOLS||!1,Ft=N.ALLOW_SELF_CLOSE_IN_ATTR!==!1,gt=N.SAFE_FOR_TEMPLATES||!1,yn=N.SAFE_FOR_XML!==!1,ve=N.WHOLE_DOCUMENT||!1,bn=N.RETURN_DOM||!1,Pr=N.RETURN_DOM_FRAGMENT||!1,Vn=N.RETURN_TRUSTED_TYPE||!1,Ya=N.FORCE_BODY||!1,yt=N.SANITIZE_DOM!==!1,Wn=N.SANITIZE_NAMED_PROPS||!1,sp=N.KEEP_CONTENT!==!1,cp=N.IN_PLACE||!1,ge=sR(N.ALLOWED_URI_REGEXP)?N.ALLOWED_URI_REGEXP:Sy,Ei=typeof N.NAMESPACE=="string"?N.NAMESPACE:nn,mp=ze(N,"MATHML_TEXT_INTEGRATION_POINTS")&&N.MATHML_TEXT_INTEGRATION_POINTS&&typeof N.MATHML_TEXT_INTEGRATION_POINTS=="object"?ut(N.MATHML_TEXT_INTEGRATION_POINTS):Ee({},Sw),fp=ze(N,"HTML_INTEGRATION_POINTS")&&N.HTML_INTEGRATION_POINTS&&typeof N.HTML_INTEGRATION_POINTS=="object"?ut(N.HTML_INTEGRATION_POINTS):Ee({},Cw);const $=ze(N,"CUSTOM_ELEMENT_HANDLING")&&N.CUSTOM_ELEMENT_HANDLING&&typeof N.CUSTOM_ELEMENT_HANDLING=="object"?ut(N.CUSTOM_ELEMENT_HANDLING):si(null);if(ue=si(null),ze($,"tagNameCheck")&&Nw($.tagNameCheck)&&(ue.tagNameCheck=$.tagNameCheck),ze($,"attributeNameCheck")&&Nw($.attributeNameCheck)&&(ue.attributeNameCheck=$.attributeNameCheck),ze($,"allowCustomizedBuiltInElements")&&typeof $.allowCustomizedBuiltInElements=="boolean"&&(ue.allowCustomizedBuiltInElements=$.allowCustomizedBuiltInElements),Qe(ue),gt&&(Ce=!1),Pr&&(bn=!0),ki&&(ae=Ee({},by),de=si(null),ki.html===!0&&(Ee(ae,yy),Ee(de,_y)),ki.svg===!0&&(Ee(ae,Ad),Ee(de,Dd),Ee(de,As)),ki.svgFilters===!0&&(Ee(ae,xd),Ee(de,Dd),Ee(de,As)),ki.mathMl===!0&&(Ee(ae,Rd),Ee(de,wy),Ee(de,As))),W.tagCheck=null,W.attributeCheck=null,ze(N,"ADD_TAGS")&&(typeof N.ADD_TAGS=="function"?W.tagCheck=N.ADD_TAGS:Mn(N.ADD_TAGS)&&(ae===xe&&(ae=ut(ae)),Ee(ae,N.ADD_TAGS,Ke))),ze(N,"ADD_ATTR")&&(typeof N.ADD_ATTR=="function"?W.attributeCheck=N.ADD_ATTR:Mn(N.ADD_ATTR)&&(de===Te&&(de=ut(de)),Ee(de,N.ADD_ATTR,Ke))),ze(N,"ADD_URI_SAFE_ATTR")&&Mn(N.ADD_URI_SAFE_ATTR)&&Ee(dp,N.ADD_URI_SAFE_ATTR,Ke),ze(N,"FORBID_CONTENTS")&&Mn(N.FORBID_CONTENTS)&&(tn===lp&&(tn=ut(tn)),Ee(tn,N.FORBID_CONTENTS,Ke)),ze(N,"ADD_FORBID_CONTENTS")&&Mn(N.ADD_FORBID_CONTENTS)&&(tn===lp&&(tn=ut(tn)),Ee(tn,N.ADD_FORBID_CONTENTS,Ke)),sp&&(ae["#text"]=!0),ve&&Ee(ae,["html","head","body"]),ae.table&&(Ee(ae,["tbody"]),delete z.tbody),N.TRUSTED_TYPES_POLICY){if(typeof N.TRUSTED_TYPES_POLICY.createHTML!="function")throw mr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof N.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw mr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const ee=T;T=N.TRUSTED_TYPES_POLICY;try{P=j("")}catch(le){throw T=ee,le}}else N.TRUSTED_TYPES_POLICY===null?(T=void 0,P=""):(T===void 0&&(T=q()),T&&typeof P=="string"&&(P=j("")));Xe&&Xe(N),Pi=N},Tw=Ee({},[...Ad,...xd,...cR]),Iw=Ee({},[...Rd,...lR]),F1=function(N,$,ee){return $.namespaceURI===nn?N==="svg":$.namespaceURI===mc?N==="svg"&&(ee==="annotation-xml"||mp[ee]):!!Tw[N]},B1=function(N,$,ee){return $.namespaceURI===nn?N==="math":$.namespaceURI===fc?N==="math"&&fp[ee]:!!Iw[N]},U1=function(N,$,ee){return $.namespaceURI===fc&&!fp[ee]||$.namespaceURI===mc&&!mp[ee]?!1:!Iw[N]&&($1[N]||!Tw[N])},G1=function(N){let $=v(N);(!$||!$.tagName)&&($={namespaceURI:Ei,tagName:"template"});const ee=ha(N.tagName),le=ha($.tagName);return pp[N.namespaceURI]?N.namespaceURI===fc?F1(ee,$,le):N.namespaceURI===mc?B1(ee,$,le):N.namespaceURI===nn?U1(ee,$,le):!!(Xa==="application/xhtml+xml"&&pp[N.namespaceURI]):!1},zn=function(N){ci(t.removed,{element:N});try{v(N).removeChild(N)}catch{if(f(N),!v(N))throw mr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},kw=function(N){const $=h(N);if($){const le=[];fa($,Ie=>{ci(le,Ie)}),fa(le,Ie=>{try{f(Ie)}catch{}})}const ee=b(N);if(ee)for(let le=ee.length-1;le>=0;--le){const Ie=ee[le],$e=Ie&&Ie.name;if(typeof $e=="string")try{N.removeAttribute($e)}catch{}}},Ar=function(N,$){try{ci(t.removed,{attribute:$.getAttributeNode(N),from:$})}catch{ci(t.removed,{attribute:null,from:$})}if($.removeAttribute(N),N==="is")if(bn||Pr)try{zn($)}catch{}else try{$.setAttribute(N,"")}catch{}},H1=function(N){const $=b(N);if($)for(let ee=$.length-1;ee>=0;--ee){const le=$[ee],Ie=le&&le.name;if(!(typeof Ie!="string"||de[Ke(Ie)]))try{N.removeAttribute(Ie)}catch{}}},q1=function(N){const $=[N];for(;$.length>0;){const ee=$.pop();(S?S(ee):ee.nodeType)===Xt.element&&H1(ee);const le=h(ee);if(le)for(let Ie=le.length-1;Ie>=0;--Ie)$.push(le[Ie])}},Ew=function(N){let $=null,ee=null;if(Ya)N="<remove></remove>"+N;else{const $e=fy(N,/^[\r\n\t ]+/);ee=$e&&$e[0]}Xa==="application/xhtml+xml"&&Ei===nn&&(N='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+N+"</body></html>");const le=T?j(N):N;if(Ei===nn)try{$=new d().parseFromString(le,Xa)}catch{}if(!$||!$.documentElement){$=R.createDocument(Ei,"template",null);try{$.documentElement.innerHTML=up?P:le}catch{}}const Ie=$.body||$.documentElement;return N&&ee&&Ie.insertBefore(n.createTextNode(ee),Ie.childNodes[0]||null),Ei===nn?D.call($,ve?"html":"body")[0]:ve?$.documentElement:Ie},Pw=function(N){return A.call(N.ownerDocument||N,N,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},hc=function(N){return N=ga(N,ce," "),N=ga(N,ie," "),N=ga(N,re," "),N},gp=function(N){var $;N.normalize();const ee=A.call(N.ownerDocument||N,N,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let le=ee.nextNode();for(;le;)le.data=hc(le.data),le=ee.nextNode();const Ie=($=N.querySelectorAll)===null||$===void 0?void 0:$.call(N,"template");Ie&&fa(Ie,$e=>{Ai($e.content)&&gp($e.content)})},gc=function(N){const $=C?C(N):null;return typeof $!="string"||Ke($)!=="form"?!1:typeof N.nodeName!="string"||typeof N.textContent!="string"||typeof N.removeChild!="function"||N.attributes!==b(N)||typeof N.removeAttribute!="function"||typeof N.setAttribute!="function"||typeof N.namespaceURI!="string"||typeof N.insertBefore!="function"||typeof N.hasChildNodes!="function"||N.nodeType!==S(N)||N.childNodes!==h(N)},Ai=function(N){if(!S||typeof N!="object"||N===null)return!1;try{return S(N)===Xt.documentFragment}catch{return!1}},Qa=function(N){if(!S||typeof N!="object"||N===null)return!1;try{return typeof S(N)=="number"}catch{return!1}};function _n(te,N,$){te.length!==0&&fa(te,ee=>{ee.call(t,N,$,Pi)})}const K1=function(N,$){return!!(yn&&N.hasChildNodes()&&!Qa(N.firstElementChild)&&Ze(Cy,N.textContent)&&Ze(Cy,N.innerHTML)||yn&&N.namespaceURI===nn&&$==="style"&&Qa(N.firstElementChild)||N.nodeType===Xt.processingInstruction||yn&&N.nodeType===Xt.comment&&Ze(bR,N.data))},V1=function(N,$){if(!z[$]&&Rw($)&&(ue.tagNameCheck instanceof RegExp&&Ze(ue.tagNameCheck,$)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck($)))return!1;if(sp&&!tn[$]){const ee=v(N),le=h(N);if(le&&ee){const Ie=le.length;for(let $e=Ie-1;$e>=0;--$e){const Be=cp?le[$e]:m(le[$e],!0);ee.insertBefore(Be,g(N))}}}return zn(N),!0},Aw=function(N){if(_n(K.beforeSanitizeElements,N,null),gc(N))return zn(N),!0;const $=Ke(C?C(N):N.nodeName);if(_n(K.uponSanitizeElement,N,{tagName:$,allowedTags:ae}),K1(N,$))return zn(N),!0;if(z[$]||!(W.tagCheck instanceof Function&&W.tagCheck($))&&!ae[$])return V1(N,$);if((S?S(N):N.nodeType)===Xt.element&&!G1(N)||($==="noscript"||$==="noembed"||$==="noframes")&&Ze(_R,N.innerHTML))return zn(N),!0;if(gt&&N.nodeType===Xt.text){const ee=hc(N.textContent);N.textContent!==ee&&(ci(t.removed,{element:N.cloneNode()}),N.textContent=ee)}return _n(K.afterSanitizeElements,N,null),!1},xw=function(N,$,ee){if(G[$]||yt&&($==="id"||$==="name")&&(ee in n||ee in j1))return!1;const le=de[$]||W.attributeCheck instanceof Function&&W.attributeCheck($,N);if(!(Ce&&Ze(ye,$))){if(!(be&&Ze(Y,$))){if(le){if(!dp[$]){if(!Ze(ge,ga(ee,ne,""))){if(!(($==="src"||$==="xlink:href"||$==="href")&&N!=="script"&&hy(ee,"data:")===0&&bw[N])){if(!(ht&&!Ze(he,ga(ee,ne,"")))){if(ee)return!1}}}}}else if(!(Rw(N)&&(ue.tagNameCheck instanceof RegExp&&Ze(ue.tagNameCheck,N)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(N))&&(ue.attributeNameCheck instanceof RegExp&&Ze(ue.attributeNameCheck,$)||ue.attributeNameCheck instanceof Function&&ue.attributeNameCheck($,N))||$==="is"&&ue.allowCustomizedBuiltInElements&&(ue.tagNameCheck instanceof RegExp&&Ze(ue.tagNameCheck,ee)||ue.tagNameCheck instanceof Function&&ue.tagNameCheck(ee))))return!1}}return!0},W1=Ee({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Rw=function(N){return!W1[ha(N)]&&Ze(ke,N)},z1=function(N,$,ee,le){if(T&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!ee)switch(u.getAttributeType(N,$)){case"TrustedHTML":return j(le);case"TrustedScriptURL":return O(le)}return le},J1=function(N,$,ee,le){try{ee?N.setAttributeNS(ee,$,le):N.setAttribute($,le),gc(N)?zn(N):my(t.removed)}catch{Ar($,N)}},Dw=function(N){_n(K.beforeSanitizeAttributes,N,null);const $=N.attributes;if(!$||gc(N))return;const ee={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:de,forceKeepAttr:void 0};let le=$.length;const Ie=Ke(N.nodeName);for(;le--;){const $e=$[le],Be=$e.name,Rt=$e.namespaceURI,wn=$e.value,Bt=Ke(Be),yp=wn;let mt=Be==="value"?yp:tR(yp);if(ee.attrName=Bt,ee.attrValue=mt,ee.keepAttr=!0,ee.forceKeepAttr=void 0,_n(K.uponSanitizeAttribute,N,ee),mt=ee.attrValue,Wn&&(Bt==="id"||Bt==="name")&&hy(mt,yw)!==0&&(Ar(Be,N),mt=yw+mt),yn&&Ze(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,mt)){Ar(Be,N);continue}if(Bt==="attributename"&&fy(mt,"href")){Ar(Be,N);continue}if(!ee.forceKeepAttr){if(!ee.keepAttr){Ar(Be,N);continue}if(!Ft&&Ze(wR,mt)){Ar(Be,N);continue}if(gt&&(mt=hc(mt)),!xw(Ie,Bt,mt)){Ar(Be,N);continue}mt=z1(Ie,Bt,Rt,mt),mt!==yp&&J1(N,Be,Rt,mt)}}_n(K.afterSanitizeAttributes,N,null)},vc=function(N){let $=null;const ee=Pw(N);for(_n(K.beforeSanitizeShadowDOM,N,null);$=ee.nextNode();)if(_n(K.uponSanitizeShadowNode,$,null),Aw($),Dw($),Ai($.content)&&vc($.content),(S?S($):$.nodeType)===Xt.element){const le=w($);Ai(le)&&(vp(le),vc(le))}_n(K.afterSanitizeShadowDOM,N,null)},vp=function(N){const $=[{node:N,shadow:null}];for(;$.length>0;){const ee=$.pop();if(ee.shadow){vc(ee.shadow);continue}const le=ee.node,Ie=(S?S(le):le.nodeType)===Xt.element,$e=h(le);if($e)for(let Be=$e.length-1;Be>=0;--Be)$.push({node:$e[Be],shadow:null});if(Ie){const Be=C?C(le):null;if(typeof Be=="string"&&Ke(Be)==="template"){const Rt=le.content;Ai(Rt)&&$.push({node:Rt,shadow:null})}}if(Ie){const Be=w(le);Ai(Be)&&$.push({node:null,shadow:Be},{node:Be,shadow:null})}}};return t.sanitize=function(te){let N=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},$=null,ee=null,le=null,Ie=null;if(up=!te,up&&(te="<!-->"),typeof te!="string"&&!Qa(te)&&(te=oR(te),typeof te!="string"))throw mr("dirty is not a string, aborting");if(!t.isSupported)return te;vt?(ae=Nt,de=Ii):hp(N),(K.uponSanitizeElement.length>0||K.uponSanitizeAttribute.length>0)&&(ae=ut(ae)),K.uponSanitizeAttribute.length>0&&(de=ut(de)),t.removed=[];const $e=cp&&typeof te!="string"&&Qa(te);if($e){const wn=C?C(te):te.nodeName;if(typeof wn=="string"){const Bt=Ke(wn);if(!ae[Bt]||z[Bt])throw mr("root node is forbidden and cannot be sanitized in-place")}if(gc(te))throw mr("root node is clobbered and cannot be sanitized in-place");try{vp(te)}catch(Bt){throw kw(te),Bt}}else if(Qa(te))$=Ew("<!---->"),ee=$.ownerDocument.importNode(te,!0),ee.nodeType===Xt.element&&ee.nodeName==="BODY"||ee.nodeName==="HTML"?$=ee:$.appendChild(ee),vp(ee);else{if(!bn&&!gt&&!ve&&te.indexOf("<")===-1)return T&&Vn?j(te):te;if($=Ew(te),!$)return bn?null:Vn?P:""}$&&Ya&&zn($.firstChild);const Be=Pw($e?te:$);try{for(;le=Be.nextNode();)Aw(le),Dw(le),Ai(le.content)&&vc(le.content)}catch(wn){throw $e&&kw(te),wn}if($e)return fa(t.removed,wn=>{wn.element&&q1(wn.element)}),gt&&gp(te),te;if(bn){if(gt&&gp($),Pr)for(Ie=I.call($.ownerDocument);$.firstChild;)Ie.appendChild($.firstChild);else Ie=$;return(de.shadowroot||de.shadowrootmode)&&(Ie=F.call(r,Ie,!0)),Ie}let Rt=ve?$.outerHTML:$.innerHTML;return ve&&ae["!doctype"]&&$.ownerDocument&&$.ownerDocument.doctype&&$.ownerDocument.doctype.name&&Ze(vR,$.ownerDocument.doctype.name)&&(Rt="<!DOCTYPE "+$.ownerDocument.doctype.name+`>
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
`),
|
|
51
|
-
`)}
|
|
52
|
-
`).map(a=>{let s=a.match(n.other.beginningSpace);if(s===null)return a;let[c]=s;return c.length>=i.length?a.slice(i.length):a}).join(`
|
|
53
|
-
`)}var $s=class{options;rules;lexer;constructor(e){this.options=e||fr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:Gy(t[0]);return{type:"code",raw:n,codeBlockStyle:"indented",text:n.replace(this.rules.other.codeRemoveIndent,"")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=s0(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=jn(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:jn(t[0],`
|
|
54
|
-
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:jn(t[0],`
|
|
55
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=jn(t[0],`
|
|
41
|
+
`)},LP=0,wi=[];function jP(e){var t=q([]),n=q([0,0]),r=q(),i=x(LP++)[0],o=x(Jh)[0],s=q(e);K(function(){s.current=e},[e]),K(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var g=rP([e.lockRef.current],(e.shards||[]).map(ng),!0).filter(Boolean);return g.forEach(function(h){return h.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),g.forEach(function(h){return h.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var c=se(function(g,h){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!s.current.allowPinchZoom;var y=ss(g),w=n.current,_="deltaX"in g?g.deltaX:w[0]-y[0],I="deltaY"in g?g.deltaY:w[1]-y[1],P,k=g.target,A=Math.abs(_)>Math.abs(I)?"h":"v";if("touches"in g&&A==="h"&&k.type==="range")return!1;var L=window.getSelection(),F=L&&L.anchorNode;if(F&&(F===k||F.contains(k)))return!1;var T=Qh(A,k);if(!T)return!0;if(T?P=A:(P=A==="v"?"h":"v",T=Qh(A,k)),!T)return!1;if(!r.current&&"changedTouches"in g&&(_||I)&&(r.current=P),!P)return!0;var M=r.current||P;return xP(M,h,g,M==="h"?_:I,!0)},[]),l=se(function(g){var h=g;if(!(!wi.length||wi[wi.length-1]!==o)){var y="deltaY"in h?tg(h):ss(h),w=t.current.filter(function(I){return I.name===h.type&&(I.target===h.target||h.target===I.shadowParent)&&DP(I.delta,y)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(ng).filter(Boolean).filter(function(I){return I.contains(h.target)});(_.length>0?c(h,_[0]):!s.current.noIsolation)&&h.cancelable&&h.preventDefault()}}},[]),d=se(function(g,h,y,w){var _={name:g,delta:h,target:y,should:w,shadowParent:OP(y)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(I){return I!==_})},1)},[]),u=se(function(g){n.current=ss(g),r.current=void 0},[]),p=se(function(g){d(g.type,tg(g),g.target,c(g,e.lockRef.current))},[]),f=se(function(g){d(g.type,ss(g),g.target,c(g,e.lockRef.current))},[]);K(function(){return wi.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",l,_i),document.addEventListener("touchmove",l,_i),document.addEventListener("touchstart",u,_i),function(){wi=wi.filter(function(g){return g!==o}),document.removeEventListener("wheel",l,_i),document.removeEventListener("touchmove",l,_i),document.removeEventListener("touchstart",u,_i)}},[]);var m=e.removeScrollBar,v=e.inert;return b(z,null,v?b(o,{styles:$P(i)}):null,m?b(PP,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function OP(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var MP=pP(zh,jP),Co=J(function(e,t){return b(os,an({},e,{ref:t,sideCar:MP}))});Co.classNames=os.classNames;var FP=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Si=new WeakMap,cs=new WeakMap,ls={},od=0,rg=function(e){return e&&(e.host||rg(e.parentNode))},BP=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=rg(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},UP=function(e,t,n,r){var i=BP(t,Array.isArray(e)?e:[e]);ls[n]||(ls[n]=new WeakMap);var o=ls[n],s=[],c=new Set,l=new Set(i),d=function(p){!p||c.has(p)||(c.add(p),d(p.parentNode))};i.forEach(d);var u=function(p){!p||l.has(p)||Array.prototype.forEach.call(p.children,function(f){if(c.has(f))u(f);else try{var m=f.getAttribute(r),v=m!==null&&m!=="false",g=(Si.get(f)||0)+1,h=(o.get(f)||0)+1;Si.set(f,g),o.set(f,h),s.push(f),g===1&&v&&cs.set(f,!0),h===1&&f.setAttribute(n,"true"),v||f.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return u(t),c.clear(),od++,function(){s.forEach(function(p){var f=Si.get(p)-1,m=o.get(p)-1;Si.set(p,f),o.set(p,m),f||(cs.has(p)||p.removeAttribute(r),cs.delete(p)),m||p.removeAttribute(n)}),od--,od||(Si=new WeakMap,Si=new WeakMap,cs=new WeakMap,ls={})}},ds=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||FP(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),UP(r,i,n,"aria-hidden")):function(){return null}},qP=Object.defineProperty,sn=(e,t)=>qP(e,"name",{value:t,configurable:!0}),ad="Dialog",[ig,_U]=lt(ad),[GP,Wn]=ig(ad),HP=sn(e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=q(null),l=q(null),[d,u]=Et({prop:r,defaultProp:i??!1,onChange:o,caller:ad}),[p,f]=x(0),[m,v]=x(0);return a(GP,{scope:t,triggerRef:c,contentRef:l,contentId:Nt(),titleId:Nt(),descriptionId:Nt(),titlePresent:p>0,descriptionPresent:m>0,setTitleCount:f,setDescriptionCount:v,open:d,onOpenChange:u,onOpenToggle:se(()=>u(g=>!g),[u]),modal:s,children:n})},"Dialog"),og="DialogPortal",[KP,ag]=ig(og,{forceMount:void 0}),VP=sn(e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=Wn(og,t);return a(KP,{scope:t,forceMount:n,children:Ir.map(r,s=>a(Pt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:s})}))})},"DialogPortal"),sd="DialogOverlay",zP=J(sn(function(t,n){const r=ag(sd,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Wn(sd,t.__scopeDialog);return s.modal?a(Pt,{present:i||s.open,children:a(JP,{...o,ref:n})}):null},"DialogOverlay")),WP=on("DialogOverlay.RemoveScroll"),JP=J(sn(function(t,n){const{__scopeDialog:r,...i}=t,o=Wn(sd,r),s=Nh(),c=Se(n,s);return a(Co,{as:WP,allowPinchZoom:!0,shards:[o.contentRef],children:a(ve.div,{"data-state":cd(o.open),...i,ref:c,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),Io="DialogContent",YP=J(sn(function(t,n){const r=ag(Io,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Wn(Io,t.__scopeDialog);return a(Pt,{present:i||s.open,children:s.modal?a(XP,{...o,ref:n}):a(QP,{...o,ref:n})})},"DialogContent")),XP=J(sn(function(t,n){const r=Wn(Io,t.__scopeDialog),i=q(null),o=Se(n,r.contentRef,i);return K(()=>{const s=i.current;if(s)return ds(s)},[]),a(sg,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:ne(t.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:ne(t.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&s.preventDefault()}),onFocusOutside:ne(t.onFocusOutside,s=>s.preventDefault())})},"DialogContentModal")),QP=J(sn(function(t,n){const r=Wn(Io,t.__scopeDialog),i=q(!1),o=q(!1);return a(sg,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})},"DialogContentNonModal")),sg=J(sn(function(t,n){const{__scopeDialog:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,...c}=t,l=Wn(Io,r);return bi(),a(z,{children:a(ts,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(hi,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":cd(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),ZP="DialogTitle",eR=J(sn(function(t,n){const{__scopeDialog:r,...i}=t,o=Wn(ZP,r),{setTitleCount:s}=o;return Xe(()=>(s(c=>c+1),()=>s(c=>c-1)),[s]),a(ve.h2,{id:o.titleId,...i,ref:n})},"DialogTitle"));function cd(e){return e?"open":"closed"}sn(cd,"getState");function Rr({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:o=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:f,overlayId:m,slotId:v}){return a(HP,{modal:o,open:p,onOpenChange:u,children:p?a(VP,{children:[a(zP,{asChild:!0,children:a("div",{className:f,id:m})}),a(YP,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:a("div",{role:"dialog",className:r,id:i,onClick:g=>{g.target===g.currentTarget&&u(!1)},tabIndex:-1,children:n??(v?a("div",{id:v}):null)})})]}):null})}function tR(e){return a(eR,{...e})}function nR(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function Po(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function cg(e){const t=new Map;for(const n of e){const r=t.get(n.canonicalId);(!r||n.displayName<r.displayName)&&t.set(n.canonicalId,n)}return[...t.values()].sort(nR)}function kr(e){const t=new Map;for(const r of cg(e)){const i=Po(r.displayName),o=t.get(i);o?o.push(r):t.set(i,[r])}const n=new Map;for(const r of t.values())for(const[i,o]of r.entries())n.set(o.canonicalId,r.length>1?`${o.displayName} — duplicate name ${i+1} of ${r.length}`:o.displayName);return n}function rR(e){const t=new Map;for(const n of cg(e)){const r=Po(n.displayName),i=t.get(r);i?i.canonicalIds.push(n.canonicalId):t.set(r,{displayName:n.displayName,canonicalIds:[n.canonicalId],firstCanonicalId:n.canonicalId})}return[...t.values()].sort((n,r)=>{const i=Po(n.displayName).localeCompare(Po(r.displayName));return i!==0?i:n.firstCanonicalId<r.firstCanonicalId?-1:n.firstCanonicalId>r.firstCanonicalId?1:0}).map(n=>({displayName:n.displayName,identityCount:n.canonicalIds.length}))}var lg=500,us=null,Ro=null,ko=null;function To(e){return Ro?Ro(e)?(ko=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(ko=document.activeElement instanceof HTMLElement?document.activeElement:null,us=e,!0)}function dt(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function dg(e){const t=e.indexOf(":"),n=e.slice(0,t),r=e.slice(t+1);return r?n==="identity"?{recipientKind:"identity",identityId:r}:n==="team"?{recipientKind:"team",teamId:r}:null:null}function No(e){return e.recipientKind==="identity"?dt({recipientKind:"identity",identityId:e.identityId}):dt({recipientKind:"team",teamId:e.teamId})}function iR(e,t){return No(e)===dt(t)}function ld(e,t){const n=[...new Set(e)].sort((r,i)=>r<i?-1:r>i?1:0);return new Map(n.map((r,i)=>[r,n.length===1?t:`${t} ${i+1} of ${n.length}`]))}function oR(e,t){if(t?.mode!=="project-manage")return new Map;const n=new Set(e.teams.map(c=>c.teamId)),r=new Set(e.identities.map(c=>c.identityId)),i=e.projectRecipients.filter(c=>c.status==="active"&&c.canonicalProjectIdentity===t.projectId),o=i.flatMap(c=>c.recipientKind==="team"&&!n.has(c.teamId)?[No(c)]:[]),s=i.flatMap(c=>c.recipientKind==="identity"&&!r.has(c.identityId)?[No(c)]:[]);return new Map([...ld(o,"Unavailable Team"),...ld(s,"Unavailable Identity")])}function aR(e,t,n){if(t?.mode!=="recipient-manage")return new Map;const r=new Set(e.map(i=>i.canonicalProjectIdentity));return ld(n.filter(i=>!r.has(i)),"Unavailable Project")}function ug(e,t){return e instanceof hl?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function pg({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${Cr()}`;return a("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:o,children:[a("input",{checked:e,disabled:n,id:o,onChange:i,type:"checkbox"}),a("span",{children:[a("strong",{className:"recipient-policy-management-name",children:r}),a("span",{className:"small recipient-policy-management-description",children:t})]})]})}function sR(e,t,n){const r=e.teamMemberships.filter(c=>c.status==="active"),i=new Map(e.identities.map(c=>[c.identityId,c])),o=[...e.teams.filter(c=>c.status==="active").map(c=>{const l=r.filter(d=>d.teamId===c.teamId).map(d=>i.get(d.identityId)?.displayName).filter(d=>!!d);return{key:dt({recipientKind:"team",teamId:c.teamId}),label:c.displayName,description:`Team · ${l.length.toLocaleString()} current ${l.length===1?"member":"members"}${l.length?`: ${l.join(", ")}`:""}`}}),...e.identities.filter(c=>c.status==="active"||c.status==="pending").map(c=>({key:dt({recipientKind:"identity",identityId:c.identityId}),label:c.displayName,description:`Identity · ${c.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return o;const s=new Set(o.map(c=>c.key));for(const c of e.projectRecipients){if(c.status!=="active"||c.canonicalProjectIdentity!==t.projectId)continue;const l=No(c);if(!s.has(l)){if(c.recipientKind==="team"){const d=e.teams.find(p=>p.teamId===c.teamId),u=n.get(l)??"Unavailable Team";o.push({key:l,label:d?.displayName??u,description:`${d?.status==="archived"?"Archived Team":u} · existing access can only be removed`})}else{const d=i.get(c.identityId),u=n.get(l)??"Unavailable Identity";o.push({key:l,label:d?.displayName??u,description:`${d?.status==="merged"?"Merged Identity":u} · existing access can only be removed`})}s.add(l)}}return o}function fg(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function cR(e,t){const n=t.projectRecipients.filter(r=>r.status==="active");return e.mode==="project-add"?[]:e.mode==="project-manage"?n.filter(r=>r.canonicalProjectIdentity===e.projectId).map(No):n.filter(r=>iR(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function lR(e,t,n,r){const i=kr(e.map(d=>({canonicalId:d.canonicalProjectIdentity,displayName:d.displayName}))),o=t.mode==="recipient-add"?e.filter(d=>!n.includes(d.canonicalProjectIdentity)):e,s=o.map(d=>({...d,displayName:i.get(d.canonicalProjectIdentity)??d.displayName,description:`${d.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return s;const c=new Set(o.map(d=>d.canonicalProjectIdentity)),l=n.filter(d=>!c.has(d));for(const d of l){const u=r.get(d)??"Unavailable Project";s.push({canonicalProjectIdentity:d,displayName:u,existingMemoryCount:0,description:`${u} · existing access can only be removed`})}return s}function dR(e,t,n){return e.mode==="project-add"?fg(e).flatMap(r=>t.flatMap(i=>{const o=dg(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=dg(r);return!i||n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:e.projectId,recipient:i,action:t.includes(r)?"add":"remove"}]}):e.mode==="recipient-add"?t.map(r=>({canonicalProjectIdentity:r,recipient:e.recipient,action:"add"})):[...new Set([...n,...t])].flatMap(r=>n.includes(r)===t.includes(r)?[]:[{canonicalProjectIdentity:r,recipient:e.recipient,action:t.includes(r)?"add":"remove"}])}function uR(e){return e.mode==="project-add"?{title:"Add recipient access",description:"Choose the Teams and Identities that should receive the selected Projects.",legend:"Choose recipients"}:e.mode==="project-manage"?{title:"Manage Project recipients",description:"Choose exactly which Teams and Identities receive this Project.",legend:"Project recipients"}:e.mode==="recipient-add"?{title:"Add Projects",description:"Choose additional Projects for this recipient. Existing access cannot be removed here.",legend:"Additional Projects"}:{title:"Manage recipient Projects",description:"Choose exactly which Projects this recipient receives.",legend:"Recipient Projects"}}function mg(e,t){let n=!1,r=!1,i=!1,o=!1;const s=dt(t);for(const c of e){const{change:l,outcome:d}=c;dt(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(o=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!o?"Already has access":o&&!i?"Already without access":"No changes"}function pR(e){const t=new Set(e.selectedRecipients.map(dt)),n=new Map;for(const r of e.normalizedChanges){const i=dt(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function fR(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function dd(e,t){const n=t.get(e.canonicalProjectIdentity);return n||(e.displayName!==e.canonicalProjectIdentity?e.displayName:"Unavailable Project")}function mR({preview:e,projectLabels:t,recipientLabels:n}){const r=fR(e.effectiveDevices),i=pR(e);return a("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[a("section",{"aria-labelledby":"recipient-policy-review-projects",children:[a("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),a("ul",{children:e.projects.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:dd(o,t)}),a("span",{children:[" ","— Access changes affect ",o.existingMemoryCount.toLocaleString()," existing memories",o.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},o.canonicalProjectIdentity))})]}),a("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[a("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),a("ul",{children:[e.selectedRecipients.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:o.displayName})," ",a("span",{children:["— ",mg(e.outcomes,o)," · "]}),o.recipientKind==="identity"?a("span",{children:"Identity · locally verified"}):a("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",o.currentMembers.length.toLocaleString()," current"," ",o.currentMembers.length===1?"member":"members",o.currentMembers.length?a(z,{children:[":"," ",a("span",{className:"recipient-policy-management-member-names",children:o.currentMembers.map(s=>s.displayName).join(", ")})]}):null,". Future Team members"," ",o.futureMembersInherit?"inherit":"do not inherit"," access."]})]},dt(o))),i.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:n.get(dt(o))??(o.recipientKind==="team"?"Unavailable Team":"Unavailable Identity")})," ",a("span",{children:["— ",mg(e.outcomes,o)," ·"," ",o.recipientKind==="team"?"Team":"Identity"]})]},dt(o)))]})]}),a("section",{"aria-labelledby":"recipient-policy-review-availability",children:[a("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),r.length?a(z,{children:[a("p",{children:["After the update, the affected Projects will be available on"," ",r.length.toLocaleString()," current"," ",r.length===1?"device":"devices"," across all recipients."]}),a("ul",{children:r.map(o=>a("li",{className:"recipient-policy-management-name",children:o.displayName},o.deviceId))})]}):a("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),a("details",{className:"recipient-policy-management-details",children:[a("summary",{children:"Change details"}),a("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?a(z,{children:[a("p",{className:"small recipient-policy-management-detail-label",children:a("strong",{children:"Unchanged Projects"})}),a("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(o=>a("li",{className:"recipient-policy-management-name",children:dd(o,t)},o.canonicalProjectIdentity))})]}):null]})]})}function hR({preview:e,projectLabels:t,recipientLabels:n,result:r}){const i=r.status==="applied"?"Applied":r.status==="not_found"?"Not found":`${r.status.charAt(0).toUpperCase()}${r.status.slice(1)}`;return a("div",{className:"sync-dialog-stack recipient-policy-management-result",children:a("details",{className:"recipient-policy-management-details",children:[a("summary",{children:"Technical details"}),a("p",{children:["Status: ",i,". Writes: ",r.writeCount.toLocaleString(),"."]}),r.errorCode?a("p",{children:["Error code: ",r.errorCode.replaceAll("_"," "),"."]}):null,r.outcomes.length?a("ul",{children:r.outcomes.map(o=>{const s=e.projects.find(d=>d.canonicalProjectIdentity===o.change.canonicalProjectIdentity),c=s?dd(s,t):t.get(o.change.canonicalProjectIdentity)??"Unavailable Project",l=e.selectedRecipients.find(d=>dt(d)===dt(o.change.recipient))?.displayName??n.get(dt(o.change.recipient))??(o.change.recipient.recipientKind==="team"?"Team":"Identity");return a("li",{children:[o.change.action==="add"?"Add":"Remove"," ",l," ",o.change.action==="add"?"to":"from"," ",c,":"," ",o.outcome.replaceAll("_"," ")]},`${o.change.canonicalProjectIdentity}:${dt(o.change.recipient)}`)})}):null]})})}function gR({intent:e,options:t,projects:n}){const[r,i]=x(null),[o,s]=x([]),[c,l]=x([]),[d,u]=x(null),[p,f]=x(null),[m,v]=x(null),[g,h]=x(""),[y,w]=x(!1),_=q(!1),I=q(new Map),P=q(new Map),k=Re(()=>oR(e,r),[e,r]),A=Re(()=>sR(e,r,k),[e,r,k]),L=Re(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName]),...k]),[e,k]),F=Re(()=>aR(n,r,c),[c,n,r]),T=Re(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]),M=Re(()=>{const Y=kr(n.map(ce=>({canonicalId:ce.canonicalProjectIdentity,displayName:ce.displayName})));return new Map([...Y,...F])},[n,F]);if(K(()=>{if(Ro=Y=>{if(_.current)return!1;const ce=cR(Y,e);return i(Y),l(ce),s(Y.mode==="recipient-add"?[]:ce),u(null),f(null),I.current=new Map,P.current=new Map,v(null),h(""),w(!1),_.current=!1,!0},us){const Y=us;us=null,Ro(Y)}return()=>{Ro=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const j=uR(r),B=fg(r),U=r.mode==="recipient-manage"?!1:B.some(Y=>!T.has(Y)),$=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!A.some(Y=>Y.key===dt(r.recipient)),E=t.loading||t.loadError||U||$,S=dR(r,o,c),D=S.length>lg,H=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,G=r.mode!=="project-add"&&r.mode!=="recipient-add"&&S.length===0,oe=lR(n,r,c,F),ae=p?.status==="applied",ee=p?ae?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":j.title,ie=p?ae?"The reviewed recipient access changes are applied.":"Some reviewed recipient access changes were not applied. Review the technical details.":d?"Confirm the exact Projects, recipients, and resulting access.":j.description,Ce=()=>{_.current||(i(null),u(null),f(null),I.current=new Map,P.current=new Map,v(null),h(""))},Ie=Y=>{s(ce=>ce.includes(Y)?ce.filter(ge=>ge!==Y):[...ce,Y]),v(null),h("")},Ne=async()=>{if(!(E||H||G||D||_.current)){_.current=!0,w(!0),v(null),h("Reviewing exact recipient access changes.");try{const Y=await TC({version:1,changes:S});I.current=new Map(L),P.current=new Map(M),u(Y),h("Review ready. Confirm the exact changes.")}catch(Y){v(ug(Y,"Unable to review recipient access changes.")),h("")}finally{_.current=!1,w(!1)}}},le=async()=>{if(!(!d||_.current)){_.current=!0,w(!0),v(null),h("Saving recipient access changes.");try{const Y=await NC({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});f(Y),h("");try{await t.onCommitted?.(Y)}catch{v("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof hl&&(u(null),I.current=new Map,P.current=new Map,h("")),v(ug(Y,"Unable to save recipient access changes."))}finally{_.current=!1,w(!1)}}};let ye=null;return t.loading?ye="Loading the complete recipient access inventory…":t.loadError?ye="The complete recipient access inventory is unavailable. Refresh and try again.":U?ye="One selected Project is no longer available. Refresh and try again.":$&&(ye="This recipient is no longer available. Refresh and try again."),a(Rr,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const ce=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ge=ko?.isConnected?ko:document.getElementById(ce);ge instanceof HTMLElement&&ge.focus(),ko=null},onOpenAutoFocus:Y=>{const ce=document.getElementById("recipient-policy-management-title");ce&&(Y.preventDefault(),ce.focus())},onOpenChange:Y=>{Y||Ce()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":y||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:ee}),a(ui,{ariaLabel:`Close ${ee}`,className:"modal-close-button recipient-policy-management-target",disabled:y,onClick:Ce})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:ie}),ye?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:ye}):p&&d?a(hR,{preview:d,projectLabels:P.current,recipientLabels:I.current,result:p}):d?a(mR,{preview:d,projectLabels:P.current,recipientLabels:I.current}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:y,children:[a("legend",{children:j.legend}),oe.length?oe.map(Y=>a(pg,{checked:o.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:y,label:Y.displayName,onChange:()=>Ie(Y.canonicalProjectIdentity)},Y.canonicalProjectIdentity)):a("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):a("fieldset",{className:"sync-dialog-radio-list",disabled:y,children:[a("legend",{children:j.legend}),A.length?A.map(Y=>a(pg,{checked:o.includes(Y.key),description:Y.description,disabled:y,label:Y.label,onChange:()=>Ie(Y.key)},Y.key)):a("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:a("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:g}),m?a("p",{"aria-live":"assertive",role:"alert",children:m}):null,D?a("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",S.length.toLocaleString()," access changes. Review at most ",lg.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),a("div",{className:"modal-footer recipient-policy-management-actions",children:[a("button",{className:"settings-button recipient-policy-management-target",disabled:y,onClick:d&&!p?()=>{u(null),I.current=new Map,P.current=new Map,h("")}:Ce,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!ye?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:y||!d&&(H||G||D),onClick:()=>{d?le():Ne()},type:"button",children:y?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function hg(e,t,n,r={}){We(a(gR,{intent:n,options:r,projects:t}),e)}function ps(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function vR(e){const t=new Map;for(const n of e)n.read_only_reason==="peer_received"&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0,latestSessionAt:n.latest_session_at??null});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function fs(e){const t=new Map;for(const n of e)ps(n)&&t.set(n.workspace_identity,{canonicalProjectIdentity:n.workspace_identity,displayName:n.display_project,existingMemoryCount:n.memory_count??0});return[...t.values()].sort((n,r)=>n.displayName.localeCompare(r.displayName)||n.canonicalProjectIdentity.localeCompare(r.canonicalProjectIdentity))}function gg({detailRowCount:e=3,label:t}){return a(z,{children:[a("span",{className:"sr-only",role:"status",children:t}),a("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>a("div",{"aria-hidden":"true",className:"loading-card",children:[a("div",{className:"loading-card-header",children:[a("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),a("span",{className:"loading-card-badge"})]}),a("div",{className:"loading-card-details",children:Array.from({length:e},(i,o)=>a("div",{className:"loading-card-detail",children:[a("span",{className:"loading-card-line loading-card-label"}),a("span",{className:`loading-card-line ${(r+o)%2?"w-45":"w-60"}`})]},o))})]},r))})]})}function yR(e){return e.state!=="configured"}function vg(e){return e?.items.filter(yR)??[]}function ms(e,t){return e.truncated?{blocked:!0,recovery:"Refresh Devices after the complete inventory is available."}:e.coordinatorEvidence.availability==="available"?{blocked:!1,recovery:null}:e.coordinatorEvidence.safeErrorCode==="coordinator_not_configured"&&t.isLocal?{blocked:!1,recovery:null}:{blocked:!0,recovery:"Refresh Devices after coordinator device information is available."}}var bR=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,_R=/^(?:actor|device|identity|local):\S+$/iu,wR=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,SR=/^pending[_-]\S+$/iu,CR=/^[a-f0-9]{12,64}$/iu;function ud(e){return[bR,_R,wR,SR,CR].some(t=>t.test(e))}function Ci(e){if(typeof e!="string"||[...e].some(n=>/[\p{Cc}\p{Cf}]/u.test(n)))return"";const t=e.replace(/\s+/gu," ").trim();return!t||[...t].length>120||ud(t)?"":t}var Ii=null,Pi=null;function hs(e=[],t=""){if(Pi){const n=Pi(e,t);return n||(Ii=null),n}return Ii={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function yg(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function bg(e,t){if(!(e instanceof Error))return t;switch(e.message){case"team_sharing_not_configured":return"Set up Team sharing before creating an invitation.";case"team_selection_ambiguous":return"Choose one active Team in settings before creating an invitation.";case"project_selection_ambiguous":return"One selected project has a name collision. Review its project identity first.";case"project_selection_unsupported":case"project_selection_unknown":case"reviewed_project_set_changed":return"The selected projects changed. Review the invitation again.";default:return t}}function IR(e){const t=`share-project-${Cr()}`,n=yg(e.project);return a("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[a("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),a("span",{children:[a("strong",{children:e.project.display_project}),a("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function PR({preview:e}){return a("div",{className:"sync-dialog-stack",children:[a("p",{children:a("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?a("p",{className:"small",children:"This invitation will use the existing teammate."}):null,a("ul",{children:e.projects.map(t=>a("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),a("p",{children:a("strong",{children:"No other projects will be shared."})})]})}function RR({projects:e,inventoryError:t}){const[n,r]=x(!1),[i,o]=x(""),[s,c]=x([]),[l,d]=x(null),[u,p]=x(null),[f,m]=x(null),[v,g]=x(!1),[h,y]=x(null),[w,_]=x(!1),I=Re(()=>e.filter(yg),[e]);K(()=>{if(Pi=(T,M="")=>{if(t)return!1;const j=[...new Set(T)],B=j.some(U=>!I.some($=>$.workspace_identity===U));return o(M.trim()),c(B?[]:j),_(B),d(null),p(null),m(B?"The original project selection is no longer available. Refresh Projects and try again.":null),y(null),r(!0),!0},Ii){const T=Ii;Ii=null,Pi(T.projectIds,T.teammateName)}return()=>{Pi=null}},[I,t]),K(()=>{t&&(Ii=null,r(!1),o(""),c([]),d(null),p(null),m(null),y(null),_(!1))},[t]);const P=()=>{v||r(!1)},k=T=>{c(M=>M.includes(T)?M.filter(j=>j!==T):[...M,T])},A=async()=>{if(m(null),!i.trim()){m("Enter your teammate's name.");return}if(s.length===0){m("Select at least one project.");return}g(!0);try{d(await $C({teammate_name:i.trim(),project_ids:s}))}catch(T){m(bg(T,"Unable to review this invitation."))}finally{g(!1)}},L=async()=>{if(l){m(null),g(!0);try{p(await LC({teammate_name:l.teammate.display_name,project_ids:l.projects.map(T=>T.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(T){T instanceof Error&&T.message==="reviewed_project_set_changed"&&d(null),m(bg(T,"Unable to create this invitation."))}finally{g(!1)}}},F=async()=>{if(u){m(null),y(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),y("Invite copied.")}catch(T){m(T instanceof Error?T.message:"Unable to copy the invitation.")}}};return a(z,{children:[a("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||I.length===0,onClick:()=>Pi?.([]),type:"button",children:"Share projects"}),t?a("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?a(Rr,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:T=>{T||P()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:a("div",{className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"project-share-title",children:"Share projects"}),a("button",{"aria-label":"Close Share projects",disabled:v,onClick:P,type:"button",children:"×"})]}),a("div",{"aria-busy":v,className:"modal-body",children:[a("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?a("div",{children:[a("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),a("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(T=>T.display_name).join(", "),"."]}),a("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),a("button",{className:"settings-button",onClick:()=>{F()},type:"button",children:"Copy invite"}),h?a("p",{role:"status",children:h}):null]}):l?a(PR,{preview:l}):a(z,{children:[a("label",{className:"field",htmlFor:"project-share-teammate",children:[a("span",{children:"Who are you sharing with?"}),a("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:T=>o(T.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(T=>a(IR,{onToggle:k,project:T,selected:s.includes(T.workspace_identity)},T.workspace_identity))]})]}),f?a("p",{role:"alert",children:f}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:v,onClick:P,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:v||w,onClick:()=>{l?L():A()},type:"button",children:v?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function _g(e,t,n={}){We(a(RR,{inventoryError:n.inventoryError===!0,projects:t}),e)}function pd(e){return Ci(String(e??"").trim())}function Ri(e,t){const n=e.trim();return n?[...n].length>120?`${t} must use 120 characters or fewer.`:[...n].some(r=>/[\p{Cc}\p{Cf}]/u.test(r))?`${t} cannot include control or format characters.`:ud(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function kR(e){return{...e,status:e.status==="pending_setup"?"pending_setup":void 0,setup_state:e.setup_state==="pending_inviter"||e.setup_state==="restart_required"?e.setup_state:void 0,restart_required:e.restart_required===!0,detail:typeof e.detail=="string"?e.detail:void 0,type:e.type==="project_share"?"project_share":void 0}}function gs(e,t){return e instanceof Error?e instanceof zf?{device_display_name_invalid:"Enter a human-readable device name instead of an internal identifier.",device_display_name_required:"Enter a device display name.",device_display_name_too_long:"Use a device display name with 120 characters or fewer.",invite_already_bound:"This invitation was accepted by another device. Ask the owner to create a new invitation.",invite_expired:"This invitation expired. Ask the owner to create a new invitation.",invite_identity_conflict:"This invitation does not match this Identity. Ask the owner to create a new invitation for this recipient.",invite_invalid:"This invitation is no longer valid. Ask the owner to create a new invitation.",inviter_identity_invalid:"The owner's device identity could not be verified. Ask the owner to review the share and create a new invitation.",project_invite_acceptance_failed:"The invitation could not be accepted safely. Retry once, then ask the owner to review the share.",project_invite_bootstrap_incomplete:"The owner's device is not ready to establish trust yet. Retry once, then ask the owner to review the share.",project_invite_self_acceptance_forbidden:"The owner cannot accept this recipient invitation on the owner's device.",project_invite_trust_state_invalid:"The owner's trust setup could not be verified. Ask the owner to review the share.",project_sync_enablement_failed:"The invitation was accepted, but Project setup could not be enabled because the codemem config is not writable. Make the config writable, then check Sync to finish setup.",recipient_display_name_invalid:"Enter a human-readable Identity name instead of an internal identifier.",recipient_display_name_required:"Enter an Identity display name.",recipient_display_name_too_long:"Use an Identity display name with 120 characters or fewer."}[e.errorCode]??t:e.message==="reviewed_onboarding_stale"?"Invitation details changed. Review them again before creating it.":e.message==="recipient_invite_review_unavailable"?"The invitation review is unavailable. Ask the owner to create a new invitation.":e.message==="recipient_invite_intent_mismatch"?"The invitation details do not match the reviewed access. Ask the owner to create a new invitation.":e.message==="invite_identity_conflict"?"This device already belongs to a different Identity. Use a fresh device or ask the owner for the correct invitation.":e.message==="recipient_display_name_invalid"?"Enter a human-readable Identity name instead of an internal identifier.":e.message==="recipient_display_name_required"?"Enter an Identity display name before accepting.":e.message==="recipient_display_name_too_long"?"Use an Identity display name with 120 characters or fewer.":t:t}function Eo(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function TR({preview:e}){return e.projects.length===0?a("p",{className:"small",children:"No Projects are currently shared with this Team."}):a("ul",{children:e.projects.map(t=>a("li",{children:[a("strong",{children:t.displayName})," — ",Eo(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function NR({preview:e}){return a("div",{className:"sync-dialog-stack",children:[a("p",{children:a("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),a(TR,{preview:e}),a("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),a("p",{children:a("strong",{children:"No other Projects will be shared through this invitation."})})]})}function ER({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return a("div",{className:"sync-dialog-stack",children:[a("section",{"aria-labelledby":"add-device-direct-projects",children:[a("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?a("ul",{children:t.map(r=>a("li",{children:[r.displayName," — ",Eo(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):a("p",{className:"small",children:"No Projects are shared directly."})]}),a("section",{"aria-labelledby":"add-device-team-projects",children:[a("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?a("ul",{children:n.map(r=>{const i=r.sources.filter(o=>o.kind==="team").map(o=>o.displayName);return a("li",{children:[r.displayName," — ",Eo(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):a("p",{className:"small",children:"No Projects are inherited through Teams."})]}),a("section",{"aria-labelledby":"add-device-excluded-projects",children:[a("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?a("ul",{children:e.excludedProjects.map(r=>a("li",{children:[r.displayName," — ",Eo(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):a("p",{className:"small",children:"No other Projects are excluded."}),a("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?a("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function wg({preview:e}){return e.journey==="team"?a(NR,{preview:e}):a(ER,{preview:e})}function AR({error:e,name:t,onChange:n}){return a("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[a("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),a("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[a("span",{children:"Identity display name"}),a("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?a("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function xR({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:o,recipientNameError:s}){const c=n.projects??[];return a("div",{className:"sync-dialog-stack",children:[a("section",{"aria-labelledby":"project-share-invitation-recipient",children:[a("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),a("p",{children:"Review these display names before importing the invitation."}),a("label",{className:"field",htmlFor:"project-share-recipient-name",children:[a("span",{children:"Identity display name"}),a("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:o})]}),s?a("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,a("label",{className:"field",htmlFor:"project-share-device-name",children:[a("span",{children:"Device display name"}),a("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?a("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),a("section",{"aria-labelledby":"project-share-invitation-projects",children:[a("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?a("p",{children:["Invitation from ",n.inviter_name,"."]}):null,a("p",{children:["You will receive ",a("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?a("ul",{children:c.map((l,d)=>a("li",{children:[a("strong",{children:l.display_name})," —"," ",Eo(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):a("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),a("p",{children:a("strong",{children:"Accepting this invitation does not join a Team."})}),a("p",{children:a("strong",{children:"No other Projects are included."})})]})}function DR({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return a("div",{className:"sync-dialog-stack",children:[a("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?a("p",{role:"status",children:[a("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?a("p",{role:"status",children:[a("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):a("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function $R({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added",n=[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0;return a("section",{"aria-describedby":n,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[a("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),a("div",{className:"recipient-policy-invitation-result-copy",children:[a("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?a("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?a("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Sg(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function LR({intent:e}){const t=e.teams.filter(W=>W.status==="active"),n=e.identities.filter(W=>W.status==="active"),[r,i]=x(null),[o,s]=x("team_member"),[c,l]=x(t[0]?.teamId??""),[d,u]=x(""),[p,f]=x(null),[m,v]=x(null),[g,h]=x(null),[y,w]=x(null),[_,I]=x(""),[P,k]=x(""),[A,L]=x(""),[F,T]=x(null),[M,j]=x(!1),[B,U]=x(""),[$,E]=x(""),S=q(null),D=q(0),H=q(""),G=q(!1);K(()=>{if(y){document.getElementById("recipient-invitation-result")?.focus();return}if(g){document.getElementById("project-share-invitation-result")?.focus();return}m?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[m,g,y]);const oe=()=>{D.current+=1,H.current="",G.current=!1,u(""),f(null),v(null),h(null),w(null),I(""),k(""),L(""),T(null),U(""),E("")},ae=(W,Pe)=>{oe(),S.current=Pe,i(W)},ee=()=>{M||(i(null),oe())},ie=W=>{D.current+=1,H.current=W,u(W)},Ce=W=>{s(W),l(W==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),oe()},Ie=async()=>{if(c){j(!0),E(""),U("Reviewing invitation…");try{const W=await EC(Sg(o,c));f(W.preview),U("Review ready. Confirm the invitation details.")}catch(W){E(gs(W,"Unable to review this invitation.")),U("")}finally{j(!1)}}},Ne=async()=>{if(p){j(!0),E(""),U("Creating invitation…");try{const W=await AC({...Sg(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest});T(W),U("Invitation created.")}catch(W){W instanceof Error&&W.message==="reviewed_onboarding_stale"&&f(null),E(gs(W,"Unable to create this invitation.")),U("")}finally{j(!1)}}},le=async()=>{const W=H.current.trim(),Pe=D.current;if(!W){E("Paste an invitation first.");return}const re=()=>D.current===Pe&&H.current.trim()===W;j(!0),E(""),U("Reviewing invitation…");try{const je=await Wf(W);if(!re())return;v(je),je.kind==="team_member"?I(pd(je.recipient_name)):je.kind==="project_share_invite"&&(k(pd(je.recipient_name)),L(pd(je.device_name))),U(je.kind==="add_device"?(je.onboarding?.projects?.length??0)>0?"Review ready. Existing shared Projects sync to the invited device only after the owner’s device completes access setup. Confirm before accepting.":"Review ready. Confirm before accepting.":je.kind==="team_member"?"Review ready. Confirm before accepting.":je.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced, then Sync, to review and import this legacy invitation.")}catch(je){if(!re())return;E(gs(je,"Unable to review this invitation.")),U("")}finally{j(!1)}},ye=async()=>{if(!(M||G.current||y)&&!(!m||m.kind==="legacy_team_invite")&&!(m.kind==="project_share_invite"&&!(m.projects?.length??0))&&!(m.kind==="project_share_invite"&&(Ri(P,"Identity display name")||Ri(A,"Device display name")))&&!(m.kind==="team_member"&&Ri(_,"Identity display name"))){G.current=!0,j(!0),E(""),U("Accepting invitation…");try{const W=m.kind==="project_share_invite"?await pl(d.trim(),{recipient_name:P.trim(),device_name:A.trim()},m.kind):await pl(d.trim(),{...m.kind==="team_member"?{recipient_name:_.trim()}:{},device_name:m.device_name,reviewed_onboarding_digest:m.onboarding.reviewedOnboardingDigest},m.kind);if(m.kind==="project_share_invite")h(kR(W)),U("");else{const Pe=m.kind,re=W.restart_required===!0||W.setup_state==="restart_required";w({kind:Pe,restartRequired:re,detail:Pe==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:Pe==="add_device"&&(m.onboarding?.projects?.length??0)>0}),U("")}}catch(W){G.current=!1;const Pe=m.kind==="project_share_invite"?"Unable to accept this Project invitation. Ask the owner to create a new invitation, then try again.":"Unable to accept this invitation.";E(gs(W,Pe)),U("")}finally{j(!1)}}},Y=async()=>{const W=F?.invite.link||F?.invite.encoded||"";if(!W){E("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(W),U("Invitation copied.")}catch{E("Unable to copy the invitation.")}},ce=m?.kind==="team_member"||m?.kind==="add_device"?m.onboarding:null,ge=m?.kind==="project_share_invite"?m:null,pe=m?.kind==="team_member"?Ri(_,"Identity display name"):"",He=ge?Ri(P,"Identity display name"):"",de=ge?Ri(A,"Device display name"):"";return a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[a("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[a("h3",{children:"Create an invitation"}),a("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),a("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[a("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:W=>{Ce("team_member"),ae("create",W.currentTarget)},type:"button",children:"Invite Team member"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:W=>{Ce("add_device"),ae("create",W.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>hs(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?a("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),a("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[a("h3",{children:"Accept an invitation"}),a("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:W=>ae("accept",W.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced, in Sync."})]}),r?a(Rr,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:W=>{W.preventDefault(),S.current?.focus(),S.current=null},onOpenAutoFocus:W=>{W.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:W=>{W||ee()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:a("div",{"aria-busy":M,className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-invitation-title",tabIndex:-1,children:y?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(ui,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:M,onClick:ee})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:y?"The invitation has been accepted.":"Confirm exactly what this invitation includes before continuing."}),r==="create"&&!p&&!F?a("label",{className:"field",htmlFor:"recipient-invitation-target",children:[a("span",{children:o==="team_member"?"Team":"Identity"}),a("select",{id:"recipient-invitation-target",onChange:W=>l(W.currentTarget.value),value:c,children:(o==="team_member"?t:n).map(W=>a("option",{value:"teamId"in W?W.teamId:W.identityId,children:W.displayName},"teamId"in W?W.teamId:W.identityId))})]}):r==="accept"&&!m&&!y?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:W=>{ie(W.currentTarget.value),v(null),h(null),U(""),E("")},rows:5,value:d})]}):null,p?a(wg,{preview:p}):null,ce&&!y?a(wg,{preview:ce}):null,m?.kind==="team_member"&&!y?a(AR,{error:pe,name:_,onChange:W=>{I(W),E("")}}):null,ge&&!g?a(xR,{deviceName:A,deviceNameError:de,invite:ge,onDeviceNameChange:W=>{L(W),E("")},onRecipientNameChange:W=>{k(W),E("")},recipientName:P,recipientNameError:He}):null,g?a(DR,{result:g}):null,y?a($R,{result:y}):null,F?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{Y()},type:"button",children:"Copy invitation"})]}):null,m?.kind==="legacy_team_invite"?a("p",{children:"Open Advanced, then Sync, to review and import this legacy invitation."}):null,a("p",{"aria-live":"polite",className:"small",role:"status",children:B}),$?a("p",{"aria-live":"assertive",role:"alert",children:$}):null]}),a("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[a("button",{className:"settings-button",disabled:M,onClick:ee,type:"button",children:F||g||y?"Done":"Cancel"}),r==="create"&&!F?a("button",{className:"settings-button sync-dialog-confirm",disabled:M||!c,onClick:()=>{p?Ne():Ie()},type:"button",children:M?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!m&&!y?a("button",{className:"settings-button sync-dialog-confirm",disabled:M,onClick:()=>{le()},type:"button",children:M?"Reviewing…":"Review invitation"}):ce&&!y||ge&&!g?a("button",{className:"settings-button sync-dialog-confirm",disabled:M||!!(m?.kind==="team_member"&&pe)||!!(ge&&(!ge.projects?.length||He||de)),onClick:()=>{ye()},type:"button",children:M?"Accepting…":ge?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}function jR(e){const t=e.trim();return t?[...t].length>120?"Team name must use 120 characters or fewer.":[...t].some(n=>/[\p{Cc}\p{Cf}]/u.test(n))?"Team name cannot include control or format characters.":ud(t)?"Enter a human-readable Team name.":"":"Team name is required."}function OR(e){return e instanceof Ba?e.errorCode==="team_name_invalid"?"Enter a valid human-readable Team name.":e.errorCode==="team_not_found"?"This Team is no longer available. Refresh Sharing and try again.":e.errorCode==="team_rename_stale"?"This Team changed since you opened settings. Refresh Sharing and try again.":e.errorCode==="team_link_stale"?"This Team’s connected setup is no longer configured. Refresh Sharing before renaming it.":e.errorCode==="team_link_ambiguous"?"This Team has conflicting connected setup records. Nothing was changed. Review the Team setup before retrying.":e.errorCode==="team_coordinator_rename_failed"?"The connected Team service could not be updated. Nothing changed locally. Try again.":e.errorCode==="team_local_rename_pending"?"The connected Team service was updated, but Sharing could not save the name locally. Try again to finish.":"The Team could not be renamed safely. Try again.":"The Team could not be renamed. Try again."}function MR({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=iC,teamId:o}){const[s,c]=x(!1),[l,d]=x(n),[u,p]=x(!1),[f,m]=x(""),[v,g]=x(""),h=q(null),y=q(null),w=q(null);K(()=>{v&&!u&&w.current?.focus()},[u,v]);const _=()=>{u||(c(!1),m(""),g(""))},I=async()=>{const P=jR(l);if(P){m(P);return}if(!u){p(!0),m(""),g("");try{const k=await i({teamId:o,displayName:l,expectedDisplayName:n});d(k.displayName),g(`Team renamed to ${k.displayName}.`);try{await r?.()===!1&&g(`Team renamed to ${k.displayName}, but Sharing could not refresh.`)}catch{g(`Team renamed to ${k.displayName}, but Sharing could not refresh.`)}}catch(k){m(OR(k))}finally{p(!1)}}};return a(z,{children:[a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Team settings for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||(d(n),m(""),g(""),c(!0))},ref:h,type:"button",children:"Team settings"}),a(Rr,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:P=>{P.preventDefault(),h.current?.focus()},onEscapeKeyDown:P=>{u&&P.preventDefault()},onInteractOutside:P=>{u&&P.preventDefault()},onOpenAutoFocus:P=>{P.preventDefault(),y.current?.focus(),y.current?.select()},onOpenChange:P=>{P||_()},open:s,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyTeamSettingsDialogBackdrop",children:a("div",{"aria-busy":u?"true":"false",className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-policy-team-settings-title",children:"Team settings"}),a(ui,{ariaLabel:"Close Team settings",disabled:u,onClick:_})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-policy-team-settings-description",children:"Change the name shown for this Team in Sharing."}),a("label",{className:"form-field",htmlFor:"recipient-policy-team-settings-name",children:[a("span",{children:"Team name"}),a("input",{disabled:u||!!v,id:"recipient-policy-team-settings-name",maxLength:120,onInput:P=>{d(P.currentTarget.value),m("")},ref:y,value:l})]}),u?a("p",{"aria-live":"polite",role:"status",children:"Saving Team name…"}):null,f?a("p",{"aria-live":"assertive",role:"alert",children:f}):null,v?a("p",{"aria-live":"polite",role:"status",children:v}):null]}),a("div",{className:"modal-footer recipient-policy-team-settings-actions",children:[a("button",{className:"settings-button",disabled:u,onClick:_,ref:w,type:"button",children:v?"Done":"Cancel"}),v?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:u||!l.trim()||l.trim()===n,onClick:()=>{I()},type:"button",children:u?"Saving…":f?"Try again":"Save"})]})]})})]})}var Cg={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Ig={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},fd={role:"list"},md={role:"listitem"};function FR(e){return typeof e=="string"&&Object.hasOwn(Cg,e)?Cg[e]:"Ready to review"}function BR(e){return typeof e=="string"&&Object.hasOwn(Ig,e)?Ig[e]:"needs_attention"}function UR(e){const t=new Map;for(const n of e){const r=n.displayName.trim().toLowerCase(),i=t.get(r);i?t.set(r,{...i,candidates:[...i.candidates,n]}):t.set(r,{displayName:n.displayName,candidates:[n]})}return[...t.values()].map(n=>({...n,candidates:[...n.candidates].sort((r,i)=>r.candidateRef<i.candidateRef?-1:r.candidateRef>i.candidateRef?1:0)}))}function qR({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=UR(e);return a("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-team-setup-heading",children:"Legacy groups to migrate"}),a("p",{children:"Current devices are proposed for review. No Team membership or Project access changes happen until you finish the migration."}),a("ul",{...fd,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:n.map(r=>b("li",{...md,className:"recipient-policy-sharing-team-setup-group",key:r.displayName},r.candidates.length>1?a("div",{className:"recipient-policy-sharing-team-setup-group-title",children:[a("strong",{children:r.displayName}),a("span",{className:"small",children:[r.candidates.length," Teams"]})]}):null,a("div",{className:"recipient-policy-sharing-team-setup-rows",children:r.candidates.map((i,o)=>{const s=`${o+1} of ${r.candidates.length}`,c=`${Vt(i.deviceCount,"device")}, ${Vt(i.projectCount,"Project")}`,l=r.candidates.length>1?`Review and migrate ${r.displayName} ${s}: ${c}`:`Review and migrate ${i.displayName}: ${c}`;return a("div",{className:"recipient-policy-sharing-team-setup-row",children:[a("span",{className:"recipient-policy-sharing-team-setup-label",children:[r.candidates.length>1?a("span",{className:"small",children:["Team ",s," · ",c]}):a(z,{children:[a("strong",{children:i.displayName}),a("span",{className:"small",children:[" · ",c]})]}),a("span",{"aria-hidden":"true",className:"recipient-policy-sharing-team-setup-separator",children:[" ","—"," "]})]}),a("span",{className:"recipient-policy-sharing-team-setup-status",children:a("span",{className:`project-status-badge ${BR(i.status)}`.trim(),children:FR(i.status)})}),a("span",{className:"recipient-policy-sharing-team-setup-action",children:t?a("button",{"aria-label":l,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t(i.candidateRef),type:"button",children:"Review and migrate"}):null})]},i.candidateRef)})})))})]})}var Tr=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Vt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function GR(e,t){return e.length?e.join(", "):t}var Pg=3;function hd({empty:e,label:t,names:n}){return n.length===0?a(z,{children:e}):n.length<=Pg?a(z,{children:GR(n,e)}):a(z,{children:[n.slice(0,Pg).join(", "),a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-name-details",children:[a("summary",{children:["View all ",Vt(n.length,t)]}),a("ul",{...fd,"aria-label":`All ${t}s`,children:n.map((r,i)=>b("li",{...md,key:`${i}-${r}`},r))})]})]})}function Rg(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var kg=3;function Tg({empty:e,identities:t,qualifier:n}){if(t.length===0)return a(z,{children:e});const r=rR(t),i=s=>s.identityCount>1?`${s.displayName} (${Vt(s.identityCount,"identity","identities")})`:s.displayName,o=r.slice(0,kg);return a(z,{children:[Vt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",o.map(i).join(", "),r.length>kg?a(z,{children:[a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-project-details",children:[a("summary",{children:["View all ",Vt(r.length,"Project name group")]}),a("ul",{...fd,"aria-label":`All ${n} Project identity groups`,children:r.map(s=>b("li",{...md,key:s.displayName},i(s)))})]})]}):null]})}function Ng({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{To({mode:"recipient-manage",recipient:r})},o=()=>{To({mode:"recipient-add",recipient:r})};return a(z,{children:[a("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Add projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||o()},type:"button",children:"Add projects"}),a("button",{"aria-describedby":e,"aria-disabled":t?"true":void 0,"aria-label":`Manage projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",onClick:()=>{t||i()},type:"button",children:"Manage projects"})]}),a("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function HR({disableMutations:e,intent:t,onTeamRenamed:n,projects:r,renameTeam:i}){const o=t.teams.filter(l=>l.status==="active"),s=new Map(t.identities.filter(l=>l.status==="active").map(l=>[l.identityId,l])),c=new Map(r.map(l=>[l.canonicalProjectIdentity,l]));return o.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:o.map((l,d)=>{const u=[...new Set(t.teamMemberships.filter(h=>h.status==="active"&&h.teamId===l.teamId&&s.has(h.identityId)).map(h=>h.identityId))],p=u.map(h=>s.get(h)?.displayName??""),f=new Set(t.identityDevices.filter(h=>h.status==="active"&&u.includes(h.identityId)).map(h=>h.deviceId)).size,m=Rg(t.projectRecipients.filter(h=>h.status==="active"&&h.recipientKind==="team"&&h.teamId===l.teamId).map(h=>h.canonicalProjectIdentity),c),v=`recipient-policy-sharing-team-title-${d}`,g=`recipient-policy-sharing-team-add-description-${d}`;return a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:l.displayName}),a("span",{className:"badge actor-badge",children:"Team"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Current members"}),a("dd",{children:[Vt(p.length,"active member")," —"," ",a(hd,{empty:"No active members",label:"member",names:p})]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:Vt(f,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared projects"}),a("dd",{children:a(Tg,{empty:"No Projects shared",identities:m,qualifier:"active shared"})})]}),a("div",{children:[a("dt",{children:"Future Team members"}),a("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),a(Ng,{descriptionId:g,disabled:e,displayName:l.displayName,recipient:{recipientKind:"team",teamId:l.teamId}}),a("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:a(MR,{descriptionId:g,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function KR({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),o=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(m=>m.status==="active"&&m.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(m=>m.status==="active"&&m.identityId===s.identityId&&i.has(m.teamId)).map(m=>m.teamId))].map(m=>i.get(m)?.displayName??""),u=Rg(t.projectRecipients.filter(m=>m.status==="active"&&m.recipientKind==="identity"&&m.identityId===s.identityId).map(m=>m.canonicalProjectIdentity),o),p=`recipient-policy-sharing-identity-title-${c}`,f=`recipient-policy-sharing-identity-add-description-${c}`;return a("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:p,children:s.displayName}),a("span",{className:"badge actor-badge local",children:"Local identity"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Verification"}),a("dd",{children:"Local identity"})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:[Vt(l.length,"active registered device")," —"," ",a(hd,{empty:"No active devices",label:"device",names:l.map(m=>m.displayName)})]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[Vt(d.length,"active Team membership")," —"," ",a(hd,{empty:"No active Team memberships",label:"Team membership",names:d})]})]}),a("div",{children:[a("dt",{children:"Directly shared projects"}),a("dd",{children:a(Tg,{empty:"No Projects shared directly",identities:u,qualifier:"directly shared active"})})]})]}),a("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),a(Ng,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function VR({received:e}){return e.length===0?a("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):a("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return a("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:r,children:t.displayName}),a("span",{className:"badge actor-badge",children:"Received"})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Memories on this device"}),a("dd",{children:Vt(t.existingMemoryCount,"memory","memories")})]}),a("div",{children:[a("dt",{children:"Latest activity"}),a("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),a("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function zR({intent:e,options:t,projects:n}){const[r,i]=x(()=>e.teams.some(m=>m.status==="active")?"teams":"identities"),o=q(t.loading===!0||t.loadError===!0),s=q([]),c=vg(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(m=>m.status==="active");K(()=>{if(o.current&&!t.loading&&!t.loadError){o.current=!1,i(u?"teams":"identities");return}u||i(m=>m==="teams"?"identities":m)},[u,t.loadError,t.loading]);const p=m=>{const v=Tr[m];v&&(i(v.id),s.current[m]?.focus())},f=(m,v)=>{let g=null;m.key==="ArrowRight"?g=(v+1)%Tr.length:m.key==="ArrowLeft"?g=(v-1+Tr.length)%Tr.length:m.key==="Home"?g=0:m.key==="End"&&(g=Tr.length-1),g!==null&&(m.preventDefault(),p(g))};return a("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("header",{className:"recipient-policy-sharing-header",children:[a("h2",{children:"Sharing"}),a("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),a(qR,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading&&!t.teamSetupSummary?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Team setup status is loading."}):null,t.teamSetupUnavailable?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?a("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?a("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),a("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),a("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review devices"}):null]}):null,d>0?a("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),a("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),a("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review devices"}):null]}):null,t.refreshError?a("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Refresh failed; showing previous Sharing details. Team and Identity Project changes are disabled until a refresh succeeds."}):null,a("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:Tr.map((m,v)=>a("button",{"aria-controls":`recipient-policy-sharing-panel-${m.id}`,"aria-selected":r===m.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===m.id?" active":""}`,id:`recipient-policy-sharing-tab-${m.id}`,onClick:()=>i(m.id),onKeyDown:g=>f(g,v),ref:g=>{s.current[v]=g},role:"tab",tabIndex:r===m.id?0:-1,type:"button",children:m.label},m.id))}),Tr.map(m=>a(z,{children:a("div",{"aria-labelledby":`recipient-policy-sharing-tab-${m.id}`,className:"recipient-policy-sharing-panel",hidden:r!==m.id,id:`recipient-policy-sharing-panel-${m.id}`,role:"tabpanel",tabIndex:0,children:t.loading?r===m.id?a(gg,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===m.id?a("p",{"aria-live":"assertive",className:"recipient-policy-sharing-state recipient-policy-sharing-error",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:m.id==="teams"?a(HR,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):m.id==="identities"?a(KR,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?a(VR,{received:t.received??[]}):a(LR,{intent:e})})},m.id))]})}function WR(e,t,n,r={}){We(a(zR,{intent:n,options:r,projects:t}),e)}var gd={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function JR(){const e=[];let t=0;for(;;){const n=await ho({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:fs(e),received:vR(e)}}var YR={loadDeviceInventory:vl,loadIntent:gl,loadProjects:JR,loadSyncStatus:Ua,loadTeamSetupSummary:nm,mountManagement:hg,mountSharing:WR};function XR(e={},t={}){const n={...YR,...e};let r=0,i=null,o=0,s,c,l=!1,d=!1,u=!1,p=!1,f=null;const m=(g={})=>{const h=v(++r,g);return i=h,h};async function v(g,h){const y=document.getElementById("recipientPolicySharingMount");if(!y){if(!h.requireTeamSetupSummary)return!0;try{return await n.loadTeamSetupSummary(),!0}catch{return!1}}const w=document.getElementById("recipientPolicyManagementMount");l=!0,d=!1;let _=()=>{const E=f;n.mountSharing(y,E?.inventory.manageable??[],E?.intent??gd,E?{coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,...u?{refreshError:!0}:{},teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d}:{loading:!0,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};_();const I=Promise.resolve().then(()=>n.loadTeamSetupSummary()).then(E=>(g!==r||(c=E,l=!1,d=!1,_()),!0),()=>(g!==r||(l=!1,d=!0,_()),!1)),[P,k,A,L]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(g!==r)return h.requireTeamSetupSummary?(await I,!1):i??!1;const F=A.status==="rejected";A.status==="fulfilled"&&(s=A.value),L.status==="fulfilled"&&(o=um(L.value));let T,M,j;const B=P.status==="fulfilled"&&k.status==="fulfilled";if(u=!B,p=F,B){const E=P.value,S=k.value;f={intent:S,inventory:E},T=E.manageable,M=S,j={coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:F,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.received},w&&n.mountManagement(w,E.manageable,S,{onCommitted:async()=>{await m()}})}else if(f){const E=f;T=E.inventory.manageable,M=E.intent,j={coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:F,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,refreshError:!0}}else T=[],M=gd,j={deviceInventoryUnavailable:F,loadError:!0};const U=()=>{n.mountSharing(y,T,M,{...j,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if(U(),_=U,!B&&w&&n.mountManagement(w,[],gd,{loadError:!0}),!h.requireTeamSetupSummary)return B;const $=await I;return g!==r?!1:B&&$}return m}var QR=Symbol.for("preact-signals");function vs(){if(kn>1)kn--;else{var e,t=!1;for((function(){var i=_s;for(_s=void 0;i!==void 0;){var o=i.S;if(o.v===i.v)for(var s=o.t;s!==void 0;s=s.x)s.i===i.i&&(s.i=o.i);i=i.o}})();xo!==void 0;){var n=xo;for(xo=void 0,bs++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Ag(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(bs=0,kn--,t)throw e}}function ZR(e){if(kn>0)return e();vd=++ek,kn++;try{return e()}finally{vs()}}var Ao,Ke=void 0;function ys(e){var t=Ke,n=Ao;Ke=void 0,Ao=void 0;try{return e()}finally{Ke=t,Ao=n}}var xo=void 0,kn=0,bs=0,ek=0,vd=0,_s=void 0,ws=0;function Eg(e){if(Ke!==void 0){var t=e.n;if(t===void 0||t.t!==Ke)return t={i:0,S:e,p:Ke.s,n:void 0,t:Ke,e:void 0,x:void 0,r:t},Ke.s!==void 0&&(Ke.s.n=t),Ke.s=t,e.n=t,32&Ke.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Ke.s,t.n=void 0,Ke.s.n=t,Ke.s=t),t}}function ut(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}ut.prototype.brand=QR,ut.prototype.h=function(){return!0},ut.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:ys(function(){var r;(r=t.W)==null||r.call(t)}))},ut.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&ys(function(){var i;(i=t.Z)==null||i.call(t)}))}},ut.prototype.subscribe=function(e){var t=this;return Do(function(){var n=t.value;ys(function(){return e(n)})},{name:"sub"})},ut.prototype.valueOf=function(){return this.value},ut.prototype.toString=function(){return this.value+""},ut.prototype.toJSON=function(){return this.value},ut.prototype.peek=function(){var e=this;return ys(function(){return e.value})},Object.defineProperty(ut.prototype,"value",{get:function(){var e=Eg(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(bs>100)throw new Error("Cycle detected");(function(n){kn!==0&&bs===0&&n.l!==vd&&(n.l=vd,_s={S:n,v:n.v,i:n.i,o:_s})})(this),this.v=e,this.i++,ws++,kn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{vs()}}}});function yd(e,t){return new ut(e,t)}function Ag(e){for(var t=e.s;t!==void 0;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function xg(e){for(var t=e.s;t!==void 0;t=t.n){var n=t.S.n;if(n!==void 0&&(t.r=n),t.S.n=t,t.i=-1,t.n===void 0){e.s=t;break}}}function Dg(e){for(var t=e.s,n=void 0;t!==void 0;){var r=t.p;t.i===-1?(t.S.U(t),r!==void 0&&(r.n=t.n),t.n!==void 0&&(t.n.p=r)):n=t,t.S.n=t.r,t.r!==void 0&&(t.r=void 0),t=r}e.s=n}function Nr(e,t){ut.call(this,void 0,t),this.x=e,this.s=void 0,this.g=ws-1,this.f=4}Nr.prototype=new ut,Nr.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===ws))return!0;if(this.g=ws,this.f|=1,this.i>0&&!Ag(this))return this.f&=-2,!0;var e=Ke;try{xg(this),Ke=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Ke=e,Dg(this),this.f&=-2,!0},Nr.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}ut.prototype.S.call(this,e)},Nr.prototype.U=function(e){if(this.t!==void 0&&(ut.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},Nr.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;e!==void 0;e=e.x)e.t.N()}},Object.defineProperty(Nr.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Eg(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function $g(e,t){return new Nr(e,t)}function Lg(e){var t=e.m;if(e.m=void 0,typeof t=="function"){kn++;var n=Ke;Ke=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,bd(e),r}finally{Ke=n,vs()}}}function bd(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Lg(e)}function tk(e){if(Ke!==this)throw new Error("Out-of-order effect");Dg(this),Ke=e,this.f&=-2,8&this.f&&bd(this),vs()}function ki(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Ao&&Ao.push(this)}ki.prototype.c=function(){var e=this.S();try{if(8&this.f||this.x===void 0)return;var t=this.x();typeof t=="function"&&(this.m=t)}finally{e()}},ki.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Lg(this),xg(this),kn++;var e=Ke;return Ke=this,tk.bind(this,e)},ki.prototype.N=function(){2&this.f||(this.f|=2,this.u=xo,xo=this)},ki.prototype.d=function(){this.f|=8,1&this.f||bd(this)},ki.prototype.dispose=function(){this.d()};function Do(e,t){var n=new ki(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var jg,_d,Ss,nk=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Og=[];Do(function(){jg=this.N})();function Ti(e,t){he[e]=t.bind(null,he[e]||function(){})}function Cs(e){if(Ss){var t=Ss;Ss=void 0,t()}Ss=e&&e.S()}function Mg(e){var t=this,n=e.data,r=ik(n);r.name="ReactiveDom",r.value=n;var i=Re(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=$g(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=$g(function(){return!Array.isArray(d.value)&&!fm(d.value)}),p=Do(function(){if(this.N=Fg,u.value){var m=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=m)}}),f=t.__$u.d;return t.__$u.d=function(){p(),f.call(this)},[u,d]},[]),o=i[0],s=i[1];return o.value?s.peek():s.value}Mg.displayName="ReactiveTextNode",Object.defineProperties(ut.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Mg},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Ti("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var i in r)if(i!=="children"){var o=r[i];o instanceof ut&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Ti("__r",function(e,t){if(e(t),t.type!==z){Cs();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Do(function(){s=this},{name:o}),s.c=i,s})((function(i){return function(){var o;nk&&((o=this.y)==null||o.call(this)),i.__$f|=1,i.setState({})}})(r),typeof t.type=="function"?t.type.displayName||t.type.name:""))),_d=r,Cs(n)}}),Ti("__e",function(e,t,n,r){Cs(),_d=void 0,e(t,n,r)}),Ti("diffed",function(e,t){Cs(),_d=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props,o=n.U;if(o)for(var s in o){var c=o[s];c===void 0||r&&s in r||(c.d(),o[s]=void 0)}if(r){o||(o={},n.U=o);for(var l in r){var d=o[l],u=r[l];d===void 0?(d=rk(n,l,u,i),o[l]=d):d.o(u,i)}}}e(t)});function rk(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=yd(n);return{o:function(s,c){o.value=s,r=c},d:Do(function(){this.N=Fg;var s=o.value.value;r[t]!==s&&(r[t]=s,i?e[t]=s:s!=null&&(s!==!1||t[4]==="-")?e.setAttribute(t,s):e.removeAttribute(t))})}}Ti("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var o=r[i];o&&o.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),Ti("__h",function(e,t,n,r){r<3&&(t.__$f|=2),e(t,n,r)}),jt.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var o=2&this.__$f;if(!(r||o||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function ik(e,t){return Re(function(){return yd(e,t)},[])}var ok=function(e){queueMicrotask(function(){queueMicrotask(e)})};function ak(){ZR(function(){for(var e;e=Og.shift();)jg.call(e)})}function Fg(){Og.push(this)===1&&(he.requestAnimationFrame||ok)(ak)}var sk=Object.defineProperty,at=(e,t)=>sk(e,"name",{value:t,configurable:!0});function $o(e){const t=e+"CollectionProvider",[n,r]=lt(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=at(g=>{const{scope:h,children:y}=g,w=q(null),_=q(new Map).current;return a(i,{scope:h,itemMap:_,collectionRef:w,children:y})},"CollectionProvider");s.displayName=t;const c=e+"CollectionSlot",l=on(c),d=J((g,h)=>{const{scope:y,children:w}=g,_=o(c,y),I=Se(h,_.collectionRef);return a(l,{ref:I,children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",f=on(u),m=J((g,h)=>{const{scope:y,children:w,..._}=g,I=q(null),P=Se(h,I),k=o(u,y);return K(()=>(k.itemMap.set(I,{ref:I,..._}),()=>{k.itemMap.delete(I)})),a(f,{[p]:"",ref:P,children:w})});m.displayName=u;function v(g){const h=o(e+"CollectionConsumer",g);return se(()=>{const y=h.collectionRef.current;if(!y)return[];const w=Array.from(y.querySelectorAll(`[${p}]`));return Array.from(h.itemMap.values()).sort((_,I)=>w.indexOf(_.ref.current)-w.indexOf(I.ref.current))},[h.collectionRef,h.itemMap])}return at(v,"useCollection"),[{Provider:s,Slot:d,ItemSlot:m},v,r]}at($o,"createCollection");var Bg=new WeakMap,wd=class yr extends Map{static{at(this,"OrderedDict")}#e;constructor(t){super(t),this.#e=[...super.keys()],Bg.set(this,!0)}set(t,n){return Bg.get(this)&&(this.has(t)?this.#e[this.#e.indexOf(t)]=t:this.#e.push(t)),super.set(t,n),this}insert(t,n,r){const i=this.has(n),o=this.#e.length,s=Sd(t);let c=s>=0?s:o+s;const l=c<0||c>=o?-1:c;if(l===this.size||i&&l===this.size-1||l===-1)return this.set(n,r),this;const d=this.size+(i?0:1);s<0&&c++;const u=[...this.#e];let p,f=!1;for(let m=c;m<d;m++)if(c===m){let v=u[m];u[m]===n&&(v=u[m+1]),i&&this.delete(n),p=this.get(v),this.set(n,r)}else{!f&&u[m-1]===n&&(f=!0);const v=u[f?m:m-1],g=p;p=this.get(v),this.delete(v),this.set(v,g)}return this}with(t,n,r){const i=new yr(this);return i.insert(t,n,r),i}before(t){const n=this.#e.indexOf(t)-1;if(!(n<0))return this.entryAt(n)}setBefore(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i,n,r)}after(t){let n=this.#e.indexOf(t);if(n=n===-1||n===this.size-1?-1:n+1,n!==-1)return this.entryAt(n)}setAfter(t,n,r){const i=this.#e.indexOf(t);return i===-1?this:this.insert(i+1,n,r)}first(){return this.entryAt(0)}last(){return this.entryAt(-1)}clear(){return this.#e=[],super.clear()}delete(t){const n=super.delete(t);return n&&this.#e.splice(this.#e.indexOf(t),1),n}deleteAt(t){const n=this.keyAt(t);return n!==void 0?this.delete(n):!1}at(t){const n=Is(this.#e,t);if(n!==void 0)return this.get(n)}entryAt(t){const n=Is(this.#e,t);if(n!==void 0)return[n,this.get(n)]}indexOf(t){return this.#e.indexOf(t)}keyAt(t){return Is(this.#e,t)}from(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.at(i)}keyFrom(t,n){const r=this.indexOf(t);if(r===-1)return;let i=r+n;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return i;r++}}findIndex(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return r;r++}return-1}filter(t,n){const r=[];let i=0;for(const o of this)Reflect.apply(t,n,[o,i,this])&&r.push(o),i++;return new yr(r)}map(t,n){const r=[];let i=0;for(const o of this)r.push([o[0],Reflect.apply(t,n,[o,i,this])]),i++;return new yr(r)}reduce(...t){const[n,r]=t;let i=0,o=r??this.at(0);for(const s of this)i===0&&t.length===1?o=s:o=Reflect.apply(n,this,[o,s,i,this]),i++;return o}reduceRight(...t){const[n,r]=t;let i=r??this.at(-1);for(let o=this.size-1;o>=0;o--){const s=this.at(o);o===this.size-1&&t.length===1?i=s:i=Reflect.apply(n,this,[i,s,o,this])}return i}toSorted(t){const n=[...this.entries()].sort(t);return new yr(n)}toReversed(){const t=new yr;for(let n=this.size-1;n>=0;n--){const r=this.keyAt(n),i=this.get(r);t.set(r,i)}return t}toSpliced(...t){const n=[...this.entries()];return n.splice(...t),new yr(n)}slice(t,n){const r=new yr;let i=this.size-1;if(t===void 0)return r;t<0&&(t=t+this.size),n!==void 0&&n>0&&(i=n-1);for(let o=t;o<=i;o++){const s=this.keyAt(o),c=this.get(s);r.set(s,c)}return r}every(t,n){let r=0;for(const i of this){if(!Reflect.apply(t,n,[i,r,this]))return!1;r++}return!0}some(t,n){let r=0;for(const i of this){if(Reflect.apply(t,n,[i,r,this]))return!0;r++}return!1}};function Is(e,t){if("at"in Array.prototype)return Array.prototype.at.call(e,t);const n=Ug(e,t);return n===-1?void 0:e[n]}at(Is,"at");function Ug(e,t){const n=e.length,r=Sd(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}at(Ug,"toSafeIndex");function Sd(e){return e!==e||e===0?0:Math.trunc(e)}at(Sd,"toSafeInteger");function ck(e){const t=e+"CollectionProvider",[n,r]=lt(t),[i,o]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new wd,setItemMap:at(()=>{},"setItemMap")}),s=at(({state:w,..._})=>w?a(l,{..._,state:w}):a(c,{..._}),"CollectionProvider");s.displayName=t;const c=at(w=>{const _=h();return a(l,{...w,state:_})},"CollectionInit");c.displayName=t+"Init";const l=at(w=>{const{scope:_,children:I,state:P}=w,k=q(null),[A,L]=x(null),F=Se(k,L),[T,M]=P;return K(()=>{if(!A)return;const j=Hg(()=>{});return j.observe(A,{childList:!0,subtree:!0}),()=>{j.disconnect()}},[A]),a(i,{scope:_,itemMap:T,setItemMap:M,collectionRef:F,collectionRefObject:k,collectionElement:A,children:I})},"CollectionProviderImpl");l.displayName=t+"Impl";const d=e+"CollectionSlot",u=on(d),p=J((w,_)=>{const{scope:I,children:P}=w,k=o(d,I),A=Se(_,k.collectionRef);return a(u,{ref:A,children:P})});p.displayName=d;const f=e+"CollectionItemSlot",m="data-radix-collection-item",v=on(f),g=J((w,_)=>{const{scope:I,children:P,...k}=w,A=q(null),[L,F]=x(null),T=Se(_,A,F),{setItemMap:M}=o(f,I),j=q(k);qg(j.current,k)||(j.current=k);const B=j.current;return K(()=>{const U=B;return M($=>L?$.has(L)?$.set(L,{...U,element:L}).toSorted(Cd):($.set(L,{...U,element:L}),$.toSorted(Cd)):$),()=>{M($=>!L||!$.has(L)?$:($.delete(L),new wd($)))}},[L,B,M]),a(v,{[m]:"",ref:T,children:P})});g.displayName=f;function h(){return x(new wd)}at(h,"useInitCollection");function y(w){const{itemMap:_}=o(e+"CollectionConsumer",w);return _}return at(y,"useCollection"),[{Provider:s,Slot:p,ItemSlot:g},{createCollectionScope:r,useCollection:y,useInitCollection:h}]}at(ck,"createCollection");function qg(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e==null||t==null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!Object.prototype.hasOwnProperty.call(t,i)||e[i]!==t[i])return!1;return!0}at(qg,"shallowEqual");function Gg(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}at(Gg,"isElementPreceding");function Cd(e,t){return!e[1].element||!t[1].element?0:Gg(e[1].element,t[1].element)?-1:1}at(Cd,"sortByDocumentPosition");function Hg(e){return new MutationObserver(t=>{for(const n of t)if(n.type==="childList"){e();return}})}at(Hg,"getChildListObserver");var lk=Object.defineProperty,dk=(e,t)=>lk(e,"name",{value:t,configurable:!0}),Kg=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Id=J(dk(function(t,n){return a(ve.span,{...t,ref:n,style:{...Kg,...t.style}})},"VisuallyHidden")),uk=Id,pk=Object.defineProperty,qe=(e,t)=>pk(e,"name",{value:t,configurable:!0}),Vg="ToastProvider",[Pd,zg,fk]=$o("Toast"),[Wg,wU]=lt("Toast",[fk]),[mk,Ps]=Wg(Vg),hk=qe(e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:o=50,announcerContainer:s,children:c}=e,[l,d]=x(null),[u,p]=x(0),f=q(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Vg}\`. Expected non-empty \`string\`.`),a(Pd.Provider,{scope:t,children:a(mk,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:o,toastCount:u,viewport:l,onViewportChange:d,onToastAdd:se(()=>p(m=>m+1),[]),onToastRemove:se(()=>p(m=>m-1),[]),isClosePausedRef:f,announcerContainer:s,children:c})})},"ToastProvider"),gk="ToastViewport",vk=["F8"],Rd="toast.viewportPause",kd="toast.viewportResume",yk=J(qe(function(t,n){const{__scopeToast:r,hotkey:i=vk,label:o="Notifications ({hotkey})",...s}=t,c=Ps(gk,r),l=zg(r),d=q(null),u=q(null),p=q(null),f=q(null),m=Se(n,f,c.onViewportChange),v=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=c.toastCount>0;K(()=>{const y=qe(w=>{i.length!==0&&i.every(_=>w[_]||w.code===_)&&f.current?.focus()},"handleKeyDown");return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),K(()=>{const y=d.current,w=f.current;if(g&&y&&w){const _=qe(()=>{if(!c.isClosePausedRef.current){const A=new CustomEvent(Rd);w.dispatchEvent(A),c.isClosePausedRef.current=!0}},"handlePause"),I=qe(()=>{if(c.isClosePausedRef.current){const A=new CustomEvent(kd);w.dispatchEvent(A),c.isClosePausedRef.current=!1}},"handleResume"),P=qe(A=>{y.contains(A.relatedTarget)||I()},"handleFocusOutResume"),k=qe(()=>{y.contains(document.activeElement)||I()},"handlePointerLeaveResume");return y.addEventListener("focusin",_),y.addEventListener("focusout",P),y.addEventListener("pointermove",_),y.addEventListener("pointerleave",k),window.addEventListener("blur",_),window.addEventListener("focus",I),()=>{y.removeEventListener("focusin",_),y.removeEventListener("focusout",P),y.removeEventListener("pointermove",_),y.removeEventListener("pointerleave",k),window.removeEventListener("blur",_),window.removeEventListener("focus",I)}}},[g,c.isClosePausedRef]);const h=se(({tabbingDirection:y})=>{const w=l().map(_=>{const I=_.ref.current,P=[I,...Zg(I)];return y==="forwards"?P:P.reverse()});return(y==="forwards"?w.reverse():w).flat()},[l]);return K(()=>{const y=f.current;if(y){const w=qe(_=>{const I=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!I){const P=document.activeElement,k=_.shiftKey;if(_.target===y&&k){u.current?.focus();return}const A=h({tabbingDirection:k?"backwards":"forwards"}),L=A.findIndex(F=>F===P);ks(A.slice(L+1))?_.preventDefault():k?u.current?.focus():p.current?.focus()}},"handleKeyDown");return y.addEventListener("keydown",w),()=>y.removeEventListener("keydown",w)}},[l,h]),a(YI,{ref:d,role:"region","aria-label":o.replace("{hotkey}",v),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Jg,{ref:u,onFocusFromOutsideViewport:()=>{ks(h({tabbingDirection:"forwards"}))}}),a(Pd.Slot,{scope:r,children:a(ve.ol,{tabIndex:-1,...s,ref:m})}),g&&a(Jg,{ref:p,onFocusFromOutsideViewport:()=>{ks(h({tabbingDirection:"backwards"}))}})]})},"ToastViewport")),bk="ToastFocusProxy",Jg=J(qe(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:i,...o}=t,s=Ps(bk,r);return a(Id,{tabIndex:0,...o,ref:n,style:{position:"fixed"},onFocus:c=>{const l=c.relatedTarget;s.viewport?.contains(l)||i()}})},"ToastFocusProxy")),Rs="Toast",_k="toast.swipeStart",wk="toast.swipeMove",Sk="toast.swipeCancel",Ck="toast.swipeEnd",Ik=J(qe(function(t,n){const{forceMount:r,open:i,defaultOpen:o,onOpenChange:s,...c}=t,[l,d]=Et({prop:i,defaultProp:o??!0,onChange:s,caller:Rs});return a(Pt,{present:r||l,children:a(kk,{open:l,...c,ref:n,onClose:()=>d(!1),onPause:mt(t.onPause),onResume:mt(t.onResume),onSwipeStart:ne(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ne(t.onSwipeMove,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${f}px`)}),onSwipeCancel:ne(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ne(t.onSwipeEnd,u=>{const{x:p,y:f}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${f}px`),d(!1)})})})},"Toast")),[Pk,Rk]=Wg(Rs,{onClose(){}}),kk=J(qe(function(t,n){const{__scopeToast:r,type:i="foreground",duration:o,open:s,onClose:c,onEscapeKeyDown:l,onPause:d,onResume:u,onSwipeStart:p,onSwipeMove:f,onSwipeCancel:m,onSwipeEnd:v,...g}=t,h=Ps(Rs,r),y=zg(r),[w,_]=x(null),I=Se(n,_),P=q(null),k=q(null),A=o||h.duration,L=q(0),F=q(A),T=q(0),{onToastAdd:M,onToastRemove:j}=h,B=mt(()=>{w?.contains(document.activeElement)&&h.viewport?.focus(),c()}),U=se(E=>{!E||E===1/0||(window.clearTimeout(T.current),L.current=new Date().getTime(),T.current=window.setTimeout(B,E))},[B]);K(()=>{const E=h.viewport;if(E){const S=qe(()=>{U(F.current),u?.()},"handleResume"),D=qe(()=>{const H=new Date().getTime()-L.current;F.current=F.current-H,window.clearTimeout(T.current),d?.()},"handlePause");return E.addEventListener(Rd,D),E.addEventListener(kd,S),()=>{E.removeEventListener(Rd,D),E.removeEventListener(kd,S)}}},[h.viewport,A,d,u,U]),K(()=>{s&&!h.isClosePausedRef.current&&U(A)},[s,A,h.isClosePausedRef,U]),K(()=>()=>{window.clearTimeout(T.current)},[]),K(()=>(M(),()=>j()),[M,j]);const $=Re(()=>w?Td(w):null,[w]);return h.viewport?a(z,{children:[$&&a(Tk,{__scopeToast:r,role:"status","aria-live":i==="foreground"?"assertive":"polite",children:$}),a(Pk,{scope:r,onClose:B,children:rn(a(Pd.ItemSlot,{scope:r,children:a(JI,{asChild:!0,onEscapeKeyDown:ne(l,E=>{y().some(S=>S.ref.current?.contains(E.target))||B()}),children:a(ve.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":h.swipeDirection,...g,ref:I,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:ne(t.onKeyDown,E=>{E.key==="Escape"&&(l?.(E.nativeEvent),E.nativeEvent.defaultPrevented||B())}),onPointerDown:ne(t.onPointerDown,E=>{E.button===0&&(P.current={x:E.clientX,y:E.clientY})}),onPointerMove:ne(t.onPointerMove,E=>{if(!P.current)return;const S=E.clientX-P.current.x,D=E.clientY-P.current.y,H=!!k.current,G=["left","right"].includes(h.swipeDirection),oe=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,ae=G?oe(0,S):0,ee=G?0:oe(0,D),ie=E.pointerType==="touch"?10:2,Ce={x:ae,y:ee},Ie={originalEvent:E,delta:Ce};H?(k.current=Ce,Lo(wk,f,Ie,{discrete:!1})):Yg(Ce,h.swipeDirection,ie)?(k.current=Ce,Lo(_k,p,Ie,{discrete:!1}),E.target.setPointerCapture(E.pointerId)):(Math.abs(S)>ie||Math.abs(D)>ie)&&(P.current=null)}),onPointerUp:ne(t.onPointerUp,E=>{const S=k.current,D=E.target;if(D.hasPointerCapture(E.pointerId)&&D.releasePointerCapture(E.pointerId),k.current=null,P.current=null,S){const H=E.currentTarget,G={originalEvent:E,delta:S};Yg(S,h.swipeDirection,h.swipeThreshold)?Lo(Ck,v,G,{discrete:!0}):Lo(Sk,m,G,{discrete:!0}),H.addEventListener("click",oe=>oe.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null},"ToastImpl")),Tk=qe(e=>{const{__scopeToast:t,children:n,...r}=e,i=Ps(Rs,t),[o,s]=x(!1),[c,l]=x(!1);return Xg(()=>s(!0)),K(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(gi,{asChild:!0,container:i.announcerContainer||void 0,children:a(Id,{...r,children:o&&a(z,{children:[i.label," ",n]})})})},"ToastAnnounce"),Nk=J(qe(function(t,n){const{__scopeToast:r,...i}=t;return a(ve.div,{...i,ref:n})},"ToastDescription")),Ek="ToastClose",Ak=J(qe(function(t,n){const{__scopeToast:r,...i}=t,o=Rk(Ek,r);return a(xk,{asChild:!0,children:a(ve.button,{type:"button",...i,ref:n,onClick:ne(t.onClick,o.onClose)})})},"ToastClose")),xk=J(qe(function(t,n){const{__scopeToast:r,altText:i,...o}=t;return a(ve.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":i||void 0,...o,ref:n})},"ToastAnnounceExclude"));function Td(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),Qg(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const o=n.dataset.radixToastAnnounceAlt;o&&t.push(o)}else t.push(...Td(n))}}),t}qe(Td,"getAnnounceTextContent");function Lo(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,o=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?es(i,o):i.dispatchEvent(o)}qe(Lo,"handleAndDispatchCustomEvent");var Yg=qe((e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),o=r>i;return t==="left"||t==="right"?o&&r>n:!o&&i>n},"isDeltaInDirection");function Xg(e=()=>{}){const t=mt(e);Xe(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}qe(Xg,"useNextFrame");function Qg(e){return e.nodeType===e.ELEMENT_NODE}qe(Qg,"isHTMLElement");function Zg(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:qe(r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}qe(Zg,"getTabbableCandidates");function ks(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}qe(ks,"focusFirst");var Dk=hk,$k=yk,Lk=Ik,jk=Nk,Ok=Ak,jo=yd([]),Mk=1;function Fk(e,t="success",n=8e3){if(!e)return;const r=Mk++;jo.value=[...jo.value,{id:r,message:e,variant:t,durationMs:n}]}function Bk(e){jo.value=jo.value.filter(t=>t.id!==e)}function Uk(){const e=jo.value;return a(Dk,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(Lk,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||Bk(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(jk,{className:"toast-message",children:t.message}),a(Ok,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a($k,{className:"toast-viewport"})]})}function qk(e){We(a(Uk,{}),e)}function Ts(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Le(e){return document.getElementById(e)}function Nd(e){return document.getElementById(e)}function Ed(e){return document.getElementById(e)}function ev(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Gk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hk(e,t){const n=t.trim();if(!n)return ev(e);const r=ev(e);try{const i=new RegExp(`(${Gk(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Oo(e,t){const n=t.textContent;try{await navigator.clipboard.writeText(e),t.textContent="Copied"}catch{t.textContent="Copy failed"}setTimeout(()=>{t.textContent=n||"Copy"},1200)}var Kk=new Set(["BUTTON","A","SELECT"]),Vk=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function zk(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function Wk(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function Jk(e){return e?Kk.has(e.tagName)?!0:e instanceof HTMLInputElement&&Vk.has(e.type):!1}function Yk(e){return e.metaKey||e.ctrlKey}function Ni(e,t){if(t.disabled||e.defaultPrevented||e.isComposing||e.key!=="Enter"&&e.key!=="Escape")return;const n=e.target instanceof HTMLElement?e.target:null;if(!zk(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}Jk(n)||Wk(n)&&!Yk(e)||(e.preventDefault(),t.onSubmit())}}var Er=["feed","projects","sharing","devices","health","advanced"],tv=["sync","coordinator-admin"],Ad="codemem-tab",nv="codemem-advanced-section",rv="codemem-feed-filter",iv="codemem-feed-scope",Xk="codemem-sync-diagnostics",ov="codemem-sync-pairing",av="codemem-sync-redact",sv=["all","observations","summaries"],cv=["all","mine","theirs"],C={activeTab:"feed",advancedSection:"sync",currentProject:"",refreshState:"idle",refreshInFlight:!1,refreshQueued:!1,refreshTimer:null,feedTypeFilter:"all",feedScopeFilter:"all",feedQuery:"",lastFeedItems:[],lastFeedFilteredCount:0,lastFeedSignature:"",pendingFeedItems:null,itemViewState:new Map,itemExpandState:new Map,newItemKeys:new Set,lastStatsPayload:null,lastUsagePayload:null,lastRawEventsPayload:null,lastUpdateStatus:null,lastSyncStatus:null,lastDeviceIdentityInventory:null,deviceIdentityInventoryLoadError:!1,pendingDeviceIdentityFocus:void 0,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastSyncCoordinatorAdminStatus:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastProjectCoordinatorAdminGroups:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,pendingCoordinatorApprovalsByDeviceId:new Map,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function Qk(e){return[...Er]}function Mo(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Er.includes(e)?e:"feed"}function xd(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return tv.includes(t)?"advanced":Er.includes(t)?t:null}function Dd(e=window.location.hash){const[t,n]=e.replace(/^#/,"").split("/");return t==="sync"?"sync":t==="coordinator-admin"?"teams":t!=="advanced"?null:n==="teams"?"teams":"sync"}function Zk(){const e=xd();if(e)return Mo(e,C.lastCoordinatorAdminStatus);const t=localStorage.getItem(Ad);return t&&(Er.includes(t)||tv.includes(t))?Mo(t,C.lastCoordinatorAdminStatus):"feed"}function eT(){const e=Dd();if(e)return e;const t=localStorage.getItem(Ad);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(nv)==="teams"?"teams":"sync"}function $d(e,t=!1){C.advancedSection=e,localStorage.setItem(nv,e),t&&(window.location.hash=`advanced/${e}`)}function lv(e,t={}){const n=Mo(e,C.lastCoordinatorAdminStatus);C.activeTab=n,localStorage.setItem(Ad,n);const r=xd();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${C.advancedSection}`:n)}function tT(){const e=localStorage.getItem(rv)||"all";return sv.includes(e)?e:"all"}function nT(){const e=localStorage.getItem(iv)||"all";return cv.includes(e)?e:"all"}function rT(e){C.feedTypeFilter=sv.includes(e)?e:"all",localStorage.setItem(rv,C.feedTypeFilter)}function dv(e){C.feedScopeFilter=cv.includes(e)?e:"all",localStorage.setItem(iv,C.feedScopeFilter)}function iT(){return localStorage.getItem(Xk)==="1"}function oT(e){C.syncPairingOpen=e;try{localStorage.setItem(ov,e?"1":"0")}catch{}}function Fo(){return localStorage.getItem(av)!=="0"}function aT(e){localStorage.setItem(av,e?"1":"0")}function sT(){C.activeTab=Zk(),C.advancedSection=eT(),C.feedTypeFilter=tT(),C.feedScopeFilter=nT(),C.syncDiagnosticsOpen=iT();try{C.syncPairingOpen=localStorage.getItem(ov)==="1"}catch{C.syncPairingOpen=!1}}var Ld=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],uv="codemem-theme";function pv(e){const t=Ld.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return Ld.find(r=>r.id===n)||Ld[0]}function jd(){const e=localStorage.getItem(uv);return e?pv(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function fv(e){const t=pv(e);document.documentElement.setAttribute("data-theme",t.mode),document.documentElement.setAttribute("data-color-mode",t.mode),t.id===t.mode?document.documentElement.removeAttribute("data-theme-variant"):document.documentElement.setAttribute("data-theme-variant",t.id),localStorage.setItem(uv,t.id)}function cT(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const o=document.createElement("i");o.setAttribute("data-lucide",r),o.setAttribute("aria-hidden","true"),e.appendChild(o),globalThis.lucide?.createIcons?.()};t(jd()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=jd()==="dark"?"light":"dark";fv(n),t(n)})}var lT=Object.defineProperty,dT=(e,t)=>lT(e,"name",{value:t,configurable:!0}),uT=wr(void 0);function Ei(e){const t=Cn(uT);return e||t||"ltr"}dT(Ei,"useDirection");var pT=Object.defineProperty,Od=(e,t)=>pT(e,"name",{value:t,configurable:!0}),Md=!1;function mv(){const[e,t]=x(Md);return K(()=>{Md||(Md=!0,t(!0))},[]),e}Od(mv,"useIsHydrated");var hv=pi[" useSyncExternalStore ".trim().toString()];function gv(){return()=>{}}Od(gv,"subscribe");function vv(){return hv(gv,()=>!0,()=>!1)}Od(vv,"useIsHydratedModern");var fT=typeof hv=="function"?vv:mv,mT=Object.defineProperty,Ar=(e,t)=>mT(e,"name",{value:t,configurable:!0}),Fd="rovingFocusGroup.onEntryFocus",hT={bubbles:!1,cancelable:!0},Ns="RovingFocusGroup",[Bd,yv,gT]=$o(Ns),[vT,Ai]=lt(Ns,[gT]),[yT,bT]=vT(Ns),_T=J(Ar(function(t,n){return a(Bd.Provider,{scope:t.__scopeRovingFocusGroup,children:a(Bd.Slot,{scope:t.__scopeRovingFocusGroup,children:a(wT,{...t,ref:n})})})},"RovingFocusGroup")),wT=J(Ar(function(t,n){const{__scopeRovingFocusGroup:r,orientation:i,loop:o=!1,dir:s,currentTabStopId:c,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:p=!1,...f}=t,m=q(null),v=Se(n,m),g=Ei(s),[h,y]=Et({prop:c,defaultProp:l??null,onChange:d,caller:Ns}),[w,_]=x(!1),I=mt(u),P=yv(r),k=q(!1),[A,L]=x(0);return K(()=>{const F=m.current;if(F)return F.addEventListener(Fd,I),()=>F.removeEventListener(Fd,I)},[I]),a(yT,{scope:r,orientation:i,dir:g,loop:o,currentTabStopId:h,onItemFocus:se(F=>y(F),[y]),onItemShiftTab:se(()=>_(!0),[]),onFocusableItemAdd:se(()=>L(F=>F+1),[]),onFocusableItemRemove:se(()=>L(F=>F-1),[]),children:a(ve.div,{tabIndex:w||A===0?-1:0,"data-orientation":i,...f,ref:v,style:{outline:"none",...t.style},onMouseDown:ne(t.onMouseDown,()=>{k.current=!0}),onFocus:ne(t.onFocus,F=>{const T=!k.current;if(F.target===F.currentTarget&&T&&!w){const M=new CustomEvent(Fd,hT);if(F.currentTarget.dispatchEvent(M),!M.defaultPrevented){const j=P().filter(B=>B.focusable);Ud([j.find(B=>B.active),j.find(B=>B.id===h),...j].filter(Boolean).map(B=>B.ref.current),p)}}k.current=!1}),onBlur:ne(t.onBlur,()=>_(!1))})})},"RovingFocusGroupImpl")),ST="RovingFocusGroupItem",CT=J(Ar(function(t,n){const{__scopeRovingFocusGroup:r,focusable:i=!0,active:o=!1,tabStopId:s,children:c,...l}=t,d=Nt(),u=s||d,p=bT(ST,r),f=p.currentTabStopId===u,m=yv(r),{onFocusableItemAdd:v,onFocusableItemRemove:g,currentTabStopId:h}=p,y=fT();return Xe(()=>{if(!(!y||!i))return v(),()=>g()},[y,i,v,g]),K(()=>{if(!(y||!i))return v(),()=>g()},[y,i,v,g]),a(Bd.ItemSlot,{scope:r,id:u,focusable:i,active:o,children:a(ve.span,{tabIndex:f?0:-1,"data-orientation":p.orientation,...l,ref:n,onMouseDown:ne(t.onMouseDown,w=>{i?p.onItemFocus(u):w.preventDefault()}),onFocus:ne(t.onFocus,()=>p.onItemFocus(u)),onKeyDown:ne(t.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){p.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const _=_v(w,p.orientation,p.dir);if(_!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let I=m().filter(P=>P.focusable).map(P=>P.ref.current);if(_==="last")I.reverse();else if(_==="prev"||_==="next"){_==="prev"&&I.reverse();const P=I.indexOf(w.currentTarget);I=p.loop?wv(I,P+1):I.slice(P+1)}setTimeout(()=>Ud(I))}}),children:typeof c=="function"?c({isCurrentTabStop:f,hasTabStop:h!=null}):c})})},"RovingFocusGroupItem")),IT={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Ar(bv,"getDirectionAwareKey");function _v(e,t,n){const r=bv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return IT[r]}Ar(_v,"getFocusIntent");function Ud(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Ar(Ud,"focusFirst");function wv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Ar(wv,"wrapArray");var qd=_T,Gd=CT,PT=Object.defineProperty,xi=(e,t)=>PT(e,"name",{value:t,configurable:!0}),Hd="Tabs",[RT,SU]=lt(Hd,[Ai]),Sv=Ai(),[kT,Kd]=RT(Hd),TT=J(xi(function(t,n){const{__scopeTabs:r,value:i,onValueChange:o,defaultValue:s,orientation:c="horizontal",dir:l,activationMode:d="automatic",...u}=t,p=Ei(l),[f,m]=Et({prop:i,onChange:o,defaultProp:s??"",caller:Hd});return a(kT,{scope:r,baseId:Nt(),value:f,onValueChange:m,orientation:c,dir:p,activationMode:d,children:a(ve.div,{dir:p,"data-orientation":c,...u,ref:n})})},"Tabs")),NT="TabsList",ET=J(xi(function(t,n){const{__scopeTabs:r,loop:i=!0,...o}=t,s=Kd(NT,r),c=Sv(r);return a(qd,{asChild:!0,...c,orientation:s.orientation,dir:s.dir,loop:i,children:a(ve.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:n})})},"TabsList")),AT="TabsTrigger",xT=J(xi(function(t,n){const{__scopeTabs:r,value:i,disabled:o=!1,...s}=t,c=Kd(AT,r),l=Sv(r),d=Vd(c.baseId,i),u=zd(c.baseId,i),p=i===c.value;return a(Gd,{asChild:!0,...l,focusable:!o,active:p,children:a(ve.button,{type:"button",role:"tab","aria-selected":p,"aria-controls":u,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:d,...s,ref:n,onMouseDown:ne(t.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?c.onValueChange(i):f.preventDefault()}),onKeyDown:ne(t.onKeyDown,f=>{o||f.target!==f.currentTarget||[" ","Enter"].includes(f.key)&&c.onValueChange(i)}),onFocus:ne(t.onFocus,()=>{const f=c.activationMode!=="manual";!p&&!o&&f&&c.onValueChange(i)})})})},"TabsTrigger")),DT="TabsContent",$T=J(xi(function(t,n){const{__scopeTabs:r,value:i,forceMount:o,children:s,...c}=t,l=Kd(DT,r),d=Vd(l.baseId,i),u=zd(l.baseId,i),p=i===l.value,f=q(p);return K(()=>{const m=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(m)},[]),a(Pt,{present:o||p,children:({present:m})=>a(ve.div,{"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":d,hidden:!m,id:u,tabIndex:0,...c,ref:n,style:{...t.style,animationDuration:f.current?"0s":void 0},children:m&&s})})},"TabsContent"));function Vd(e,t){return`${e}-trigger-${t}`}xi(Vd,"makeTriggerId");function zd(e,t){return`${e}-content-${t}`}xi(zd,"makeContentId");var LT=TT,jT=ET,OT=xT,MT=$T;function Cv({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(LT,{onValueChange:r,value:s,children:[a(jT,{"aria-label":e,className:n,children:i.map(c=>a(OT,{className:o,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function xr({children:e,className:t,forceMount:n=!1,value:r}){return a(MT,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function ke(e){return a("input",{...e})}function Es(){return{aliases:new Map,duplicateDisplayNames:new Map,reservedDisplayNames:new Set}}function Iv(e,t=Es()){for(const o of e){const s=String(o.display_name||"").trim();s&&t.reservedDisplayNames.add(s)}for(const[o,s]of t.aliases)t.reservedDisplayNames.has(s)&&t.aliases.delete(o);const n=new Set([...t.reservedDisplayNames,...t.aliases.values()]),r=e.filter(o=>!String(o.display_name||"").trim()).map(o=>String(o.device_id||"").trim()).filter(Boolean).sort((o,s)=>o.localeCompare(s));let i=Math.max(0,...[...t.aliases.values()].map(o=>{const s=/^Unnamed device (\d+)$/.exec(o);return s?Number(s[1]):0}));for(const o of r){if(t.aliases.has(o))continue;let s;do i+=1,s=`Unnamed device ${i}`;while(n.has(s));t.aliases.set(o,s),n.add(s)}return t.aliases}function As(e,t=Es()){const n=Iv(e,t),r=new Map,i=new Map,o=new Map,s=new Set;for(const l of e){const d=String(l.device_id||"").trim(),u=String(l.display_name||"").trim();if(!d)continue;if(!u){r.set(d,n.get(d)||"Unnamed device");continue}o.set(d,u),s.add(u);const p=i.get(u)??[];p.push(d),i.set(u,p)}for(const[l,d]of t.duplicateDisplayNames){const u=o.get(l);(u&&u!==d.sourceName||s.has(d.displayName))&&t.duplicateDisplayNames.delete(l)}const c=new Set([...s,...[...t.duplicateDisplayNames.values()].map(l=>l.displayName)]);for(const[l,d]of i)for(const u of d.sort((p,f)=>p.localeCompare(f))){const p=t.duplicateDisplayNames.get(u);if(p?.sourceName===l){r.set(u,p.displayName);continue}if(d.length===1){r.set(u,l);continue}let f=0,m;do f+=1,m=`${l} · Device ${f}`;while(c.has(m));r.set(u,m),t.duplicateDisplayNames.set(u,{displayName:m,sourceName:l}),c.add(m)}return r}function FT(e,t,n=""){const r=String(e.device_id||"").trim(),i=String(e.group_id||t||"").trim(),o=n||String(e.display_name||"").trim()||"Unnamed device",s=e.enabled!==!1&&e.enabled!==0,c=[`Device ID ${r||"unknown"}`];return i&&c.push(`Group ID ${i}`),{advancedDetail:`Advanced: ${c.join(" · ")}`,deviceId:r,displayName:o,statusLabel:s?"Enabled in this coordinator group":"Disabled in this coordinator group",teamId:i}}var Pv={status:"coordinator status",groups:"coordinator groups",joinRequests:"join requests",devices:"devices"};function xs(){return{availability:"unknown",retrying:!1}}function BT(){return{status:xs(),groups:xs(),joinRequests:xs(),devices:xs()}}function Bo(e,t){e[t]={...e[t],retrying:!0}}function Wd(e,t){e[t]={...e[t],retrying:!1}}function Ds(e,t){e[t]={availability:"fresh",retrying:!1}}function cn(e,t,n){e[t]={availability:n??(e[t].availability==="fresh"||e[t].availability==="stale")?"stale":"unavailable",retrying:!1}}function Jd(e,t){e[t]={availability:"not_applicable",retrying:!1}}function Dr(e,t){return e[t].availability==="fresh"||e[t].availability==="stale"}function Tn(e,...t){return t.every(n=>e[n].availability==="fresh"&&!e[n].retrying)}function Di(e,t){return e[t].availability==="not_applicable"}function Rv(e){const t=Object.entries(e),n=t.filter(([,i])=>i.availability==="stale").map(([i])=>Pv[i]),r=t.filter(([,i])=>i.availability==="unavailable").map(([i])=>Pv[i]);return n.length===0&&r.length===0?null:{stale:n,unavailable:r,retrying:t.some(([,i])=>i.retrying)}}var UT="codemem-coordinator-admin-target-group",N={recovery:BT(),loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",joinRequestsSnapshotTarget:null,devicesSnapshotTarget:null,groupRenameDrafts:new Map,groupPresentationAliases:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,unnamedDeviceAliases:Es(),groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function kv(){return N.loadGeneration+=1,N.loadGeneration}function Yd(e){return N.loadGeneration===e}function qT(e){const{summary:t,fresh:n,runDevice:r,snapshotMatchesTarget:i}=e,o=i&&Dr(N.recovery,"devices"),s=Di(N.recovery,"devices"),c=o&&Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices:[],l=As(c,N.unnamedDeviceAliases);return b(xr,{className:"coordinator-admin-panel",value:"devices"},b("h3",null,"Enrolled devices"),b("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove devices from the selected coordinator group. Space transport access is managed below; policy Team membership and Project access stay in Sharing.":"Finish coordinator setup first. Device administration stays disabled until legacy administration is ready."),s?b("div",{class:"peer-meta"},"Complete legacy coordinator setup to load enrolled devices. No device data is expected yet."):o?c.length?b("div",{class:"peer-list"},c.map(d=>{const u=FT(d,String(C.lastCoordinatorAdminStatus?.active_group||""),l.get(String(d.device_id||"").trim())),{deviceId:p,displayName:f,teamId:m}=u,v=N.deviceActionPendingId===p,g=N.deviceRenameDrafts.get(p)??String(d.display_name||""),h=d.enabled!==!1&&d.enabled!==0,y=!n||!p||v;return b("div",{class:"peer-card peer-card--padded",key:p||String(d.fingerprint||"unknown")},b("div",{class:"peer-title"},b("strong",null,f)),b("div",{class:"peer-submeta"},u.statusLabel),b("details",{class:"coordinator-admin-diagnostics"},b("summary",null,"Diagnostics"),b("div",{class:"peer-meta"},u.advancedDetail)),b("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!y&&r(p,m,f,"rename")}},b("div",{class:"coordinator-admin-form-grid"},b("label",{class:"coordinator-admin-field"},b("span",null,"Display name"),b(ke,{class:"peer-scope-input",disabled:!n||v,onInput:w=>{N.deviceRenameDrafts.set(p,String(w.currentTarget.value||""))},type:"text",value:g}))),b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:y,type:"submit"},v&&N.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),h?b("button",{class:"settings-button danger",disabled:y,onClick:()=>r(p,m,f,"disable"),type:"button"},v&&N.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):b("button",{class:"settings-button",disabled:y,onClick:()=>r(p,m,f,"enable"),type:"button"},v&&N.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),b("button",{class:"settings-button danger",disabled:y,onClick:()=>r(p,m,f,"remove"),type:"button"},v&&N.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):b("div",{class:"peer-meta"},t.readiness==="ready"?"No enrolled devices found for the active coordinator group.":"Device administration will appear here once setup is complete."):b("div",{class:"peer-meta"},"Enrolled devices are unavailable. Retry to load current devices; no empty result is being assumed."))}var GT=Object.defineProperty,Uo=(e,t)=>GT(e,"name",{value:t,configurable:!0}),Xd="Collapsible",[HT,CU]=lt(Xd),[KT,Qd]=HT(Xd),VT=J(Uo(function(t,n){const{__scopeCollapsible:r,open:i,defaultOpen:o,disabled:s,onOpenChange:c,...l}=t,[d,u]=Et({prop:i,defaultProp:o??!1,onChange:c,caller:Xd});return a(KT,{scope:r,disabled:s,contentId:Nt(),open:d,onOpenToggle:se(()=>u(p=>!p),[u]),children:a(ve.div,{"data-state":$s(d),"data-disabled":s?"":void 0,...l,ref:n})})},"Collapsible")),zT="CollapsibleTrigger",WT=J(Uo(function(t,n){const{__scopeCollapsible:r,...i}=t,o=Qd(zT,r);return a(ve.button,{type:"button","aria-controls":o.open?o.contentId:void 0,"aria-expanded":o.open||!1,"data-state":$s(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...i,ref:n,onClick:ne(t.onClick,o.onOpenToggle)})},"CollapsibleTrigger")),Tv="CollapsibleContent",JT=J(Uo(function(t,n){const{forceMount:r,...i}=t,o=Qd(Tv,t.__scopeCollapsible);return a(Pt,{present:r||o.open,children:({present:s})=>a(YT,{...i,ref:n,present:s})})},"CollapsibleContent")),YT=J(Uo(function(t,n){const{__scopeCollapsible:r,present:i,children:o,...s}=t,c=Qd(Tv,r),[l,d]=x(i),u=q(null),p=Se(n,u),f=q(0),m=f.current,v=q(0),g=v.current,h=c.open||l,y=q(h),w=q(void 0);return K(()=>{const _=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(_)},[]),Xe(()=>{const _=u.current;if(_){w.current=w.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const I=_.getBoundingClientRect();f.current=I.height,v.current=I.width,y.current||(_.style.transitionDuration=w.current.transitionDuration,_.style.animationName=w.current.animationName),d(i)}},[c.open,i]),a(ve.div,{"data-state":$s(c.open),"data-disabled":c.disabled?"":void 0,id:c.contentId,hidden:!h,...s,ref:p,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...t.style},children:h&&o})},"CollapsibleContentImpl"));function $s(e){return e?"open":"closed"}Uo($s,"getState");var qo=VT,Zd=WT,Go=JT,XT=["top","right","bottom","left"],Jn=Math.min,At=Math.max,Ls=Math.round,js=Math.floor,ln=e=>({x:e,y:e}),QT={left:"right",right:"left",bottom:"top",top:"bottom"};function eu(e,t,n){return At(e,Jn(t,n))}function Nn(e,t){return typeof e=="function"?e(t):e}function En(e){return e.split("-")[0]}function $i(e){return e.split("-")[1]}function tu(e){return e==="x"?"y":"x"}function nu(e){return e==="y"?"height":"width"}function dn(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ru(e){return tu(dn(e))}function ZT(e,t,n){n===void 0&&(n=!1);const r=$i(e),i=ru(e),o=nu(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=Os(s)),[s,Os(s)]}function eN(e){const t=Os(e);return[iu(e),t,iu(t)]}function iu(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Nv=["left","right"],Ev=["right","left"],tN=["top","bottom"],nN=["bottom","top"];function rN(e,t,n){switch(e){case"top":case"bottom":return n?t?Ev:Nv:t?Nv:Ev;case"left":case"right":return t?tN:nN;default:return[]}}function iN(e,t,n,r){const i=$i(e);let o=rN(En(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(iu)))),o}function Os(e){const t=En(e);return QT[t]+e.slice(t.length)}function oN(e){return{top:0,right:0,bottom:0,left:0,...e}}function Av(e){return typeof e!="number"?oN(e):{top:e,right:e,bottom:e,left:e}}function Ms(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function xv(e,t,n){let{reference:r,floating:i}=e;const o=dn(t),s=ru(t),c=nu(s),l=En(t),d=o==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,f=r[c]/2-i[c]/2;let m;switch(l){case"top":m={x:u,y:r.y-i.height};break;case"bottom":m={x:u,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:p};break;case"left":m={x:r.x-i.width,y:p};break;default:m={x:r.x,y:r.y}}switch($i(t)){case"start":m[s]-=f*(n&&d?-1:1);break;case"end":m[s]+=f*(n&&d?-1:1)}return m}async function aN(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:o,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:f=!1,padding:m=0}=Nn(t,e),v=Av(m),g=c[f?p==="floating"?"reference":"floating":p],h=Ms(await o.getClippingRect({element:(n=await(o.isElement==null?void 0:o.isElement(g)))==null||n?g:g.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),y=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,w=await(o.getOffsetParent==null?void 0:o.getOffsetParent(c.floating)),_=await(o.isElement==null?void 0:o.isElement(w))?await(o.getScale==null?void 0:o.getScale(w))||{x:1,y:1}:{x:1,y:1},I=Ms(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:y,offsetParent:w,strategy:l}):y);return{top:(h.top-I.top+v.top)/_.y,bottom:(I.bottom-h.bottom+v.bottom)/_.y,left:(h.left-I.left+v.left)/_.x,right:(I.right-h.right+v.right)/_.x}}var sN=50,cN=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:aN},l=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:p}=xv(d,r,l),f=r,m=0;const v={};for(let g=0;g<o.length;g++){const h=o[g];if(!h)continue;const{name:y,fn:w}=h,{x:_,y:I,data:P,reset:k}=await w({x:u,y:p,initialPlacement:r,placement:f,strategy:i,middlewareData:v,rects:d,platform:c,elements:{reference:e,floating:t}});u=_??u,p=I??p,v[y]={...v[y],...P},k&&m<sN&&(m++,typeof k=="object"&&(k.placement&&(f=k.placement),k.rects&&(d=k.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):k.rects),{x:u,y:p}=xv(d,f,l)),g=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},lN=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:o,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=Nn(e,t)||{};if(d==null)return{};const p=Av(u),f={x:n,y:r},m=ru(i),v=nu(m),g=await s.getDimensions(d),h=m==="y",y=h?"top":"left",w=h?"bottom":"right",_=h?"clientHeight":"clientWidth",I=o.reference[v]+o.reference[m]-f[m]-o.floating[v],P=f[m]-o.reference[m],k=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=k?k[_]:0;(!A||!await(s.isElement==null?void 0:s.isElement(k)))&&(A=c.floating[_]||o.floating[v]);const L=I/2-P/2,F=A/2-g[v]/2-1,T=Jn(p[y],F),M=Jn(p[w],F),j=T,B=A-g[v]-M,U=A/2-g[v]/2+L,$=eu(j,U,B),E=!l.arrow&&$i(i)!=null&&U!==$&&o.reference[v]/2-(U<j?T:M)-g[v]/2<0,S=E?U<j?U-j:U-B:0;return{[m]:f[m]+S,data:{[m]:$,centerOffset:U-$-S,...E&&{alignmentOffset:S}},reset:E}}}),dN=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:o,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:g=!0,...h}=Nn(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const y=En(i),w=dn(c),_=En(c)===c,I=await(l.isRTL==null?void 0:l.isRTL(d.floating)),P=f||(_||!g?[Os(c)]:eN(c)),k=v!=="none";!f&&k&&P.push(...iN(c,g,v,I));const A=[c,...P],L=await l.detectOverflow(t,h),F=[];let T=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&F.push(L[y]),p){const U=ZT(i,s,I);F.push(L[U[0]],L[U[1]])}if(T=[...T,{placement:i,overflows:F}],!F.every(U=>U<=0)){var M,j;const U=(((M=o.flip)==null?void 0:M.index)||0)+1,$=A[U];if($&&(!(p==="alignment"&&w!==dn($))||T.every(S=>dn(S.placement)===w?S.overflows[0]>0:!0)))return{data:{index:U,overflows:T},reset:{placement:$}};let E=(j=T.filter(S=>S.overflows[0]<=0).sort((S,D)=>S.overflows[1]-D.overflows[1])[0])==null?void 0:j.placement;if(!E)switch(m){case"bestFit":{var B;const S=(B=T.filter(D=>{if(k){const H=dn(D.placement);return H===w||H==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(H=>H>0).reduce((H,G)=>H+G,0)]).sort((D,H)=>D[1]-H[1])[0])==null?void 0:B[0];S&&(E=S);break}case"initialPlacement":E=c}if(i!==E)return{reset:{placement:E}}}return{}}}};function Dv(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function $v(e){return XT.some(t=>e[t]>=0)}var uN=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=Nn(e,t);switch(i){case"referenceHidden":{const s=Dv(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:$v(s)}}}case"escaped":{const s=Dv(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:$v(s)}}}default:return{}}}}},Lv=new Set(["left","top"]);async function pN(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=En(n),c=$i(n),l=dn(n)==="y",d=Lv.has(s)?-1:1,u=o&&l?-1:1,p=Nn(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:v}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof v=="number"&&(m=c==="end"?v*-1:v),l?{x:m*u,y:f*d}:{x:f*d,y:m*u}}var fN=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:o,placement:s,middlewareData:c}=t,l=await pN(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:o+l.y,data:{...l,placement:s}}}}},mN=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:o}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:y=>{let{x:w,y:_}=y;return{x:w,y:_}}},...d}=Nn(e,t),u={x:n,y:r},p=await o.detectOverflow(t,d),f=dn(En(i)),m=tu(f);let v=u[m],g=u[f];if(s){const y=m==="y"?"top":"left",w=m==="y"?"bottom":"right",_=v+p[y],I=v-p[w];v=eu(_,v,I)}if(c){const y=f==="y"?"top":"left",w=f==="y"?"bottom":"right",_=g+p[y],I=g-p[w];g=eu(_,g,I)}const h=l.fn({...t,[m]:v,[f]:g});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[m]:s,[f]:c}}}}}},hN=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:o,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=Nn(e,t),u={x:n,y:r},p=dn(i),f=tu(p);let m=u[f],v=u[p];const g=Nn(c,t),h=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const _=f==="y"?"height":"width",I=o.reference[f]-o.floating[_]+h.mainAxis,P=o.reference[f]+o.reference[_]-h.mainAxis;m<I?m=I:m>P&&(m=P)}if(d){var y,w;const _=f==="y"?"width":"height",I=Lv.has(En(i)),P=o.reference[p]-o.floating[_]+(I&&((y=s.offset)==null?void 0:y[p])||0)+(I?0:h.crossAxis),k=o.reference[p]+o.reference[_]+(I?0:((w=s.offset)==null?void 0:w[p])||0)-(I?h.crossAxis:0);v<P?v=P:v>k&&(v=k)}return{[f]:m,[p]:v}}}},gN=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:o,platform:s,elements:c}=t,{apply:l=()=>{},...d}=Nn(e,t),u=await s.detectOverflow(t,d),p=En(i),f=$i(i),m=dn(i)==="y",{width:v,height:g}=o.floating;let h,y;p==="top"||p==="bottom"?(h=p,y=f===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(y=p,h=f==="end"?"top":"bottom");const w=g-u.top-u.bottom,_=v-u.left-u.right,I=Jn(g-u[h],w),P=Jn(v-u[y],_),k=!t.middlewareData.shift;let A=I,L=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),k&&!f){const T=At(u.left,0),M=At(u.right,0),j=At(u.top,0),B=At(u.bottom,0);m?L=v-2*(T!==0||M!==0?T+M:At(u.left,u.right)):A=g-2*(j!==0||B!==0?j+B:At(u.top,u.bottom))}await l({...t,availableWidth:L,availableHeight:A});const F=await s.getDimensions(c.floating);return v!==F.width||g!==F.height?{reset:{rects:!0}}:{}}}};function Fs(){return typeof window<"u"}function Li(e){return jv(e)?(e.nodeName||"").toLowerCase():"#document"}function xt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function un(e){var t;return(t=(jv(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function jv(e){return Fs()?e instanceof Node||e instanceof xt(e).Node:!1}function zt(e){return Fs()?e instanceof Element||e instanceof xt(e).Element:!1}function An(e){return Fs()?e instanceof HTMLElement||e instanceof xt(e).HTMLElement:!1}function Ov(e){return!Fs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof xt(e).ShadowRoot}function Ho(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Wt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function vN(e){return/^(table|td|th)$/.test(Li(e))}function Bs(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var yN=/transform|translate|scale|rotate|perspective|filter/,bN=/paint|layout|strict|content/,$r=e=>!!e&&e!=="none",ou;function au(e){const t=zt(e)?Wt(e):e;return $r(t.transform)||$r(t.translate)||$r(t.scale)||$r(t.rotate)||$r(t.perspective)||!su()&&($r(t.backdropFilter)||$r(t.filter))||yN.test(t.willChange||"")||bN.test(t.contain||"")}function _N(e){let t=Yn(e);for(;An(t)&&!ji(t);){if(au(t))return t;if(Bs(t))return null;t=Yn(t)}return null}function su(){return ou==null&&(ou=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),ou}function ji(e){return/^(html|body|#document)$/.test(Li(e))}function Wt(e){return xt(e).getComputedStyle(e)}function Us(e){return zt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Yn(e){if(Li(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ov(e)&&e.host||un(e);return Ov(t)?t.host:t}function Mv(e){const t=Yn(e);return ji(t)?e.ownerDocument?e.ownerDocument.body:e.body:An(t)&&Ho(t)?t:Mv(t)}function Ko(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Mv(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=xt(i);if(o){const c=cu(s);return t.concat(s,s.visualViewport||[],Ho(i)?i:[],c&&n?Ko(c):[])}else return t.concat(i,Ko(i,[],n))}function cu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Fv(e){const t=Wt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=An(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=Ls(n)!==o||Ls(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function lu(e){return zt(e)?e:e.contextElement}function Oi(e){const t=lu(e);if(!An(t))return ln(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=Fv(t);let s=(o?Ls(n.width):n.width)/r,c=(o?Ls(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var wN=ln(0);function Bv(e){const t=xt(e);return!su()||!t.visualViewport?wN:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function SN(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==xt(e)?!1:t}function Lr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=lu(e);let s=ln(1);t&&(r?zt(r)&&(s=Oi(r)):s=Oi(e));const c=SN(o,n,r)?Bv(o):ln(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(o){const f=xt(o),m=r&&zt(r)?xt(r):r;let v=f,g=cu(v);for(;g&&r&&m!==v;){const h=Oi(g),y=g.getBoundingClientRect(),w=Wt(g),_=y.left+(g.clientLeft+parseFloat(w.paddingLeft))*h.x,I=y.top+(g.clientTop+parseFloat(w.paddingTop))*h.y;l*=h.x,d*=h.y,u*=h.x,p*=h.y,l+=_,d+=I,v=xt(g),g=cu(v)}}return Ms({width:u,height:p,x:l,y:d})}function qs(e,t){const n=Us(e).scrollLeft;return t?t.left+n:Lr(un(e)).left+n}function Uv(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-qs(e,n),y:n.top+t.scrollTop}}function CN(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=un(r),c=t?Bs(t.floating):!1;if(r===s||c&&o)return n;let l={scrollLeft:0,scrollTop:0},d=ln(1);const u=ln(0),p=An(r);if((p||!p&&!o)&&((Li(r)!=="body"||Ho(s))&&(l=Us(r)),p)){const m=Lr(r);d=Oi(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const f=s&&!p&&!o?Uv(s,l):ln(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+f.x,y:n.y*d.y-l.scrollTop*d.y+u.y+f.y}}function IN(e){return Array.from(e.getClientRects())}function PN(e){const t=un(e),n=Us(e),r=e.ownerDocument.body,i=At(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=At(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+qs(e);const c=-n.scrollTop;return Wt(r).direction==="rtl"&&(s+=At(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var qv=25;function RN(e,t){const n=xt(e),r=un(e),i=n.visualViewport;let o=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){o=i.width,s=i.height;const u=su();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=qs(r);if(d<=0){const u=r.ownerDocument,p=u.body,f=getComputedStyle(p),m=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,v=Math.abs(r.clientWidth-p.clientWidth-m);v<=qv&&(o-=v)}else d<=qv&&(o+=d);return{width:o,height:s,x:c,y:l}}function kN(e,t){const n=Lr(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=An(e)?Oi(e):ln(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}function Gv(e,t,n){let r;if(t==="viewport")r=RN(e,n);else if(t==="document")r=PN(un(e));else if(zt(t))r=kN(t,n);else{const i=Bv(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Ms(r)}function Hv(e,t){const n=Yn(e);return n===t||!zt(n)||ji(n)?!1:Wt(n).position==="fixed"||Hv(n,t)}function TN(e,t){const n=t.get(e);if(n)return n;let r=Ko(e,[],!1).filter(c=>zt(c)&&Li(c)!=="body"),i=null;const o=Wt(e).position==="fixed";let s=o?Yn(e):e;for(;zt(s)&&!ji(s);){const c=Wt(s),l=au(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Ho(s)&&!l&&Hv(e,s))?r=r.filter(d=>d!==s):i=c,s=Yn(s)}return t.set(e,r),r}function NN(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Bs(t)?[]:TN(t,this._c):[].concat(n),r],s=Gv(t,o[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<o.length;p++){const f=Gv(t,o[p],i);c=At(f.top,c),l=Jn(f.right,l),d=Jn(f.bottom,d),u=At(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function EN(e){const{width:t,height:n}=Fv(e);return{width:t,height:n}}function AN(e,t,n){const r=An(t),i=un(t),o=n==="fixed",s=Lr(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const l=ln(0);function d(){l.x=qs(i)}if(r||!r&&!o)if((Li(t)!=="body"||Ho(i))&&(c=Us(t)),r){const p=Lr(t,!0,o,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();o&&!r&&i&&d();const u=i&&!r&&!o?Uv(i,c):ln(0);return{x:s.left+c.scrollLeft-l.x-u.x,y:s.top+c.scrollTop-l.y-u.y,width:s.width,height:s.height}}function du(e){return Wt(e).position==="static"}function Kv(e,t){if(!An(e)||Wt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return un(e)===n&&(n=n.ownerDocument.body),n}function Vv(e,t){const n=xt(e);if(Bs(e))return n;if(!An(e)){let i=Yn(e);for(;i&&!ji(i);){if(zt(i)&&!du(i))return i;i=Yn(i)}return n}let r=Kv(e,t);for(;r&&vN(r)&&du(r);)r=Kv(r,t);return r&&ji(r)&&du(r)&&!au(r)?n:r||_N(e)||n}var xN=async function(e){const t=this.getOffsetParent||Vv,n=this.getDimensions,r=await n(e.floating);return{reference:AN(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function DN(e){return Wt(e).direction==="rtl"}var $N={convertOffsetParentRelativeRectToViewportRelativeRect:CN,getDocumentElement:un,getClippingRect:NN,getOffsetParent:Vv,getElementRects:xN,getClientRects:IN,getDimensions:EN,getScale:Oi,isElement:zt,isRTL:DN};function zv(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function LN(e,t){let n=null,r;const i=un(e);function o(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),o();const d=e.getBoundingClientRect(),{left:u,top:p,width:f,height:m}=d;if(c||t(),!f||!m)return;const v=js(p),g=js(i.clientWidth-(u+f)),h=js(i.clientHeight-(p+m)),y=js(u),w={rootMargin:-v+"px "+-g+"px "+-h+"px "+-y+"px",threshold:At(0,Jn(1,l))||1};let _=!0;function I(P){const k=P[0].intersectionRatio;if(k!==l){if(!_)return s();k?s(!1,k):r=setTimeout(()=>{s(!1,1e-7)},1e3)}k===1&&!zv(d,e.getBoundingClientRect())&&s(),_=!1}try{n=new IntersectionObserver(I,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(I,w)}n.observe(e)}return s(!0),o}function jN(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:o=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=lu(e),u=i||o?[...d?Ko(d):[],...t?Ko(t):[]]:[];u.forEach(y=>{i&&y.addEventListener("scroll",n,{passive:!0}),o&&y.addEventListener("resize",n)});const p=d&&c?LN(d,n):null;let f=-1,m=null;s&&(m=new ResizeObserver(y=>{let[w]=y;w&&w.target===d&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var _;(_=m)==null||_.observe(t)})),n()}),d&&!l&&m.observe(d),t&&m.observe(t));let v,g=l?Lr(e):null;l&&h();function h(){const y=Lr(e);g&&!zv(g,y)&&n(),g=y,v=requestAnimationFrame(h)}return n(),()=>{var y;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(y=m)==null||y.disconnect(),m=null,l&&cancelAnimationFrame(v)}}var ON=fN,MN=mN,FN=dN,BN=gN,UN=uN,Wv=lN,qN=hN,GN=(e,t,n)=>{const r=new Map,i={platform:$N,...n},o={...i.platform,_c:r};return cN(e,t,{...i,platform:o})},Gs=typeof document<"u"?It:function(){};function Hs(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Hs(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const o=i[r];if(!(o==="_owner"&&e.$$typeof)&&!Hs(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Jv(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yv(e,t){const n=Jv(e);return Math.round(t*n)/n}function uu(e){const t=q(e);return Gs(()=>{t.current=e}),t}function HN(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:o,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=x({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=x(r);Hs(f,r)||m(r);const[v,g]=x(null),[h,y]=x(null),w=se(D=>{D!==k.current&&(k.current=D,g(D))},[]),_=se(D=>{D!==A.current&&(A.current=D,y(D))},[]),I=o||v,P=s||h,k=q(null),A=q(null),L=q(u),F=l!=null,T=uu(l),M=uu(i),j=uu(d),B=se(()=>{if(!k.current||!A.current)return;const D={placement:t,strategy:n,middleware:f};M.current&&(D.platform=M.current),GN(k.current,A.current,D).then(H=>{const G={...H,isPositioned:j.current!==!1};U.current&&!Hs(L.current,G)&&(L.current=G,Qa(()=>{p(G)}))})},[f,t,n,M,j]);Gs(()=>{d===!1&&L.current.isPositioned&&(L.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[d]);const U=q(!1);Gs(()=>(U.current=!0,()=>{U.current=!1}),[]),Gs(()=>{if(I&&(k.current=I),P&&(A.current=P),I&&P){if(T.current)return T.current(I,P,B);B()}},[I,P,B,T,F]);const $=Re(()=>({reference:k,floating:A,setReference:w,setFloating:_}),[w,_]),E=Re(()=>({reference:I,floating:P}),[I,P]),S=Re(()=>{const D={position:n,left:0,top:0};if(!E.floating)return D;const H=Yv(E.floating,u.x),G=Yv(E.floating,u.y);return c?{...D,transform:"translate("+H+"px, "+G+"px)",...Jv(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:G}},[n,c,E.floating,u.x,u.y]);return Re(()=>({...u,update:B,refs:$,elements:E,floatingStyles:S}),[u,B,$,E,S])}var KN=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?Wv({element:r.current,padding:i}).fn(n):{}:r?Wv({element:r,padding:i}).fn(n):{}}}},VN=(e,t)=>{const n=ON(e);return{name:n.name,fn:n.fn,options:[e,t]}},zN=(e,t)=>{const n=MN(e);return{name:n.name,fn:n.fn,options:[e,t]}},WN=(e,t)=>({fn:qN(e).fn,options:[e,t]}),JN=(e,t)=>{const n=FN(e);return{name:n.name,fn:n.fn,options:[e,t]}},YN=(e,t)=>{const n=BN(e);return{name:n.name,fn:n.fn,options:[e,t]}},XN=(e,t)=>{const n=UN(e);return{name:n.name,fn:n.fn,options:[e,t]}},QN=(e,t)=>{const n=KN(e);return{name:n.name,fn:n.fn,options:[e,t]}},ZN=Object.defineProperty,eE=(e,t)=>ZN(e,"name",{value:t,configurable:!0}),tE=J(eE(function(t,n){const{children:r,width:i=10,height:o=5,...s}=t;return a(ve.svg,{...s,ref:n,width:i,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:a("polygon",{points:"0,0 30,0 15,10"})})},"Arrow")),nE=tE,rE=Object.defineProperty,iE=(e,t)=>rE(e,"name",{value:t,configurable:!0});function Ks(e){const[t,n]=x(void 0);return Xe(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const o=i[0];let s,c;if("borderBoxSize"in o){const l=o.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}iE(Ks,"useSize");var oE=Object.defineProperty,xn=(e,t)=>oE(e,"name",{value:t,configurable:!0}),Xv="Popper",[Qv,Xn]=lt(Xv),[aE,Zv]=Qv(Xv),sE=xn(e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null),[o,s]=x(void 0);return a(aE,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:s,children:n})},"Popper"),cE="PopperAnchor",lE=J(xn(function(t,n){const{__scopePopper:r,virtualRef:i,...o}=t,s=Zv(cE,r),c=q(null),l=s.onAnchorChange,d=se(g=>{c.current=g,g&&l(g)},[l]),u=Se(n,d),p=q(null);K(()=>{if(!i)return;const g=p.current;p.current=i.current,g!==p.current&&l(p.current)});const f=s.placementState&&Vs(s.placementState),m=f?.[0],v=f?.[1];return i?null:a(ve.div,{"data-radix-popper-side":m,"data-radix-popper-align":v,...o,ref:u})},"PopperAnchor")),ey="PopperContent",[dE,uE]=Qv(ey),pE=J(xn(function(t,n){const{__scopePopper:r,side:i="bottom",sideOffset:o=0,align:s="center",alignOffset:c=0,arrowPadding:l=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:p=0,sticky:f="partial",hideWhenDetached:m=!1,updatePositionStrategy:v="optimized",onPlaced:g,...h}=t,y=Zv(ey,r),[w,_]=x(null),I=Se(n,_),[P,k]=x(null),A=Ks(P),L=A?.width??0,F=A?.height??0,T=i+(s!=="center"?"-"+s:""),M=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},j=Array.isArray(u)?u:[u],B=j.length>0,U={padding:M,boundary:j.filter(ty),altBoundary:B},{refs:$,floatingStyles:E,placement:S,isPositioned:D,middlewareData:H}=HN({strategy:"fixed",placement:T,whileElementsMounted:xn((...ye)=>jN(...ye,{animationFrame:v==="always"}),"whileElementsMounted"),elements:{reference:y.anchor},middleware:[VN({mainAxis:o+F,alignmentAxis:c}),d&&zN({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?WN():void 0,...U}),d&&JN({...U}),YN({...U,apply:xn(({elements:ye,rects:Y,availableWidth:ce,availableHeight:ge})=>{const{width:pe,height:He}=Y.reference,de=ye.floating.style;de.setProperty("--radix-popper-available-width",`${ce}px`),de.setProperty("--radix-popper-available-height",`${ge}px`),de.setProperty("--radix-popper-anchor-width",`${pe}px`),de.setProperty("--radix-popper-anchor-height",`${He}px`)},"apply")}),P&&QN({element:P,padding:l}),gE({arrowWidth:L,arrowHeight:F}),m&&XN({strategy:"referenceHidden",...U,boundary:B?U.boundary:void 0})]}),G=y.setPlacementState;Xe(()=>(G(S),()=>{G(void 0)}),[S,G]);const[oe,ae]=Vs(S),ee=mt(g);Xe(()=>{D&&ee?.()},[D,ee]);const ie=H.arrow?.x,Ce=H.arrow?.y,Ie=H.arrow?.centerOffset!==0,[Ne,le]=x();return Xe(()=>{w&&le(window.getComputedStyle(w).zIndex)},[w]),a("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...E,transform:D?E.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ne,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:a(dE,{scope:r,placedSide:oe,placedAlign:ae,onArrowChange:k,arrowX:ie,arrowY:Ce,shouldHideArrow:Ie,children:a(ve.div,{"data-side":oe,"data-align":ae,...h,ref:I,style:{...h.style,animation:D?h.style?.animation:"none"}})})})},"PopperContent")),fE="PopperArrow",mE={top:"bottom",right:"left",bottom:"top",left:"right"},hE=J(xn(function(t,n){const{__scopePopper:r,...i}=t,o=uE(fE,r),s=mE[o.placedSide];return a("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:a(nE,{...i,ref:n,style:{...i.style,display:"block"}})})},"PopperArrow"));function ty(e){return e!==null}xn(ty,"isNotNull");var gE=xn(e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,o=i.arrow?.centerOffset!==0,s=o?0:e.arrowWidth,c=o?0:e.arrowHeight,[l,d]=Vs(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,f=(i.arrow?.y??0)+c/2;let m="",v="";return l==="bottom"?(m=o?u:`${p}px`,v=`${-c}px`):l==="top"?(m=o?u:`${p}px`,v=`${r.floating.height+c}px`):l==="right"?(m=`${-c}px`,v=o?u:`${f}px`):l==="left"&&(m=`${r.floating.width+c}px`,v=o?u:`${f}px`),{data:{x:m,y:v}}}}),"transformOrigin");function Vs(e){const[t,n="center"]=e.split("-");return[t,n]}xn(Vs,"getSideAndAlignFromPlacement");var zs=sE,Vo=lE,Ws=pE,vE=hE,yE=Object.defineProperty,Dn=(e,t)=>yE(e,"name",{value:t,configurable:!0}),pu="Popover",[ny,IU]=lt(pu,[Xn]),Js=Xn(),[bE,jr]=ny(pu),_E=Dn(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=Js(t),l=q(null),[d,u]=x(!1),[p,f]=Et({prop:r,defaultProp:i??!1,onChange:o,caller:pu});return a(zs,{...c,children:a(bE,{scope:t,contentId:Nt(),triggerRef:l,open:p,onOpenChange:f,onOpenToggle:se(()=>f(m=>!m),[f]),hasCustomAnchor:d,onCustomAnchorAdd:se(()=>u(!0),[]),onCustomAnchorRemove:se(()=>u(!1),[]),modal:s,children:n})})},"Popover"),wE="PopoverAnchor",SE=J(Dn(function(t,n){const{__scopePopover:r,...i}=t,o=jr(wE,r),s=Js(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:l}=o;return K(()=>(c(),()=>l()),[c,l]),a(Vo,{...s,...i,ref:n})},"PopoverAnchor")),CE="PopoverTrigger",IE=J(Dn(function(t,n){const{__scopePopover:r,...i}=t,o=jr(CE,r),s=Js(r),c=Se(n,o.triggerRef),l=a(ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":fu(o.open),...i,ref:c,onClick:ne(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:a(Vo,{asChild:!0,...s,children:l})},"PopoverTrigger")),ry="PopoverPortal",[PE,RE]=ny(ry,{forceMount:void 0}),kE=Dn(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=jr(ry,t);return a(PE,{scope:t,forceMount:n,children:a(Pt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),zo="PopoverContent",TE=J(Dn(function(t,n){const r=RE(zo,t.__scopePopover),{forceMount:i=r.forceMount,...o}=t,s=jr(zo,t.__scopePopover);return a(Pt,{present:i||s.open,children:s.modal?a(EE,{...o,ref:n}):a(AE,{...o,ref:n})})},"PopoverContent")),NE=on("PopoverContent.RemoveScroll"),EE=J(Dn(function(t,n){const r=jr(zo,t.__scopePopover),i=q(null),o=Se(n,i),s=q(!1);return K(()=>{const c=i.current;if(c)return ds(c)},[]),a(Co,{as:NE,allowPinchZoom:!0,children:a(iy,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ne(t.onCloseAutoFocus,c=>{c.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:ne(t.onPointerDownOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;s.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:ne(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),AE=J(Dn(function(t,n){const r=jr(zo,t.__scopePopover),i=q(!1),o=q(!1);return a(iy,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{t.onCloseAutoFocus?.(s),s.defaultPrevented||(i.current||r.triggerRef.current?.focus(),s.preventDefault()),i.current=!1,o.current=!1},onInteractOutside:s=>{t.onInteractOutside?.(s),s.defaultPrevented||(i.current=!0,s.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const c=s.target;r.triggerRef.current?.contains(c)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&o.current&&s.preventDefault()}})},"PopoverContentNonModal")),iy=J(Dn(function(t,n){const{__scopePopover:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:p,...f}=t,m=jr(zo,r),v=Js(r);return bi(),a(ts,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(hi,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>m.onOpenChange(!1),deferPointerDownOutside:!0,children:a(Ws,{"data-state":fu(m.open),role:"dialog",id:m.contentId,...v,...f,ref:n,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function fu(e){return e?"open":"closed"}Dn(fu,"getState");var oy=_E,xE=SE,DE=IE,ay=kE,sy=TE;function mu(e){return e.trim()}function cy({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:o,"aria-labelledby":s}){const[c,l]=x(!1),[d,u]=x(""),[p,f]=x(0),m=q(null),v=Re(()=>{const T=new Set,M=[];for(const j of[...n,...e]){const B=mu(j);!B||T.has(B)||(T.add(B),M.push(B))}return M.sort((j,B)=>j.localeCompare(B))},[n,e]),g=mu(d),h=g.toLowerCase(),y=Re(()=>h?v.filter(T=>T.toLowerCase().includes(h)):v,[v,h]),w=g?v.some(T=>T.toLowerCase()===h):!1,_=!!g&&!w,I=y.length+(_?1:0);K(()=>{p>=I&&f(Math.max(0,I-1))},[I,p]),K(()=>{if(!c)return;const T=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(T)},[c]);const P=T=>{e.includes(T)?t(e.filter(M=>M!==T)):t(Array.from(new Set([...e,T])))},k=T=>{const M=mu(T);M&&(t(Array.from(new Set([...e,M]))),u(""),f(0))},A=T=>{if(T<y.length){const M=y[T];M&&P(M);return}_&&k(g)},L=T=>{if(T.key==="ArrowDown"){T.preventDefault(),f(M=>Math.min(I-1,M+1));return}if(T.key==="ArrowUp"){T.preventDefault(),f(M=>Math.max(0,M-1));return}if(T.key==="Enter"){T.preventDefault(),A(p);return}},F=T=>{t(e.filter(M=>M!==T))};return a("div",{class:"project-scope-picker",children:[a("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?a("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(T=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:T}),o?null:a("button",{"aria-label":`Remove ${T}`,class:"project-scope-picker-selected-remove",onClick:()=>F(T),type:"button",children:"×"})]},T))}),a(oy,{onOpenChange:T=>{l(T),T||(u(""),f(0))},open:c,children:[a(DE,{asChild:!0,children:a("button",{class:"project-scope-picker-trigger settings-button",disabled:o,type:"button",children:[a("span",{"aria-hidden":"true",children:"+"}),a("span",{children:r||"Add project"})]})}),a(ay,{children:a(sy,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:T=>{u(T.currentTarget.value),f(0)},onKeyDown:L,placeholder:"Search or create…",ref:m,type:"text",value:d}),a("div",{class:"project-scope-picker-results",role:"listbox",children:[y.length===0&&!_?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,y.map((T,M)=>{const j=e.includes(T);return a("button",{"aria-selected":j,class:M===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{f(M),P(T)},onMouseEnter:()=>f(M),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:j?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:T})]},T)}),_?a("button",{"aria-selected":!1,class:p===y.length?"project-scope-picker-row project-scope-picker-row--create project-scope-picker-row--active":"project-scope-picker-row project-scope-picker-row--create",onClick:()=>k(g),onMouseEnter:()=>f(y.length),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),a("span",{class:"project-scope-picker-row-label",children:`Create "${g}"`})]}):null]})]})})]})]})}var $E=Object.defineProperty,Qn=(e,t)=>$E(e,"name",{value:t,configurable:!0}),hu="Switch",[LE,PU]=lt(hu),[jE,gu]=LE(hu);function ly(e){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:i,disabled:o,form:s,name:c,onCheckedChange:l,required:d,value:u="on",internal_do_not_use_render:p}=e,[f,m]=Et({prop:n,defaultProp:i??!1,onChange:l,caller:hu}),[v,g]=x(null),[h,y]=x(null),w=q(!1),[_,I]=zn(k=>k+1,0),P={checked:f,setChecked:m,disabled:o,control:v,setControl:g,name:c,form:s,value:u,hasConsumerStoppedPropagationRef:w,userInteractionCount:_,onUserInteraction:I,required:d,defaultChecked:i,isFormControl:v?!!s||!!v.closest("form"):!0,bubbleInput:h,setBubbleInput:y};return a(jE,{scope:t,...P,children:dy(p)?p(P):r})}Qn(ly,"SwitchProvider");var OE="SwitchTrigger",ME=J(Qn(function({__scopeSwitch:t,onClick:n,...r},i){const{control:o,form:s,value:c,disabled:l,checked:d,required:u,setControl:p,setChecked:f,hasConsumerStoppedPropagationRef:m,onUserInteraction:v,isFormControl:g,bubbleInput:h}=gu(OE,t),y=Se(i,p),w=q(d);return K(()=>{const _=s?o?.ownerDocument.getElementById(s):o?.form;if(_ instanceof HTMLFormElement){const I=Qn(()=>f(w.current),"reset");return _.addEventListener("reset",I),()=>_.removeEventListener("reset",I)}},[o,s,f]),a(ve.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":vu(d),"data-disabled":l?"":void 0,disabled:l,value:c,...r,ref:y,onClick:ne(n,_=>{v(),f(I=>!I),h&&g&&(m.current=_.isPropagationStopped(),m.current||_.stopPropagation())})})},"SwitchTrigger")),FE=J(Qn(function(t,n){const{__scopeSwitch:r,name:i,checked:o,defaultChecked:s,required:c,disabled:l,value:d,onCheckedChange:u,form:p,...f}=t;return a(ly,{__scopeSwitch:r,checked:o,defaultChecked:s,disabled:l,required:c,onCheckedChange:u,name:i,form:p,value:d,internal_do_not_use_render:({isFormControl:m})=>a(z,{children:[a(ME,{...f,ref:n,__scopeSwitch:r}),m&&a(GE,{__scopeSwitch:r})]})})},"Switch")),BE="SwitchThumb",UE=J(Qn(function(t,n){const{__scopeSwitch:r,...i}=t,o=gu(BE,r);return a(ve.span,{"data-state":vu(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n})},"SwitchThumb")),qE="SwitchBubbleInput",GE=J(Qn(function({__scopeSwitch:t,onClick:n,...r},i){const{control:o,hasConsumerStoppedPropagationRef:s,userInteractionCount:c,checked:l,defaultChecked:d,required:u,disabled:p,name:f,value:m,form:v,bubbleInput:g,setBubbleInput:h}=gu(qE,t),y=Se(i,h),w=Ks(o),_=q(!1),I=q(l),P=q(c);K(()=>{const A=g;if(!A)return;const L=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(L,"checked").set,T=c!==P.current;P.current=c;const M=I.current!==l;I.current=l;const j=!(T&&s.current);if(M&&F){_.current=!T;const B=new Event("click",{bubbles:j});F.call(A,l),A.dispatchEvent(B),_.current=!1}},[g,l,s,c]);const k=q(l);return a(ve.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??k.current,required:u,disabled:p,name:f,value:m,form:v,...r,tabIndex:-1,ref:y,onClick:ne(n,A=>{_.current&&A.stopPropagation()}),style:{...r.style,...w,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function dy(e){return typeof e=="function"}Qn(dy,"isFunction");function vu(e){return e?"checked":"unchecked"}Qn(vu,"getState");function Mi({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(FE,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(UE,{className:c})})}function Q(e,t="success"){Fk(e,t)}function $n(e){return String(e||"").trim().replace(/\/+$/u,"")}function uy(e){return`${UT}:${$n(e)}`}function HE(e){try{return localStorage.getItem(uy(e))||""}catch{return""}}function KE(e,t){try{localStorage.setItem(uy(e),t)}catch{}}function Ln(){return String(C.coordinatorAdminTargetGroup||"").trim()}function Ys(){const e=String(C.lastCoordinatorAdminStatus?.coordinator_url||"").trim(),t=Ln()||String(C.lastCoordinatorAdminStatus?.active_group||"").trim()||Zn()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function Dt(e){const t=Ys();return!!(e&&t&&$n(e.coordinatorUrl)===$n(t.coordinatorUrl)&&e.groupId===t.groupId)}function yu(e){C.coordinatorAdminTargetGroup=e,KE(C.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Zn(){return(Array.isArray(C.lastCoordinatorAdminGroups)?C.lastCoordinatorAdminGroups:[]).map(e=>({archived_at:e.archived_at??null,display_name:e.display_name??null,group_id:String(e.group_id||"").trim()})).filter(e=>e.group_id)}function bu(e,t){const n=String(t||"").trim(),r=Zn(),i=new Set(r.map(l=>String(l.display_name||"").trim()).filter(Boolean));n&&i.add(n);for(const[l,d]of N.groupPresentationAliases)i.has(d)&&N.groupPresentationAliases.delete(l);if(n)return n;const o=N.groupPresentationAliases.get(e);if(o)return o;for(const l of N.groupPresentationAliases.values())i.add(l);let s=1,c=`Unnamed coordinator group ${s}`;for(;i.has(c);)s+=1,c=`Unnamed coordinator group ${s}`;return N.groupPresentationAliases.set(e,c),c}function VE(){const e=new Map;for(const t of Zn())e.set(t.group_id,t.display_name||"");N.groupRenameDrafts.clear();for(const[t,n]of e.entries())N.groupRenameDrafts.set(t,n)}function zE(){const e=Ln();return Zn().find(t=>t.group_id===e)||null}function py(){const e=C.lastCoordinatorAdminStatus,t=Zn(),n=String(e?.active_group||"").trim(),r=HE(e?.coordinator_url||null),i=Ln(),o=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(o.size===0||o.has(s))?s:n||t[0]?.group_id||"";return yu(c),c}function WE(){const e=new Map,t=new Map,n=Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const o=String(r.display_name||""),s=N.deviceRenameDrafts.get(i),c=N.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:o),t.set(i,o)}N.deviceRenameDrafts.clear();for(const[r,i]of e.entries())N.deviceRenameDrafts.set(r,i);N.deviceRenameServerNames.clear();for(const[r,i]of t.entries())N.deviceRenameServerNames.set(r,i)}function JE(e,t){return t&&t.groupId===e?t:null}function YE(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open legacy group defaults to inspect"}function XE(e,t){return e?.loaded?e.auto_grant_default_space_on_join?"On for the default Space":"Off — Space access stays explicit":t?.autoGrantDefaultSpaceOnJoin===!0?"On for the default Space":t?.autoGrantDefaultSpaceOnJoin===!1?"Off — Space access stays explicit":"Open legacy group defaults to inspect"}function QE(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function ZE(e){const t=QE(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function eA(e){const t=JE(e.groupId,e.setupGuide);return{autoGrant:XE(e.preferences,t),defaultSpace:YE(e.preferences,t),spaces:ZE(e.scopeManagement)}}var _u=null,Xs=null,wu=null;function tA(){return _u}function Su(e){Xs=e}function fy(e){wu=e}function nA(e){return wu===e}function rA(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function Cu(e){return!_u||!Xs?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function Qs(e){_u=e,wu?.(e)}function er(e){const t=Xs;Xs=null,Qs(null),t?.(e)}function iA(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var oA=J(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:o=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const f=q(null);Ja(p,()=>f.current,[]);const[m,v]=x(!1),[g,h]=x(-1),y=Re(()=>{const P=t.trim().toLowerCase();return(P?r.filter(k=>k.toLowerCase().includes(P)):r).slice(0,o)},[t,r,o]);K(()=>{g>=y.length&&h(y.length-1)},[y.length,g]);const w=m&&y.length>0,_=P=>{n(P),v(!1),h(-1),f.current?.focus()};return a(oy,{open:w,onOpenChange:v,children:[a(xE,{asChild:!0,children:a("input",{...u,ref:f,className:d,value:t,onInput:P=>{n(P.currentTarget.value),v(!0),h(-1)},onFocus:P=>{c?.(P)},onBlur:P=>{window.setTimeout(()=>v(!1),120),l?.(P)},onKeyDown:P=>{if(P.key==="ArrowDown"){P.preventDefault(),v(!0),h(k=>y.length===0?-1:Math.min(k+1,y.length-1));return}if(P.key==="ArrowUp"){P.preventDefault(),m||v(!0),h(k=>Math.max(k-1,-1));return}if(P.key==="Escape"&&w){P.preventDefault(),v(!1),h(-1);return}if((P.key==="Tab"||P.key==="Enter")&&g>=0){const k=y[g];if(k){P.preventDefault(),_(k);return}}if(P.key==="Enter"&&i){P.preventDefault(),i();return}s?.(P)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":g>=0?`autocomplete-option-${g}`:void 0})}),a(ay,{children:a(sy,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:P=>P.preventDefault(),onCloseAutoFocus:P=>P.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:y.map((P,k)=>{const A=k===g;return a("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${k}`,onMouseDown:L=>{L.preventDefault(),_(P)},onMouseEnter:()=>h(k),role:"option",tabIndex:-1,children:P},P)})})})})]})}),aA=Object.defineProperty,ht=(e,t)=>aA(e,"name",{value:t,configurable:!0}),my="Radio",[sA,hy]=lt(my),[cA,Zs]=sA(my);function gy(e){const{__scopeRadio:t,checked:n=!1,children:r,disabled:i,form:o,name:s,onCheck:c,required:l,value:d="on",internal_do_not_use_render:u}=e,[p,f]=x(null),[m,v]=x(null),g=q(!1),[h,y]=zn(_=>_+1,0),w={checked:n,disabled:i,required:l,name:s,form:o,value:d,control:p,setControl:f,hasConsumerStoppedPropagationRef:g,userInteractionCount:h,onUserInteraction:y,isFormControl:p?!!o||!!p.closest("form"):!0,bubbleInput:m,setBubbleInput:v,onCheck:ht(()=>c?.(),"onCheck")};return a(cA,{scope:t,...w,children:vy(u)?u(w):r})}ht(gy,"RadioProvider");var lA="RadioTrigger",dA=J(ht(function({__scopeRadio:t,onClick:n,...r},i){const{checked:o,disabled:s,value:c,setControl:l,onCheck:d,hasConsumerStoppedPropagationRef:u,onUserInteraction:p,isFormControl:f,bubbleInput:m}=Zs(lA,t),v=Se(i,l);return a(ve.button,{type:"button",role:"radio","aria-checked":o,"data-state":Iu(o),"data-disabled":s?"":void 0,disabled:s,value:c,...r,ref:v,onClick:ne(n,g=>{o||(p(),d()),m&&f&&(u.current=g.isPropagationStopped(),u.current||g.stopPropagation())})})},"RadioTrigger")),uA="RadioIndicator",pA=J(ht(function(t,n){const{__scopeRadio:r,forceMount:i,...o}=t,s=Zs(uA,r);return a(Pt,{present:i||s.checked,children:a(ve.span,{"data-state":Iu(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:n})})},"RadioIndicator")),fA="RadioBubbleInput",mA=J(ht(function({__scopeRadio:t,onClick:n,...r},i){const{control:o,checked:s,required:c,disabled:l,name:d,value:u,form:p,bubbleInput:f,setBubbleInput:m,hasConsumerStoppedPropagationRef:v,userInteractionCount:g}=Zs(fA,t),h=Se(i,m),y=Ks(o),w=q(!1),_=q(s),I=q(g);K(()=>{const k=f;if(!k)return;const A=window.HTMLInputElement.prototype,L=Object.getOwnPropertyDescriptor(A,"checked").set,F=g!==I.current;I.current=g;const T=_.current!==s;_.current=s;const M=!(F&&v.current);if(T&&L){w.current=!F;const j=new Event("click",{bubbles:M});L.call(k,s),k.dispatchEvent(j),w.current=!1}},[f,s,v,g]);const P=q(s);return a(ve.input,{type:"radio","aria-hidden":!0,defaultChecked:P.current,required:c,disabled:l,name:d,value:u,form:p,...r,tabIndex:-1,ref:h,onClick:ne(n,k=>{w.current&&k.stopPropagation()}),style:{...r.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function vy(e){return typeof e=="function"}ht(vy,"isFunction");function Iu(e){return e?"checked":"unchecked"}ht(Iu,"getState");var hA=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Pu="RadioGroup",[gA,RU]=lt(Pu,[Ai,hy]),yy=Ai(),ec=hy(),[vA,yA]=gA(Pu),bA=J(ht(function(t,n){const{__scopeRadioGroup:r,name:i,form:o,defaultValue:s,value:c,required:l=!1,disabled:d=!1,orientation:u,dir:p,loop:f=!0,onValueChange:m,...v}=t,g=yy(r),h=Ei(p),[y,w]=Et({prop:c,defaultProp:s??null,onChange:m,caller:Pu}),[_,I]=x(null),P=Se(n,I),k=q(y);return K(()=>{const A=o?_?.ownerDocument.getElementById(o):_?.closest("form");if(A instanceof HTMLFormElement){const L=ht(()=>w(k.current),"reset");return A.addEventListener("reset",L),()=>A.removeEventListener("reset",L)}},[_,o,w]),a(vA,{scope:r,name:i,form:o,required:l,disabled:d,value:y,onValueChange:w,children:a(qd,{asChild:!0,...g,orientation:u,dir:h,loop:f,children:a(ve.div,{role:"radiogroup","aria-required":l,"aria-orientation":u,"data-disabled":d?"":void 0,dir:h,...v,ref:P})})})},"RadioGroup")),_A="RadioGroupItemProvider",wA="RadioGroupItemTrigger";function by(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:i,internal_do_not_use_render:o}=e,s=yA(_A,t),c=ec(t),l=s.disabled||r;return a(gy,{...c,checked:s.value===n,disabled:l,required:s.required,name:s.name,form:s.form,value:n,onCheck:()=>s.onValueChange(n),internal_do_not_use_render:o,children:i})}ht(by,"RadioGroupItemProvider");var SA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=yy(r),s=ec(r),{checked:c,disabled:l}=Zs(wA,s.__scopeRadio),d=q(null),u=Se(n,d),p=q(!1);return K(()=>{const f=ht(v=>{hA.includes(v.key)&&(p.current=!0)},"handleKeyDown"),m=ht(()=>p.current=!1,"handleKeyUp");return document.addEventListener("keydown",f),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",m)}},[]),a(Gd,{asChild:!0,...o,focusable:!l,active:c,children:a(dA,{...s,...i,ref:u,onKeyDown:ne(i.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:ne(i.onFocus,()=>{p.current&&d.current?.click()})})})},"RadioGroupItemTrigger")),CA=J(ht(function(t,n){const{__scopeRadioGroup:r,value:i,disabled:o,...s}=t;return a(by,{__scopeRadioGroup:r,value:i,disabled:o,internal_do_not_use_render:({isFormControl:c})=>a(z,{children:[a(SA,{...s,ref:n,__scopeRadioGroup:r}),c&&a(IA,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),IA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=ec(r);return a(mA,{...o,...i,ref:n})},"RadioGroupItemBubbleInput")),PA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=ec(r);return a(pA,{...o,...i,ref:n})},"RadioGroupIndicator"));function RA({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(bA,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,f)=>{const m=`radio-option-input-${f}`,v=`radio-option-label-${f}`;return a("label",{className:i,htmlFor:m,children:[a(CA,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(PA,{className:r})}),a("span",{className:o,id:v,children:p.label})]},p.value)})})}var kA=Object.defineProperty,TA=(e,t)=>kA(e,"name",{value:t,configurable:!0});function Ru(e,[t,n]){return Math.min(n,Math.max(t,e))}TA(Ru,"clamp");var NA=Object.defineProperty,EA=(e,t)=>NA(e,"name",{value:t,configurable:!0});function _y(e){const t=q({value:e,previous:e});return Re(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}EA(_y,"usePrevious");var AA=Object.defineProperty,Me=(e,t)=>AA(e,"name",{value:t,configurable:!0}),xA=[" ","Enter","ArrowUp","ArrowDown"],DA=[" ","Enter"],Fi="Select",[tc,ku,$A]=$o(Fi),[Or,kU]=lt(Fi,[$A,Xn]),Tu=Xn(),[LA,tr]=Or(Fi),[jA,OA]=Or(Fi);function wy(e){const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:o,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:f,required:m,form:v,internal_do_not_use_render:g}=e,h=Tu(t),[y,w]=x(null),[_,I]=x(null),[P,k]=x(!1),A=Ei(d),[L,F]=Et({prop:r,defaultProp:i??!1,onChange:o,caller:Fi}),[T,M]=Et({prop:s,defaultProp:c,onChange:l,caller:Fi}),j=q(null),B=q(T);K(()=>{const ae=v?y?.ownerDocument.getElementById(v):y?.form;if(ae instanceof HTMLFormElement){const ee=Me(()=>M(B.current),"reset");return ae.addEventListener("reset",ee),()=>ae.removeEventListener("reset",ee)}},[v,y,M]);const U=y?!!v||!!y.closest("form"):!0,[$,E]=x(new Set),S=Nt(),D=Array.from($).map(ae=>ae.props.value).join(";"),H=se(ae=>{E(ee=>new Set(ee).add(ae))},[]),G=se(ae=>{E(ee=>{const ie=new Set(ee);return ie.delete(ae),ie})},[]),oe={required:m,trigger:y,onTriggerChange:w,valueNode:_,onValueNodeChange:I,valueNodeHasChildren:P,onValueNodeHasChildrenChange:k,contentId:S,value:T,onValueChange:M,open:L,onOpenChange:F,dir:A,triggerPointerDownPosRef:j,disabled:f,name:u,autoComplete:p,form:v,nativeOptions:$,nativeSelectKey:D,isFormControl:U};return a(zs,{...h,children:a(LA,{scope:t,...oe,children:a(tc.Provider,{scope:t,children:a(jA,{scope:t,onNativeOptionAdd:H,onNativeOptionRemove:G,children:Ry(g)?g(oe):n})})})})}Me(wy,"SelectProvider");var MA=Me(e=>{const{__scopeSelect:t,children:n,...r}=e;return a(wy,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:i})=>a(z,{children:[n,i?a(sx,{__scopeSelect:t}):null]})})},"Select"),FA="SelectTrigger",BA=J(Me(function(t,n){const{__scopeSelect:r,disabled:i=!1,...o}=t,s=Tu(r),c=tr(FA,r),l=c.disabled||i,d=Se(n,c.onTriggerChange),u=ku(r),p=q("touch"),[f,m,v]=Eu(h=>{const y=u().filter(_=>!_.disabled),w=Au(y,h,y.find(_=>_.value===c.value));w!==void 0&&c.onValueChange(w.value)}),g=Me(h=>{l||(c.onOpenChange(!0),v()),h&&(c.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})},"handleOpen");return a(Vo,{asChild:!0,...s,children:a(ve.button,{type:"button",role:"combobox","aria-controls":c.open?c.contentId:void 0,"aria-expanded":c.open,"aria-required":c.required,"aria-autocomplete":"none",dir:c.dir,"data-state":c.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":Wo(c.value)?"":void 0,...o,ref:d,onClick:ne(o.onClick,h=>{h.currentTarget.focus(),p.current!=="mouse"&&g(h)}),onPointerDown:ne(o.onPointerDown,h=>{p.current=h.pointerType;const y=h.target;y.hasPointerCapture(h.pointerId)&&y.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:ne(o.onKeyDown,h=>{const y=f.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(y&&h.key===" ")&&xA.includes(h.key)&&(g(),h.preventDefault())})})})},"SelectTrigger")),UA="SelectValue",qA=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,children:s,placeholder:c="",...l}=t,d=tr(UA,r),{onValueNodeHasChildrenChange:u}=d,p=s!==void 0,f=Se(n,d.onValueNodeChange);Xe(()=>{u(p)},[u,p]);const m=Wo(d.value);return a(ve.span,{...l,asChild:m?!1:l.asChild,ref:f,style:{pointerEvents:"none"},children:a(z,{children:m?c:s},m?"placeholder":"value")})},"SelectValue")),GA=J(Me(function(t,n){const{__scopeSelect:r,children:i,...o}=t;return a(ve.span,{"aria-hidden":!0,...o,ref:n,children:i||"▼"})},"SelectIcon")),[HA,KA]=Or("SelectPortal",{forceMount:void 0}),VA=Me(e=>{const{__scopeSelect:t,forceMount:n,...r}=e;return a(HA,{scope:e.__scopeSelect,forceMount:n,children:a(gi,{asChild:!0,...r})})},"SelectPortal"),Mr="SelectContent",zA=J(Me(function(t,n){const r=KA(Mr,t.__scopeSelect),{forceMount:i=r.forceMount,...o}=t,s=tr(Mr,t.__scopeSelect),[c,l]=x();return Xe(()=>{l(new DocumentFragment)},[]),a(Pt,{present:i||s.open,children:({present:d})=>d?a(YA,{...o,ref:n}):a(WA,{...o,fragment:c})})},"SelectContent")),WA=J(Me(function(t,n){const{__scopeSelect:r,children:i,fragment:o}=t;return o?rn(a(Sy,{scope:r,children:a(tc.Slot,{scope:r,children:a("div",{ref:n,children:i})})}),o):null},"SelectContentFragment")),Jt=10,[Sy,nc]=Or(Mr),JA=on("SelectContent.RemoveScroll"),YA=J(Me(function(t,n){const{__scopeSelect:r}=t,{position:i="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:c,side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:y,...w}=t,_=tr(Mr,r),[I,P]=x(null),[k,A]=x(null),L=Se(n,P),[F,T]=x(null),[M,j]=x(null),B=ku(r),[U,$]=x(!1),E=q(!1);K(()=>{if(I)return ds(I)},[I]),bi();const S=se(le=>{const[ye,...Y]=B().map(pe=>pe.ref.current),[ce]=Y.slice(-1),ge=document.activeElement;for(const pe of le)if(pe===ge||(pe?.scrollIntoView({block:"nearest"}),pe===ye&&k&&(k.scrollTop=0),pe===ce&&k&&(k.scrollTop=k.scrollHeight),pe?.focus(),document.activeElement!==ge))return},[B,k]),D=se(()=>S([F,I]),[S,F,I]);K(()=>{U&&D()},[U,D]);const{onOpenChange:H,triggerPointerDownPosRef:G}=_;K(()=>{if(I){let le={x:0,y:0};const ye=Me(ce=>{le={x:Math.abs(Math.round(ce.pageX)-(G.current?.x??0)),y:Math.abs(Math.round(ce.pageY)-(G.current?.y??0))}},"handlePointerMove"),Y=Me(ce=>{le.x<=10&&le.y<=10?ce.preventDefault():ce.composedPath().includes(I)||H(!1),document.removeEventListener("pointermove",ye),G.current=null},"handlePointerUp");return G.current!==null&&(document.addEventListener("pointermove",ye),document.addEventListener("pointerup",Y,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ye),document.removeEventListener("pointerup",Y,{capture:!0})}}},[I,H,G]),K(()=>{const le=Me(()=>H(!1),"close");return window.addEventListener("blur",le),window.addEventListener("resize",le),()=>{window.removeEventListener("blur",le),window.removeEventListener("resize",le)}},[H]);const[oe,ae]=Eu(le=>{const ye=B().filter(ce=>!ce.disabled),Y=Au(ye,le,ye.find(ce=>ce.ref.current===document.activeElement));Y&&setTimeout(()=>Y.ref.current?.focus())}),ee=se((le,ye,Y)=>{const ce=!E.current&&!Y;(_.value!==void 0&&_.value===ye||ce)&&(T(le),ce&&(E.current=!0))},[_.value]),ie=se(()=>I?.focus(),[I]),Ce=se((le,ye,Y)=>{const ce=!E.current&&!Y;(_.value!==void 0&&_.value===ye||ce)&&j(le)},[_.value]),Ie=i==="popper"?Cy:XA,Ne=Ie===Cy?{side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:y}:{};return a(Sy,{scope:r,content:I,viewport:k,onViewportChange:A,itemRefCallback:ee,selectedItem:F,onItemLeave:ie,itemTextRefCallback:Ce,focusSelectedItem:D,selectedItemText:M,position:i,isPositioned:U,searchRef:oe,children:a(Co,{as:JA,allowPinchZoom:!0,children:a(ts,{asChild:!0,trapped:_.open,onMountAutoFocus:le=>{le.preventDefault()},onUnmountAutoFocus:ne(o,le=>{_.trigger?.focus({preventScroll:!0}),le.preventDefault()}),children:a(hi,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:le=>le.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:a(Ie,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:le=>le.preventDefault(),...w,...Ne,onPlaced:()=>$(!0),ref:L,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:ne(w.onKeyDown,le=>{const ye=le.ctrlKey||le.altKey||le.metaKey;if(le.key==="Tab"&&le.preventDefault(),!ye&&le.key.length===1&&ae(le.key),["ArrowUp","ArrowDown","Home","End"].includes(le.key)){let Y=B().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(le.key)&&(Y=Y.slice().reverse()),["ArrowUp","ArrowDown"].includes(le.key)){const ce=le.target,ge=Y.indexOf(ce);Y=Y.slice(ge+1)}setTimeout(()=>S(Y)),le.preventDefault()}})})})})})})},"SelectContentImpl")),XA=J(Me(function(t,n){const{__scopeSelect:r,onPlaced:i,...o}=t,s=tr(Mr,r),c=nc(Mr,r),[l,d]=x(null),[u,p]=x(null),f=Se(n,p),m=ku(r),v=q(!1),g=q(!0),{viewport:h,selectedItem:y,selectedItemText:w,focusSelectedItem:_}=c,I=se(()=>{if(s.trigger&&s.valueNode&&l&&u&&h&&y&&w){const L=s.trigger.getBoundingClientRect(),F=u.getBoundingClientRect(),T=s.valueNode.getBoundingClientRect(),M=w.getBoundingClientRect();if(s.dir!=="rtl"){const ce=M.left-F.left,ge=T.left-ce,pe=L.left-ge,He=L.width+pe,de=Math.max(He,F.width),W=window.innerWidth-Jt,Pe=Ru(ge,[Jt,Math.max(Jt,W-de)]);l.style.minWidth=He+"px",l.style.left=Pe+"px"}else{const ce=F.right-M.right,ge=window.innerWidth-T.right-ce,pe=window.innerWidth-L.right-ge,He=L.width+pe,de=Math.max(He,F.width),W=window.innerWidth-Jt,Pe=Ru(ge,[Jt,Math.max(Jt,W-de)]);l.style.minWidth=He+"px",l.style.right=Pe+"px"}const j=m(),B=window.innerHeight-Jt*2,U=h.scrollHeight,$=window.getComputedStyle(u),E=parseInt($.borderTopWidth,10),S=parseInt($.paddingTop,10),D=parseInt($.borderBottomWidth,10),H=parseInt($.paddingBottom,10),G=E+S+U+H+D,oe=Math.min(y.offsetHeight*5,G),ae=window.getComputedStyle(h),ee=parseInt(ae.paddingTop,10),ie=parseInt(ae.paddingBottom,10),Ce=L.top+L.height/2-Jt,Ie=B-Ce,Ne=y.offsetHeight/2,le=y.offsetTop+Ne,ye=E+S+le,Y=G-ye;if(ye<=Ce){const ce=j.length>0&&y===j[j.length-1].ref.current;l.style.bottom="0px";const ge=u.clientHeight-h.offsetTop-h.offsetHeight,pe=ye+Math.max(Ie,Ne+(ce?ie:0)+ge+D);l.style.height=pe+"px"}else{const ce=j.length>0&&y===j[0].ref.current;l.style.top="0px";const ge=Math.max(Ce,E+h.offsetTop+(ce?ee:0)+Ne)+Y;l.style.height=ge+"px",h.scrollTop=ye-Ce+h.offsetTop}l.style.margin=`${Jt}px 0`,l.style.minHeight=oe+"px",l.style.maxHeight=B+"px",i?.(),requestAnimationFrame(()=>v.current=!0)}},[m,s.trigger,s.valueNode,l,u,h,y,w,s.dir,i]);Xe(()=>I(),[I]);const[P,k]=x();Xe(()=>{u&&k(window.getComputedStyle(u).zIndex)},[u]);const A=se(L=>{L&&g.current===!0&&(I(),_?.(),g.current=!1)},[I,_]);return a(QA,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:v,onScrollButtonChange:A,children:a("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:P},children:a(ve.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})},"SelectItemAlignedPosition")),Cy=J(Me(function(t,n){const{__scopeSelect:r,align:i="start",collisionPadding:o=Jt,...s}=t,c=Tu(r);return a(Ws,{...c,...s,ref:n,align:i,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[QA,ZA]=Or(Mr,{}),Iy="SelectViewport",ex=J(Me(function(t,n){const{__scopeSelect:r,nonce:i,...o}=t,s=nc(Iy,r),c=ZA(Iy,r),l=Se(n,s.onViewportChange),d=q(0);return a(z,{children:[a("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),a(tc.Slot,{scope:r,children:a(ve.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:ne(o.onScroll,u=>{const p=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:m}=c;if(m?.current&&f){const v=Math.abs(d.current-p.scrollTop);if(v>0){const g=window.innerHeight-Jt*2,h=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),w=Math.max(h,y);if(w<g){const _=w+v,I=Math.min(g,_),P=_-I;f.style.height=I+"px",f.style.bottom==="0px"&&(p.scrollTop=P>0?P:0,f.style.justifyContent="flex-end")}}}d.current=p.scrollTop})})})]})},"SelectViewport")),[TU,NU]=Or("SelectGroup"),Nu="SelectItem",[tx,Py]=Or(Nu),nx=J(Me(function(t,n){const{__scopeSelect:r,value:i,disabled:o=!1,textValue:s,...c}=t,l=tr(Nu,r),d=nc(Nu,r),u=l.value===i,[p,f]=x(s??""),[m,v]=x(!1),g=mt(I=>d.itemRefCallback?.(I,i,o)),h=Se(n,g),y=Nt(),w=q("touch"),_=Me(()=>{o||(l.onValueChange(i),l.onOpenChange(!1))},"handleSelect");return a(tx,{scope:r,value:i,disabled:o,textId:y,isSelected:u,onItemTextChange:se(I=>{f(P=>P||(I?.textContent??"").trim())},[]),children:a(tc.ItemSlot,{scope:r,value:i,disabled:o,textValue:p,children:a(ve.div,{role:"option","aria-labelledby":y,"data-highlighted":m?"":void 0,"aria-selected":u&&m,"data-state":u?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...c,ref:h,onFocus:ne(c.onFocus,()=>v(!0)),onBlur:ne(c.onBlur,()=>v(!1)),onClick:ne(c.onClick,()=>{w.current!=="mouse"&&_()}),onPointerUp:ne(c.onPointerUp,()=>{w.current==="mouse"&&_()}),onPointerDown:ne(c.onPointerDown,I=>{w.current=I.pointerType}),onPointerMove:ne(c.onPointerMove,I=>{w.current=I.pointerType,o?d.onItemLeave?.():w.current==="mouse"&&I.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ne(c.onPointerLeave,I=>{I.currentTarget===document.activeElement&&d.onItemLeave?.()}),onKeyDown:ne(c.onKeyDown,I=>{o||I.target!==I.currentTarget||d.searchRef?.current!==""&&I.key===" "||(DA.includes(I.key)&&_(),I.key===" "&&I.preventDefault())})})})})},"SelectItem")),rc="SelectItemText",rx=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,...s}=t,c=tr(rc,r),l=nc(rc,r),d=Py(rc,r),u=OA(rc,r),[p,f]=x(null),m=mt(_=>l.itemTextRefCallback?.(_,d.value,d.disabled)),v=Se(n,f,d.onItemTextChange,m),g=p?.textContent,h=Re(()=>a("option",{value:d.value,disabled:d.disabled,children:g},d.value),[d.disabled,d.value,g]),{onNativeOptionAdd:y,onNativeOptionRemove:w}=u;return Xe(()=>(y(h),()=>w(h)),[y,w,h]),a(z,{children:[a(ve.span,{id:d.textId,...s,ref:v}),d.isSelected&&c.valueNode&&!c.valueNodeHasChildren&&!Wo(c.value)?rn(s.children,c.valueNode):null]})},"SelectItemText")),ix="SelectItemIndicator",ox=J(Me(function(t,n){const{__scopeSelect:r,...i}=t;return Py(ix,r).isSelected?a(ve.span,{"aria-hidden":!0,...i,ref:n}):null},"SelectItemIndicator")),ax="SelectBubbleInput",sx=J(Me(function({__scopeSelect:t,...n},r){const i=tr(ax,t),{value:o,onValueChange:s,required:c,disabled:l,name:d,autoComplete:u,form:p}=i,{nativeOptions:f,nativeSelectKey:m}=i,v=q(null),g=Se(r,v),h=o??"",y=_y(h),w=Array.from(f).some(_=>(_.props.value??"")==="");return K(()=>{const _=v.current;if(!_)return;const I=window.HTMLSelectElement.prototype,P=Object.getOwnPropertyDescriptor(I,"value").set;if(y!==h&&P){const k=new Event("change",{bubbles:!0});P.call(_,h),_.dispatchEvent(k)}},[y,h]),a(ve.select,{"aria-hidden":!0,required:c,tabIndex:-1,name:d,autoComplete:u,disabled:l,form:p,onChange:_=>s(_.target.value),...n,style:{...Kg,...n.style},ref:g,defaultValue:h,children:[Wo(o)&&!w?a("option",{value:""}):null,Array.from(f)]},m)},"SelectBubbleInput"));function Ry(e){return typeof e=="function"}Me(Ry,"isFunction");function Wo(e){return e===""||e===void 0}Me(Wo,"shouldShowPlaceholder");function Eu(e){const t=mt(e),n=q(""),r=q(0),i=se(s=>{const c=n.current+s;t(c),Me((function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}),"updateSearch")(c)},[t]),o=se(()=>{n.current="",window.clearTimeout(r.current)},[]);return K(()=>()=>window.clearTimeout(r.current),[]),[n,i,o]}Me(Eu,"useTypeaheadSearch");function Au(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=ky(e,Math.max(i,0));r.length===1&&(o=o.filter(c=>c!==n));const s=o.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}Me(Au,"findNextItem");function ky(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Me(ky,"wrapArray");var Ty="__codemem-empty-select__";function cx(){return a("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[a("title",{children:"Open"}),a("path",{d:"m6 9 6 6 6-6"})]})}function lx(){return a("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[a("title",{children:"Selected"}),a("path",{d:"M20 6 9 17l-5-5"})]})}function xu(e){return e===""?Ty:e}function dx(e){return e===Ty?"":e}function nr({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:o,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const f=u?xu(u):void 0;return a(MA,{disabled:r,onValueChange:m=>s(dx(m)),value:f,children:[a(BA,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(qA,{placeholder:l}),a(GA,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(cx,{})})]}),a(VA,{children:a(zA,{className:n,position:"popper",children:a(ex,{className:p,children:c.map(m=>a(nx,{className:o,disabled:m.disabled,value:xu(m.value),children:[a(rx,{children:m.label}),a(ox,{className:"sync-radix-select-indicator",children:a(lx,{})})]},xu(m.value)))})})})]})}function ux({descriptionId:e,request:t}){const[n,r]=x("choice"),i=t.actors.find(y=>y.isLocal)?.actorId||t.actors[0]?.actorId||"",[o,s]=x(i),[c,l]=x("");K(()=>{r("choice");const y=t.actors.find(_=>_.isLocal)?.actorId||t.actors[0]?.actorId||"",w=t.actors.find(_=>_.actorId!==y)?.actorId||"";s(y),l(w)},[t]);const d=t.actors.find(y=>y.actorId===o)||t.actors[0],u=t.actors.filter(y=>y.actorId!==o),p=u.find(y=>y.actorId===c)||u[0],f=t.actors.map(y=>({label:a(z,{children:[y.label,y.isLocal?" (You)":""]}),value:y.actorId})),m=u.map(y=>({label:`${y.label}${y.isLocal?" (You)":""}`,value:y.actorId})),v=!!(d?.actorId&&p?.actorId),g=()=>{!d?.actorId||!p?.actorId||er({action:"merge",primaryActorId:d.actorId,secondaryActorId:p.actorId})},h=y=>{const w=y.target instanceof HTMLElement?y.target:null;y.defaultPrevented||y.isComposing||y.key!=="Enter"||w?.closest(".sync-dialog-radio-list")&&v&&(y.preventDefault(),g())};return n==="choice"?a("div",{className:"sync-dialog-stack",children:a("ul",{className:"sync-dialog-choice-list",children:[a("li",{children:a("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>er({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>er({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:y=>{h(y),Ni(y,{onSubmit:g,disabled:!v})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(RA,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:o,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:s,options:f,rootClassName:"sync-dialog-radio-list",value:o}),a("div",{className:"field",children:[a("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),a(nr,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:l,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:p?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),a("div",{className:"sync-dialog-actions",children:[a("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),a("button",{className:"settings-button","data-primary-action":"true",disabled:!v,onClick:g,type:"button",children:"Combine people"})]})]})}function px({descriptionId:e,request:t,titleId:n}){const[r,i]=x(t.kind==="input"&&t.initialValue||""),[o,s]=x(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";K(()=>{t.kind==="input"&&(i(t.initialValue||""),s(null))},[t]);const d=c&&t.cancelLabel||"Cancel",u=c?t.confirmLabel||(t.kind==="confirm"?"Confirm":"Save"):"Confirm",p=()=>{if(t.kind==="confirm"){er(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}er(f)};return a("div",{className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:n,children:t.title}),a(ui,{ariaLabel:`Close ${t.title}`,onClick:()=>er(t.kind==="confirm"?!1:null)})]}),a("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?a("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?a("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?a("div",{className:"field",children:[t.suggestions?.length?a(oA,{"aria-describedby":o?`${e} ${l}`:e,autoFocus:!0,className:o?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:f=>{i(f),o&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):a(ke,{"aria-describedby":o?`${e} ${l}`:e,autoFocus:!0,className:o?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:f=>{i(f.currentTarget.value),o&&s(null)},onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),o?a("div",{className:"sync-field-hint",id:l,children:o}):null]}):null,t.kind==="duplicate-person"?a(ux,{descriptionId:e,request:t}):null]}),a("div",{className:"modal-footer",children:[a("div",{className:"small"}),a("div",{className:"sync-dialog-actions",children:[a("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>er(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${iA(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function fx(){const[e,t]=x(tA());K(()=>(fy(t),()=>{nA(t)&&fy(null)}),[]);const n=!!e,r=Re(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Re(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(Rr,{ariaDescribedby:i,ariaLabelledby:r,contentClassName:"modal",contentId:"syncDialog",onInteractOutside:l=>{const d=l.detail?.originalEvent?.target;d instanceof Element&&d.closest(".autocomplete-popover")&&l.preventDefault()},onOpenAutoFocus:l=>{const d=document.querySelector('#syncDialog [data-sync-primary-action="true"]');if(e?.kind==="input"&&d){l.preventDefault(),d.focus();return}const u=(e?.kind==="confirm"?e.autoFocusAction??"confirm":"confirm")==="cancel"?'#syncDialog [data-sync-dialog-action="cancel"]':'#syncDialog [data-sync-dialog-action="confirm"]',p=document.querySelector(u);p&&(l.preventDefault(),p.focus())},onOpenChange:l=>{l||er(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(px,{descriptionId:i,request:e,titleId:r}):null}):null}var Fr=null;function ic(){Fr?.isConnected||(Fr=document.getElementById("syncDialogMount"),Fr||(Fr=document.createElement("div"),Fr.id="syncDialogMount",document.body.appendChild(Fr)),We(a(fx,{}),Fr))}function pn(e){return ic(),Cu("confirm")?new Promise(t=>{Su(n=>t(!!n)),Qs({kind:"confirm",...e})}):Promise.resolve(!1)}function Du(e){return ic(),Cu("input")?new Promise(t=>{Su(n=>t(typeof n=="string"?n:null)),Qs({kind:"input",...e})}):Promise.resolve(null)}function mx(e){return ic(),Cu("duplicate-person")?new Promise(t=>{Su(n=>t(n||{action:"cancel"})),Qs({kind:"duplicate-person",...e})}):Promise.resolve(rA({kind:"duplicate-person",...e}))}function hx(e){return e.readiness==="ready"?null:"Legacy Space management needs the coordinator URL, target group, and admin secret before it can list Spaces or change transport memberships."}function gx(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Ny(e){const t=String(e.label||"").trim()||"Untitled Space",n=gx(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",o=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Space ID ${i} · Membership epoch ${o}`}}function vx(e){const t={active:"Space access active",revoked:"Space access revoked",not_member:"No Space access"},n=e.role.replaceAll("_"," "),r=e.status==="not_member"?t[e.status]:`${t[e.status]} · ${n}`,i=e.membershipEpoch==null?"—":String(e.membershipEpoch);return{statusLabel:t[e.status],detail:r,advancedDetail:`Device ID ${e.deviceId} · Membership epoch ${i}`}}function yx(e,t,n){return`Revoke ${t||"this device"} from ${Ny(e).title}?`}function bx(e,t,n=Es()){const r=As(e,n),i=new Map(t.map(o=>[String(o.device_id||"").trim(),o]).filter(([o])=>o.length>0));return e.map(o=>{const s=String(o.device_id||"").trim();if(!s)return null;const c=i.get(s),l=String(c?.status||"").trim(),d=c?l==="revoked"?"revoked":"active":"not_member",u=typeof c?.membership_epoch=="number"&&Number.isFinite(c.membership_epoch)?Math.trunc(c.membership_epoch):null;return{deviceId:s,displayName:r.get(s)||"Unnamed device",enabled:o.enabled!==!1&&o.enabled!==0,status:d,role:String(c?.role||"member"),membershipEpoch:u,updatedAt:c?.updated_at?String(c.updated_at):null}}).filter(o=>o!==null).sort((o,s)=>{const c={active:0,revoked:1,not_member:2};return c[o.status]-c[s.status]||o.displayName.localeCompare(s.displayName,void 0,{numeric:!0})})}function _x(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(o=>String(o.group_id||"").trim()===i)}var EU=8;function wx(){return{loaded:!1,loading:!1,availability:"unknown",error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,memberAvailabilityByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:"",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1}}function oc(e){if(!e||typeof e!="object")throw new Error("Invalid list payload");const t=e.items;if(!Array.isArray(t))throw new Error("Invalid list payload");return t}function Ue(e){let t=N.groupScopeManagementDrafts.get(e);return t||(t=wx(),N.groupScopeManagementDrafts.set(e,t)),t}function Ve(e,t){N.groupScopeManagementDrafts.set(e,t)}function $u(e,t){const n=e instanceof Error?e.message:"";return n.includes("group_archived")||n.includes("Group is archived")?"Restore this legacy coordinator group before changing Space access.":n.includes("group_not_found")||n.includes("Group not found")?"This legacy coordinator group no longer exists. Refresh Advanced administration.":n.includes("scope_not_found")||n.includes("Scope not found")?"This Space no longer exists. Refresh legacy Spaces before retrying.":n.includes("scope_not_active")||n.includes("Scope is not active")?"Restore this legacy Space before changing its access.":n.includes("scopeId already exists")?"A Space already uses that ID. Choose a different Space ID or refresh legacy Spaces. Sharing policy is unchanged.":n.includes("device_not_enrolled_for_scope_group")||n.includes("device must be enrolled")?"This device is no longer enrolled in the legacy coordinator group. Refresh devices before retrying.":n.includes("membership_not_found")?"This device no longer has access to the Space. Refresh legacy Spaces.":t}function Jo(){Q("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning")}function Bi(e,t){return e.availability==="fresh"&&!e.loading&&(!t||e.memberAvailabilityByScope.get(t)==="fresh")&&Tn(N.recovery,"status","groups")}async function Sx(e,t,n){const r=new Array(e.length);let i=0;async function o(){for(;i<e.length;){const s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}async function Br(e,t,n=Ue(e).includeInactive){const r=Ue(e),i=r.loadGeneration+1;Ve(e,{...r,loading:!0,error:"",includeInactive:n,loadGeneration:i,recoveryAnnouncement:r.recoveryRetryRequested?r.recoveryAnnouncement:""});const o=()=>N.groupScopeManagementDrafts.get(e)?.loadGeneration===i;t();try{const[l,d]=await Promise.all([OS(e,n),Gf(e,!0)]);if(!o())return;const u=oc(l),p=oc(d),f=await Sx(u.slice(0,8),4,async w=>{const _=String(w.scope_id||"").trim();if(!_)return{scopeId:_,attempted:!0,members:[]};try{return{scopeId:_,attempted:!0,members:oc(await qf(e,_,!0))}}catch{return{scopeId:_,attempted:!0}}});if(!o())return;const m=Ue(e),v=[...f,...u.slice(8).map(w=>({scopeId:String(w.scope_id||"").trim(),attempted:!1}))],g=new Map,h=new Map;for(const w of v){if(!w.scopeId)continue;if(w.members){g.set(w.scopeId,w.members),h.set(w.scopeId,"fresh");continue}const _=m.membersByScope.get(w.scopeId),I=m.memberAvailabilityByScope.get(w.scopeId);_&&(I==="fresh"||I==="stale")?(g.set(w.scopeId,_),h.set(w.scopeId,"stale")):h.set(w.scopeId,w.attempted?"unavailable":"deferred")}const y=v.filter(w=>w.attempted&&w.scopeId&&!w.members).length;Ve(e,{...m,loaded:!0,loading:!1,availability:"fresh",recoveryAnnouncement:y?"":m.recoveryAnnouncement,error:y?`Membership details could not be refreshed for ${y} ${y===1?"Space":"Spaces"}. Successfully loaded Space data remains available.`:"",includeInactive:n,devicesLoaded:!0,scopes:u,devices:p,membersByScope:g,memberAvailabilityByScope:h,actionPendingKey:"",actionPendingKind:""})}catch{if(!o())return;const l=Ue(e),d=l.availability==="fresh"||l.availability==="stale";Ve(e,{...l,availability:d?"stale":"unavailable",loading:!1,recoveryAnnouncement:"",error:d?"Legacy Spaces could not be refreshed. Previously loaded Space and membership details are still shown.":"Legacy Spaces are unavailable. No empty Space list is being assumed."})}if(!o())return;const s=Ue(e);if(s.recoveryRetryRequested&&s.availability==="fresh"&&![...s.memberAvailabilityByScope.values()].some(l=>l==="stale"||l==="unavailable")){const l=[...s.memberAvailabilityByScope.values()].filter(d=>d==="deferred").length;Ve(e,{...s,recoveryAnnouncement:l?`Spaces refreshed. Membership details for ${l} ${l===1?"Space":"Spaces"} can be loaded on demand.`:"Spaces and membership details refreshed.",recoveryFocusPending:!0,recoveryRetryRequested:!1})}else s.recoveryRetryRequested&&Ve(e,{...s,recoveryAnnouncement:"Retry finished, but some Space data still needs attention. Retained details remain unchanged.",recoveryFocusPending:!0,recoveryRetryRequested:!1});t();const c=Ue(e);c.recoveryFocusPending&&(Ve(e,{...c,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coordinatorAdminSpacesStatus-${e}`)?.focus()))}function Lu(e,t){N.groupScopeManagementOpen.add(e),Ue(e),t(),Br(e,t)}function Ey(e,t){N.groupScopeManagementOpen.delete(e),t()}async function Cx(e,t,n){const r=Ue(e);if(!Bi(r)){Jo();return}if(r.actionPendingKey)return;const i=r.loadGeneration,o=N.loadGeneration;Ve(e,{...r,actionPendingKey:`load:${t}`,actionPendingKind:"load"}),n();try{const s=await qf(e,t,!0),c=Ue(e);if(c.loadGeneration!==i||N.loadGeneration!==o||!Bi(c)){c.actionPendingKey===`load:${t}`&&(Ve(e,{...c,actionPendingKey:"",actionPendingKind:""}),n()),Jo();return}const l=new Map(c.membersByScope);l.set(t,oc(s));const d=new Map(c.memberAvailabilityByScope);d.set(t,"fresh"),Ve(e,{...c,membersByScope:l,memberAvailabilityByScope:d,actionPendingKey:"",actionPendingKind:"",error:""})}catch{const s=Ue(e);if(s.loadGeneration!==i)return;const c=new Map(s.memberAvailabilityByScope);c.set(t,s.membersByScope.has(t)?"stale":"unavailable"),Ve(e,{...s,memberAvailabilityByScope:c,actionPendingKey:"",actionPendingKind:"",error:"Membership details could not be loaded. Existing Space data is unchanged."})}n()}async function Ix(e,t){const n=Ue(e);if(!Bi(n)){Jo();return}if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),o=n.createKind.trim()||"team";if(!r||!i){Q("Enter a Space ID and label before creating a Space.","warning");return}Ve(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await MS(e,{scope_id:r,label:i,kind:o});const s=Ue(e);Ve(e,{...s,createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:""}),Q("Space created. Grant devices explicitly before data can sync."),await Br(e,t,s.includeInactive),queueMicrotask(()=>document.getElementById(`coordinatorAdminCreateSpaceTrigger-${e}`)?.focus())}catch(s){Ve(e,{...Ue(e),actionPendingKey:"",actionPendingKind:"",error:$u(s,"Could not create the legacy Space. Sharing policy is unchanged; retry after coordinator recovery.")}),t()}}async function Px(e,t,n,r){const i=Ue(e);if(!Bi(i,t)){Jo();return}const o=`grant:${t}:${n}`;if(!i.actionPendingKey){Ve(e,{...i,actionPendingKey:o,actionPendingKind:"grant",error:""}),r();try{await FS(e,t,{device_id:n,role:"member"});const s=Ue(e);Ve(e,{...s,actionPendingKey:"",actionPendingKind:""}),Q("Device granted access to the Space."),await Br(e,r,s.includeInactive)}catch(s){Ve(e,{...Ue(e),actionPendingKey:"",actionPendingKind:"",error:$u(s,"Could not grant legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),r()}}}async function Rx(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o)return;const s=Ue(e);if(!Bi(s,o)){Jo();return}const c=s.loadGeneration,l=N.loadGeneration;if(!await pn({title:yx(t,r,n),description:"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.",confirmLabel:"Revoke membership",cancelLabel:"Keep membership",tone:"danger"}))return;const d=Ue(e),u=d.scopes.find(m=>String(m.scope_id||"").trim()===o),p=d.membersByScope.get(o)?.find(m=>String(m.device_id||"")===n&&String(m.status||"active")==="active");if(d.loadGeneration!==c||N.loadGeneration!==l||!Bi(d,o)||!u||!p||d.actionPendingKey){Q("Space membership data changed while confirmation was open. Review current access and try again.","warning");return}const f=`revoke:${o}:${n}`;Ve(e,{...d,actionPendingKey:f,actionPendingKind:"revoke",error:""}),i();try{await BS(e,o,n);const m=Ue(e);Ve(e,{...m,actionPendingKey:"",actionPendingKind:""}),Q("Space access revoked. Future sync is blocked for that device."),await Br(e,i,m.includeInactive)}catch(m){Ve(e,{...Ue(e),actionPendingKey:"",actionPendingKind:"",error:$u(m,"Could not revoke legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),i()}}function kx(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=Dt(N.devicesSnapshotTarget)?C.lastCoordinatorAdminDevices:[],c=_x(n.devices,s,e,n.devicesLoaded),l=bx(c,n.membersByScope.get(o)??[],N.unnamedDeviceAliases);return l.length?b("div",{class:"coordinator-admin-scope-member-list"},l.map(d=>{const u=`${n.actionPendingKind}:${o}:${d.deviceId}`,p=n.actionPendingKey===u,f=d.enabled&&d.status!=="active",m=d.status==="active",v=vx(d);return b("div",{class:"coordinator-admin-scope-member-row",key:d.deviceId},b("div",{class:"coordinator-admin-scope-member-copy"},b("strong",null,d.displayName),b("span",null,v.detail),b("details",{class:"coordinator-admin-diagnostics"},b("summary",null,"Diagnostics"),b("span",{class:"peer-meta"},v.advancedDetail)),d.enabled?null:b("span",null,"Device is disabled in this coordinator group.")),b("div",{class:"peer-actions"},f?b("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{Px(e,o,d.deviceId,i)},type:"button"},p&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,m?b("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{Rx(e,t,d.deviceId,d.displayName,i)},type:"button"},p&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):b("div",{class:"peer-submeta coordinator-admin-empty-state",role:"status"},"No devices are enrolled in this coordinator group yet. Enroll a device before granting this Space.")}function Tx(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=Ny(t),c=n.memberAvailabilityByScope.get(o),l=n.actionPendingKey===`load:${o}`,d=c==="stale"||c==="unavailable"||c==="deferred";return b("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:o||s.title},b("div",{class:"peer-title"},b("h5",{class:"coordinator-admin-card-title"},s.title),b("span",{class:"badge actor-badge"},"Legacy Space")),b("div",{class:"peer-submeta"},s.summary),b("details",{class:"coordinator-admin-diagnostics"},b("summary",null,"Diagnostics"),b("div",{class:"peer-meta"},s.advancedDetail)),b("div",{class:"peer-submeta"},"Devices below are enrolled in the coordinator group; only active Space members can sync this transport boundary."),c==="stale"?b("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership refresh failed for this Space. Previously loaded memberships are shown and changes are disabled."):c==="unavailable"?b("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details are unavailable for this Space. No empty membership list is being assumed."):c==="deferred"?b("div",{class:"peer-submeta coordinator-admin-inline-warning",role:"status"},"Membership details were deferred to keep this large Space list bounded. Load them before changing access."):null,d?b("button",{class:"settings-button",disabled:!!n.actionPendingKey,onClick:()=>{Cx(e,o,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:kx(e,t,n,r&&c==="fresh",i))}function ju(e,t,n){const r=[...t.memberAvailabilityByScope.values()].filter(s=>s==="stale"||s==="unavailable").length,i=t.availability==="stale"||t.availability==="unavailable"||r>0,o=()=>{const s=Ue(e);s.loading||s.actionPendingKey||(Ve(e,{...s,recoveryAnnouncement:"Retrying Spaces and membership details…",recoveryRetryRequested:!0}),Br(e,n,s.includeInactive))};return b("div",{"aria-atomic":"true","aria-live":"polite",class:i?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":t.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:`coordinatorAdminSpacesStatus-${e}`,role:"status",tabIndex:-1},i?b(z,null,b("div",{class:"coordinator-admin-legacy-notice-copy"},b("h4",{class:"coordinator-admin-drawer-title"},"Spaces need attention"),t.recoveryAnnouncement?b("p",{class:"peer-submeta"},t.recoveryAnnouncement):null,b("p",{class:"peer-submeta"},t.availability==="unavailable"?"Current Space data could not be loaded. No empty result is being shown, and no data loss is implied.":t.availability==="stale"?"Previously loaded Spaces are shown. Mutations are disabled until a retry succeeds.":`Membership details need recovery for ${r} ${r===1?"Space":"Spaces"}. Successfully loaded Spaces remain current.`)),b("button",{class:"settings-button",disabled:t.loading||!!t.actionPendingKey,onClick:o,type:"button"},t.loading?"Retrying…":"Retry")):t.recoveryAnnouncement)}function Nx(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=N.groupScopeManagementDrafts.get(t);if(!o)return null;const s=hx(r);if(s)return b("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(o.availability==="unavailable")return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),b("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ju(t,o,i));if(!o.loaded)return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),b("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ju(t,o,i),b("div",{"aria-live":"polite",class:"peer-submeta",role:"status"},"Loading Spaces…"));const c=!n||o.availability!=="fresh"||!!o.actionPendingKey||o.loading,l=o.loading||!!o.actionPendingKey,d=`coordinatorAdminCreateSpacePanel-${t}`,u=`coordinatorAdminCreateSpaceTrigger-${t}`,p=`coordinatorAdminCreateSpaceId-${t}`;return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),b("div",{class:"peer-submeta"},"Coordinator groups discover and enroll devices. Spaces are technical transport boundaries here. These controls do not manage policy Team membership or Project access in Sharing."),ju(t,o,i),b(qo,{onOpenChange:f=>{Ve(t,{...Ue(t),createPanelOpen:f}),i(),f&&queueMicrotask(()=>document.getElementById(p)?.focus())},open:o.createPanelOpen},b(z,null,b("div",{class:"section-actions coordinator-admin-space-toolbar"},b("label",{class:"coordinator-admin-inline-filter"},b("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),b(Mi,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:l,onCheckedChange:f=>{Ue(t).actionPendingKey||Br(t,i,f)},thumbClassName:"coordinator-admin-switch-thumb"})),b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:l,onClick:()=>{Ue(t).actionPendingKey||Br(t,i,o.includeInactive)},type:"button"},o.loading?"Refreshing…":"Refresh"),b(Zd,{"aria-controls":d,"aria-expanded":o.createPanelOpen,class:"settings-button coordinator-admin-scope-trigger",id:u,type:"button"},"Create legacy Space"))),b(Go,{"aria-busy":o.actionPendingKind==="create"?"true":"false","aria-labelledby":u,class:"coordinator-admin-create-space-panel",forceMount:!0,id:d},b("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!c&&Ix(t,i)}},b("p",{class:"peer-submeta"},"Create a Space only for legacy transport or recovery. Team membership and Project access stay in Sharing."),b("div",{class:"coordinator-admin-form-grid"},b("label",{class:"coordinator-admin-field"},b("span",null,"Space ID"),b(ke,{class:"peer-scope-input",disabled:c,id:p,onInput:f=>{const m=Ue(t);Ve(t,{...m,createScopeId:String(f.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:o.createScopeId})),b("label",{class:"coordinator-admin-field"},b("span",null,"Label"),b(ke,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=Ue(t);Ve(t,{...m,createLabel:String(f.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:o.createLabel})),b("label",{class:"coordinator-admin-field"},b("span",null,"Kind"),b(ke,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=Ue(t);Ve(t,{...m,createKind:String(f.currentTarget.value||"")})},placeholder:"team",type:"text",value:o.createKind}))),b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:c,type:"submit"},o.actionPendingKind==="create"?"Creating…":"Create Space")))))),o.error?b("div",{"aria-live":"assertive",class:"peer-submeta coordinator-admin-error",role:"alert"},o.error):null,o.scopes.length?b("div",{class:"coordinator-admin-scope-card-list"},o.scopes.map(f=>Tx(t,f,o,n&&o.availability==="fresh"&&!o.loading,i))):b("div",{class:"peer-meta coordinator-admin-empty-state",role:"status"},"No Spaces are defined for this coordinator group yet. Create a Space only for legacy transport or recovery, then grant specific devices. Sharing policy remains separate."))}function Ay(){return b("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},b("title",null,"Chevron"),b("path",{d:"m9 18 6-6-6-6"}))}function Ex(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,loading:!1,availability:"unknown",loadGeneration:0,recoveryAnnouncement:"",recoveryFocusPending:!1,recoveryRetryRequested:!1,saving:!1,error:""}}async function xy(e,t){const n=N.groupPreferencesDrafts.get(e)??Ex(),r=n.loadGeneration+1;N.groupPreferencesDrafts.set(e,{...n,loading:!0,error:"",loadGeneration:r,recoveryAnnouncement:n.recoveryRetryRequested?n.recoveryAnnouncement:""});const i=()=>N.groupPreferencesDrafts.get(e)?.loadGeneration===r;t();try{const s=await HC(e);if(!i())return;const c=N.groupPreferencesDrafts.get(e)??n;N.groupPreferencesDrafts.set(e,{...c,projects_include:Array.isArray(s.projects_include)?[...s.projects_include]:[],projects_exclude:Array.isArray(s.projects_exclude)?[...s.projects_exclude]:[],auto_seed_scope:s.auto_seed_scope,default_space_scope_id:s.default_space_scope_id||"",auto_grant_default_space_on_join:s.auto_grant_default_space_on_join===!0,loaded:!0,loading:!1,availability:"fresh",saving:!1,error:"",recoveryAnnouncement:c.recoveryRetryRequested?"Group defaults refreshed. Current values are available.":c.recoveryAnnouncement,recoveryFocusPending:c.recoveryRetryRequested,recoveryRetryRequested:!1})}catch{if(!i())return;const s=N.groupPreferencesDrafts.get(e)??n,c=s.availability==="fresh"||s.availability==="stale",l=s.recoveryRetryRequested;N.groupPreferencesDrafts.set(e,{...s,loading:!1,availability:c?"stale":"unavailable",recoveryAnnouncement:l?"Retry finished, but group defaults are still unavailable. Retained values remain unchanged.":"",recoveryFocusPending:l,recoveryRetryRequested:!1,error:c?"Legacy group defaults could not be refreshed. Previously loaded values are still shown.":"Legacy group defaults are unavailable. No default values are being assumed."})}t();const o=N.groupPreferencesDrafts.get(e);o?.recoveryFocusPending&&(N.groupPreferencesDrafts.set(e,{...o,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coord-admin-group-defaults-recovery-${e}`)?.focus()))}async function Ou(e,t){N.groupPreferencesOpen.add(e),t(),await xy(e,t)}function ac(e,t){N.groupPreferencesOpen.delete(e),t()}function Dy(e,t){const n=N.groupPreferencesDrafts.get(e);n&&(N.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),xy(e,t))}async function Ax(e,t){const n=N.groupPreferencesDrafts.get(e);if(!n||n.availability!=="fresh"||n.loading||!Tn(N.recovery,"status","groups")||n.saving)return;const r={projects_include:n.projects_include.length>0?[...n.projects_include]:null,projects_exclude:n.projects_exclude.length>0?[...n.projects_exclude]:null,auto_seed_scope:n.auto_seed_scope,default_space_scope_id:n.default_space_scope_id||null,auto_grant_default_space_on_join:n.auto_grant_default_space_on_join};N.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await KC(e,r),Q("Legacy coordinator group defaults saved. Sharing policy and Project access are unchanged."),ac(e,t)}catch{const i=N.groupPreferencesDrafts.get(e);if(!i)return;N.groupPreferencesDrafts.set(e,{...i,saving:!1,error:"Could not save legacy group defaults. Sharing policy is unchanged; retry after coordinator recovery."}),t()}}function xx(e,t,n){const r=N.groupPreferencesDrafts.get(e);if(!r)return null;const i=`coord-admin-group-defaults-recovery-${e}`;if(!r.loaded&&r.availability!=="unavailable")return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),b("div",{"aria-atomic":"true","aria-live":"polite",id:i,role:"status",tabIndex:-1},"Loading project defaults…"));if(r.availability==="unavailable")return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),b("div",{"aria-atomic":"true","aria-live":"polite",class:"coordinator-admin-inline-warning coordinator-admin-recovery-notice",id:i,role:"status",tabIndex:-1},b("div",{class:"coordinator-admin-legacy-notice-copy"},b("strong",null,"Group defaults are unavailable"),r.recoveryAnnouncement?b("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,b("span",{class:"peer-submeta"},"Current values could not be loaded. No defaults are being assumed or changed.")),b("button",{class:"settings-button",disabled:r.loading,onClick:()=>Dy(e,t),type:"button"},r.loading?"Retrying…":"Retry")));const o=`coord-admin-scope-autoseed-${e}`,s=`coord-admin-default-space-autogrant-${e}`,c=`coord-admin-scope-include-${e}`,l=`coord-admin-scope-exclude-${e}`,d=n&&r.availability==="fresh"&&!r.loading,u=!d||r.saving||!r.auto_seed_scope;return b(z,null,b("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),b("div",{"aria-atomic":"true","aria-live":"polite",class:r.availability==="stale"?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":"coordinator-admin-recovery-status",id:i,role:"status",tabIndex:-1},r.availability==="stale"?b(z,null,b("span",{class:"peer-submeta"},"Previously loaded group defaults are shown. Saving is disabled until refresh succeeds."),r.recoveryAnnouncement?b("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,b("button",{class:"settings-button",disabled:r.loading,onClick:()=>Dy(e,t),type:"button"},r.loading?"Retrying…":"Retry")):r.recoveryAnnouncement),b("div",{class:"peer-submeta"},"Space access grants decide what new devices can sync. Advanced sharing rules only narrow future writes after Space access already exists."),b("label",{class:"coordinator-admin-inline-filter"},b("span",{class:"section-meta",id:o},"Auto-apply advanced rules to new devices"),b(Mi,{"aria-labelledby":o,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!d||r.saving,onCheckedChange:p=>{const f=N.groupPreferencesDrafts.get(e)??r;N.groupPreferencesDrafts.set(e,{...f,auto_seed_scope:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),b("label",{class:"coordinator-admin-inline-filter"},b("span",{class:"section-meta",id:s},"Auto-grant default Space on coordinator join"),b(Mi,{"aria-labelledby":s,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!d||r.saving||!r.default_space_scope_id,onCheckedChange:p=>{const f=N.groupPreferencesDrafts.get(e)??r;N.groupPreferencesDrafts.set(e,{...f,auto_grant_default_space_on_join:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?b("div",{class:"peer-submeta"},"Default Space configured."):b("div",{class:"peer-submeta"},"No default Space has been created yet."),b("div",{class:"coordinator-admin-field"},b("span",{id:c},"Include template"),b(cy,{"aria-labelledby":c,availableProjects:N.availableProjects,disabled:u,emptyLabel:"All projects allowed.",onValuesChange:p=>{const f=N.groupPreferencesDrafts.get(e)??r;N.groupPreferencesDrafts.set(e,{...f,projects_include:p}),t()},placeholder:"Add project",values:r.projects_include}),b("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),b("div",{class:"coordinator-admin-field"},b("span",{id:l},"Exclude template"),b(cy,{"aria-labelledby":l,availableProjects:N.availableProjects,disabled:u,emptyLabel:"Nothing excluded.",onValuesChange:p=>{const f=N.groupPreferencesDrafts.get(e)??r;N.groupPreferencesDrafts.set(e,{...f,projects_exclude:p}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?b("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:!d||r.saving,onClick:()=>{Ax(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),b("button",{class:"settings-button",disabled:r.saving,onClick:()=>ac(e,t),type:"button"},"Cancel")))}function Dx(e){const t=N.teamSetupGuide;if(!t)return null;const n=bu(t.groupId,t.displayName),r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return b("div",{class:"peer-meta coordinator-admin-empty-state"},b("h4",{class:"coordinator-admin-drawer-title"},`Set up legacy group ${n}`),b("div",{class:"peer-submeta"},"This coordinator group organizes technical discovery and enrollment. It is not a policy Team; use Sharing to manage Team membership and Project access."),t.setupWarning?b("div",{class:"peer-meta coordinator-admin-inline-warning"},`Legacy coordinator group created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create transport access manually. Sharing policy is unchanged.`):b("div",{class:"peer-submeta"},t.defaultSpaceScopeId?t.defaultSpaceLabel?`Default Space ready: ${t.defaultSpaceLabel}. New devices can receive this Space when auto-grant is enabled.`:"Default Space ready. New devices can receive this Space when auto-grant is enabled.":"Default Space status is unknown. Check Spaces before inviting teammates."),b("ol",{class:"peer-submeta"},b("li",null,"Review legacy group defaults and the auto-grant default Space setting."),b("li",null,"Use legacy enrollment only when compatibility or recovery requires it."),b("li",null,"Open Sharing for Team membership and Project access.")),b("div",{class:"peer-actions"},b("button",{class:"settings-button",onClick:()=>{N.groupPreferencesOpen.add(t.groupId),Ou(t.groupId,e)},type:"button"},"Review legacy defaults"),b("button",{class:"settings-button",onClick:()=>{Lu(t.groupId,e)},type:"button"},"Check Spaces"),b("button",{class:"settings-button",onClick:()=>{N.inviteGroup=t.groupId,N.activeSection="invites",e()},type:"button"},"Create legacy device invite"),b("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Open Projects"),b("button",{class:"settings-button",onClick:()=>{N.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function $x(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function Lx(e){const{summary:t,fresh:n,createGroup:r,runGroup:i,renderShell:o,reloadData:s}=e,c=Dr(N.recovery,"groups"),l=Di(N.recovery,"groups"),d=String(C.lastCoordinatorAdminStatus?.active_group||"").trim(),u=Ln(),p=Zn(),f=p.filter(y=>!y.archived_at),m=p.filter(y=>y.archived_at),v=N.showArchivedGroups?p:f,g=u?p.some(y=>y.group_id===u):!1,h=[`${f.length} active`];return m.length&&h.push(`${m.length} archived`),b(xr,{className:"coordinator-admin-panel",value:"groups"},b("h3",null,"Coordinator groups"),b("p",{class:"peer-submeta"},u?`Managing the selected coordinator group${d&&d!==u?" · this node uses a different group for discovery":""}`:d?`This node uses ${d} for discovery. Select a coordinator group below to manage it.`:"No coordinator group selected yet. Create one or select an existing group to manage."),p.length?b("p",{class:"peer-submeta"},h.join(" · ")):null,!g&&u?b("div",{class:"peer-meta coordinator-admin-inline-warning"},"The selected legacy group is configured locally but does not exist in the coordinator yet. Create it below or switch to another coordinator group once one exists."):null,Dx(o),(()=>{const y=!n||N.groupActionPendingKind==="create";return b("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!y&&r()}},b("div",{class:"peer-meta coordinator-admin-inline-warning",role:"note"},"Creating a coordinator group changes legacy discovery and transport setup only. It does not create a policy Team or grant Project access in Sharing."),b("div",{class:"coordinator-admin-form-grid"},b("label",{class:"coordinator-admin-field"},b("span",null,"New coordinator group ID"),b(ke,{class:"peer-scope-input",disabled:y,onInput:w=>{N.createGroupId=String(w.currentTarget.value||"")},placeholder:"group-alpha",type:"text",value:N.createGroupId})),b("label",{class:"coordinator-admin-field"},b("span",null,"Legacy group display name"),b(ke,{class:"peer-scope-input",disabled:y,onInput:w=>{N.createGroupDisplayName=String(w.currentTarget.value||"")},placeholder:"Legacy group Alpha",type:"text",value:N.createGroupDisplayName}))),b("div",{class:"section-actions coordinator-admin-groups-toolbar"},b("div",{class:"coordinator-admin-primary-actions"},b("button",{class:"settings-button",disabled:y,type:"submit"},N.groupActionPendingKind==="create"?"Creating…":"Create coordinator group")),b("div",{class:"coordinator-admin-secondary-actions"},b("label",{class:"coordinator-admin-inline-filter"},b("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),b(Mi,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:N.showArchivedGroups,className:"coordinator-admin-switch",onCheckedChange:w=>{N.showArchivedGroups=w,o()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),l?b("div",{class:"peer-meta"},"Complete legacy coordinator setup before loading coordinator groups. No group list is expected yet."):c?v.length?b("div",{class:"peer-list"},v.map(y=>{const w=y.group_id===u,_=N.groupActionPendingId===y.group_id,I=!!y.archived_at,P=N.groupRenameDrafts.get(y.group_id)??y.display_name??"",k=P.trim()||bu(y.group_id,y.display_name),A=N.groupPreferencesOpen.has(y.group_id),L=N.groupScopeManagementOpen.has(y.group_id),F=I?"unarchive":"archive",T=$x(I,_&&N.groupActionPendingKind===F),M=eA({groupId:y.group_id,preferences:N.groupPreferencesDrafts.get(y.group_id),scopeManagement:N.groupScopeManagementDrafts.get(y.group_id),setupGuide:N.teamSetupGuide});return b("div",{class:"peer-card peer-card--padded",key:y.group_id},b("div",{class:"peer-title"},b("strong",null,k)),b("div",{class:"peer-submeta"},I?"Archived coordinator group":"Active coordinator group"),b("details",{class:"coordinator-admin-diagnostics"},b("summary",null,"Diagnostics"),b("div",{class:"peer-meta"},`Group ID ${y.group_id}`)),b("div",{class:"coordinator-admin-summary-grid"},b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Default Space"),b("strong",null,M.defaultSpace)),b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Auto-grant"),b("strong",null,M.autoGrant)),b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Spaces"),b("strong",null,M.spaces))),d===y.group_id?b("div",{class:"peer-submeta"},"This node uses this coordinator group for discovery."):null,b("label",{class:"coordinator-admin-field"},b("span",null,"Legacy group display name"),b(ke,{class:"peer-scope-input",disabled:!n||_,onInput:j=>{N.groupRenameDrafts.set(y.group_id,String(j.currentTarget.value||""))},type:"text",value:P})),b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:!n||w,onClick:()=>{yu(y.group_id),s()},type:"button"},w?"Managing":"Manage group"),b("button",{class:"settings-button",disabled:!n||_,onClick:()=>i(y.group_id,P,"rename"),type:"button"},_&&N.groupActionPendingKind==="rename"?"Renaming…":"Rename group"),b("button",{"aria-expanded":A,"aria-controls":`coord-admin-project-defaults-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":A?"open":"closed",disabled:_,onClick:()=>{A?ac(y.group_id,o):Ou(y.group_id,o)},type:"button"},b("span",null,"Legacy group defaults"),b("span",{"aria-hidden":"true",class:"device-row-chevron"},b(Ay,null))),b("button",{"aria-expanded":L,"aria-controls":`coord-admin-spaces-drawer-${y.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":L?"open":"closed",disabled:_,onClick:()=>{L?Ey(y.group_id,o):Lu(y.group_id,o)},type:"button"},b("span",null,"Spaces & access"),b("span",{"aria-hidden":"true",class:"device-row-chevron"},b(Ay,null))),b("button",{class:I?"settings-button":"settings-button danger",disabled:!n||_,onClick:()=>i(y.group_id,y.display_name||y.group_id,F),type:"button"},T)),b(qo,{open:A,onOpenChange:j=>{j?Ou(y.group_id,o):ac(y.group_id,o)}},b(Go,{"aria-label":`Project defaults for ${k}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${y.group_id}`},A?xx(y.group_id,o,n):null)),b(qo,{open:L,onOpenChange:j=>{j?Lu(y.group_id,o):Ey(y.group_id,o)}},b(Go,{"aria-label":`Spaces for ${k}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${y.group_id}`},L?Nx({groupId:y.group_id,ready:n,renderShell:o,summary:t}):null)))})):b("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?N.showArchivedGroups?"No coordinator groups are available yet.":"No active coordinator groups yet. Create one only for legacy discovery or recovery.":"Coordinator group browsing will appear here once setup is complete."):b("div",{class:"peer-meta coordinator-admin-empty-state"},"Coordinator groups are unavailable. Retry to load current groups; no empty result is being assumed."))}function Ui(e){return a("textarea",{...e})}function jx(e){const{summary:t,fresh:n,createInvite:r,renderShell:i}=e,o=C.lastCoordinatorAdminStatus,s=Ln()||String(o?.active_group||"").trim(),c=N.inviteGroup.trim()||s,l=String(C.lastTeamInvite?.encoded||"").trim(),d=Array.isArray(C.lastTeamInvite?.warnings)?C.lastTeamInvite?.warnings:[],u=!n||N.invitePending;return b(xr,{className:"coordinator-admin-panel",value:"invites"},b("h3",null,"Legacy coordinator invites"),b("p",{class:"peer-submeta"},n?"Legacy coordinator invites enroll a device in the selected group for discovery. They do not add policy Team membership or grant Project access; use Sharing for both.":t.readiness==="ready"?"Legacy invite creation is disabled until current coordinator status and group data are available. Previously generated invites remain available to copy.":"Finish coordinator setup first. Legacy invite creation stays disabled until the local configuration is ready."),b("form",{class:"coordinator-admin-form",onSubmit:p=>{p.preventDefault(),!u&&r()}},b("div",{class:"coordinator-admin-form-grid"},b("label",{class:"coordinator-admin-field"},b("span",null,"Coordinator group"),b(ke,{class:"peer-scope-input",disabled:!n,onInput:p=>{N.inviteGroup=String(p.currentTarget.value||""),i()},placeholder:s||"group-alpha",type:"text",value:N.inviteGroup})),b("label",{class:"coordinator-admin-field"},b("span",null,"Join policy"),b(nr,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:!n,id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:p=>{N.invitePolicy=p==="approval_required"?"approval_required":"auto_admit",i()},options:[{value:"auto_admit",label:"Auto-admit to coordinator group"},{value:"approval_required",label:"Require approval to join group"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:N.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),b("label",{class:"coordinator-admin-field"},b("span",null,"Expires in (hours)"),b(ke,{class:"peer-scope-input",disabled:!n,min:"1",onInput:p=>{N.inviteTtlHours=String(p.currentTarget.value||"")},type:"number",value:N.inviteTtlHours}))),b("div",{class:"section-actions"},b("button",{class:"settings-button",disabled:u,type:"submit"},N.invitePending?"Creating…":"Create legacy coordinator invite"),c?b("span",{class:"peer-submeta"},"Using the selected coordinator group"):null)),l?b("label",{class:"coordinator-admin-field"},b("span",null,"Generated invite"),b(Ui,{class:"feed-search coordinator-admin-output",readOnly:!0,value:l}),b("button",{class:"settings-button sync-action-copy",type:"button",onClick:p=>Oo(l,p.currentTarget)},"Copy")):null,d?.length?b("div",{class:"peer-meta coordinator-admin-warning-list"},d.join(" · ")):null,b("h3",null,"Project sharing operations"),b("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),C.lastShareOperations.length>0?b("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...C.lastShareOperations.map(p=>b("li",{key:p.operation_id},b("strong",null,p.person.display_name),b("span",null,` — ${p.projects.map(f=>f.display_name).join(", ")} — ${p.lifecycle.label}`)))):b("div",{class:"peer-meta"},"No project sharing operations yet."))}function Ox(e){const{summary:t,fresh:n,reviewJoinRequest:r,snapshotMatchesTarget:i}=e,o=i&&Dr(N.recovery,"joinRequests"),s=Di(N.recovery,"joinRequests"),c=o&&Array.isArray(C.lastCoordinatorAdminJoinRequests)?C.lastCoordinatorAdminJoinRequests:[],l=c.map(u=>({device_id:String(u.device_id||"").trim()||`join-request:${String(u.request_id||"").trim()}`,display_name:u.display_name})),d=As(l,N.unnamedDeviceAliases);return b(xr,{className:"coordinator-admin-panel",value:"join-requests"},b("h3",null,"Pending join requests"),b("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this legacy coordinator group. Space transport access is handled by legacy group defaults and can be reviewed in Spaces; Sharing policy is separate.":"Finish coordinator setup first. Join request review stays disabled until legacy administration is ready."),s?b("div",{class:"peer-meta"},"Complete legacy coordinator setup to load join requests. No join queue is expected yet."):o?c.length?b("div",{class:"peer-list"},c.map(u=>{const p=String(u.request_id||"").trim(),f=String(u.device_id||"").trim(),m=f||`join-request:${p}`,v=d.get(m)||"Unnamed device",g=String(u.fingerprint||"").trim(),h=[`Device ID ${f||"unknown"}`];g&&h.push(`Fingerprint ${g}`);const y=N.joinReviewPendingId===p;return b("div",{class:"peer-card peer-card--padded",key:p||f},b("div",{class:"peer-title"},b("strong",null,v)),b("details",{class:"coordinator-admin-diagnostics"},b("summary",null,"Diagnostics"),b("div",{class:"peer-meta"},`Advanced: ${h.join(" · ")}`)),b("div",{class:"peer-actions"},b("button",{class:"settings-button",disabled:!n||!p||y,onClick:()=>r(p,"approve"),type:"button"},y&&N.joinReviewPendingAction==="approve"?"Approving…":"Approve"),b("button",{class:"settings-button danger",disabled:!n||!p||y,onClick:()=>r(p,"deny"),type:"button"},y&&N.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):b("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."):b("div",{class:"peer-meta"},"Join requests are unavailable. Retry to load the current queue; no empty result is being assumed."))}var Mx=new Map([["display_name_required","Enter a device name before renaming it."],["display_name_invalid","Enter a valid device name and retry."],["display_name_too_long","The device name is too long. Use a shorter name and retry."]]);function Fx(e){const t=e instanceof Error?e.message:"";return t.includes("group_archived")||t.includes("Group is archived")?"This legacy coordinator group is archived. Choose an active group or refresh coordinator groups.":t.includes("group_not_found")||t.includes("Group not found")?"This legacy coordinator group no longer exists. Choose an active group or refresh coordinator groups.":"Could not create the legacy coordinator invite. Sharing policy is unchanged; check coordinator recovery status and retry."}function Bx(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function Ux(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function qx(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function Gx(e){const{renderShell:t,reloadData:n}=e,r=(...d)=>Tn(N.recovery,...d)?!0:(Q("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning"),!1);async function i(){if(!r("status","groups")||N.groupActionPendingKind)return;const d=$n(C.lastCoordinatorAdminStatus?.coordinator_url),u=N.createGroupId.trim();if(!u){Q("Enter a coordinator group ID before creating a legacy group.","warning");return}const p=N.createGroupDisplayName.trim();N.groupActionPendingKind="create",t();try{const f=await DS({group_id:u,display_name:p||null});if($n(C.lastCoordinatorAdminStatus?.coordinator_url)!==d)return;const m=f.default_space,v=(m&&"scope"in m?m.scope:m)??{},g=m&&"preferences"in m?m.preferences:null,h=String(v?.scope_id||"");N.createGroupId="",N.createGroupDisplayName="",N.teamSetupGuide={groupId:u,displayName:String(f.group?.display_name||p||""),defaultSpaceScopeId:h,defaultSpaceLabel:String(v?.label||""),autoGrantDefaultSpaceOnJoin:typeof g?.auto_grant_default_space_on_join=="boolean"?g.auto_grant_default_space_on_join:null,setupWarning:f.setup_warning||null};try{await n(),yu(u),await n()}catch{Q("Legacy coordinator group created, but coordinator data could not refresh. Check coordinator recovery status before retrying.","warning");return}f.setup_warning?Q("Legacy coordinator group created, but default Space setup needs repair. Sharing policy is unchanged.","warning"):h?Q("Legacy coordinator group created with a default Space. Sharing policy is unchanged.","success"):Q("Legacy coordinator group created, but default Space status is unknown. Sharing policy is unchanged.","warning")}catch{Q("Could not create the legacy coordinator group. No Sharing policy or Project access changed; check coordinator recovery status and retry.","warning")}finally{N.groupActionPendingKind="",t()}}async function o(d,u,p){if(!r("status","groups")||!d||N.groupActionPendingId)return;const f=u.trim();if(p==="rename"&&!f){Q("Enter a legacy group display name before renaming it.","warning");return}const m=C.lastCoordinatorAdminGroups.find(w=>w.group_id===d),v=bu(d,m?.display_name),g=Ys();if(!await pn({title:p==="rename"?`Rename ${v}?`:`${p==="archive"?"Archive":"Unarchive"} ${v}?`,description:p==="rename"?`Target: ${v}. New name: ${f}. This renames the technical coordinator group only. It does not rename a policy Team or change membership or Project access in Sharing.`:p==="archive"?`Target: ${v}. The group stays visible and restorable, but coordinator presence, peer discovery, Space grants, legacy invites, and joins stop. Archiving also removes this group from this device's local coordinator configuration. Policy Team membership and Project access in Sharing are separate and unchanged.`:`Target: ${v}. This reactivates the remote coordinator group for devices still configured for it. It does not re-add this group to this device's local coordinator configuration; restore that separately before expecting coordinator presence or peer discovery here. It does not restore or change policy Team membership or Project access in Sharing.`,confirmLabel:p==="rename"?"Rename coordinator group":p==="archive"?"Archive coordinator group":"Unarchive coordinator group",cancelLabel:p==="rename"?"Keep current group name":p==="archive"?"Keep group active":"Keep group archived",tone:p==="archive"?"danger":"default"}))return;if(!Dt(g)){Q("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}if(!Tn(N.recovery,"status","groups")){Q("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const h=C.lastCoordinatorAdminGroups.find(w=>String(w.group_id||"")===d);if(!h||N.groupActionPendingId){Q("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const y=N.groupRenameDrafts.get(d)??String(h.display_name||"");N.groupActionPendingId=d,N.groupActionPendingKind=p,t();try{const w=p==="rename"?"renamed":p==="archive"?"archived":"unarchived";p==="rename"&&await $S(d,y),p==="archive"&&await LS(d),p==="unarchive"&&await jS(d);try{await n()}catch{Q(`Legacy coordinator group ${w}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Q(p==="rename"?"Legacy coordinator group renamed. Sharing Team names are unchanged.":p==="archive"?"Legacy coordinator group archived. Sharing policy is unchanged.":"Legacy coordinator group unarchived. This device's local coordinator configuration and Sharing policy are unchanged.","success")}catch(w){if(Ux(w))try{await n(),Q("This legacy coordinator group changed or no longer exists. Coordinator groups were refreshed.","warning")}catch{Q("This legacy coordinator group changed or no longer exists. Refresh coordinator groups before trying another action.","warning")}else Q(`Could not ${p} the legacy coordinator group. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{N.groupActionPendingId="",N.groupActionPendingKind="",t()}}async function s(){if(!r("status","groups")||N.invitePending)return;const d=C.lastCoordinatorAdminStatus,u=$n(d?.coordinator_url),p=Ln()||String(d?.active_group||"").trim(),f=N.inviteGroup.trim()||p,m=Number(N.inviteTtlHours);if(!f){Q("Choose a coordinator group before creating a legacy invite.","warning");return}if(!Number.isFinite(m)||m<1){Q("Invite lifetime must be at least 1 hour.","warning");return}N.invitePending=!0,t();try{const v=await Hf({group_id:f,policy:N.invitePolicy,ttl_hours:m}),g=C.lastCoordinatorAdminStatus,h=Ln()||String(g?.active_group||"").trim(),y=N.inviteGroup.trim()||h;if($n(g?.coordinator_url)!==u||y!==f)return;C.lastTeamInvite=v,N.inviteGroup=f;const w=Array.isArray(v.warnings)?v.warnings:[];Q(w.length?`Invite created. Review ${w.length===1?"the warning":`${w.length} warnings`} before sharing it.`:"Legacy coordinator invite created. It does not grant Sharing Project access.",w.length?"warning":"success")}catch(v){Q(Fx(v),"warning")}finally{N.invitePending=!1,t()}}async function c(d,u){if(!Dt(N.joinRequestsSnapshotTarget)||!r("status","joinRequests")||N.joinReviewPendingId)return;const p=N.joinRequestsSnapshotTarget;N.joinReviewPendingId=d,N.joinReviewPendingAction=u,t();try{const f=await qS(d,u);if(!Dt(p))return;try{await n()}catch{Q(`Join request ${u==="approve"?"approved":"denied"}, but pending requests could not refresh. Check coordinator recovery status before reviewing another request.`,"warning");return}u==="approve"&&f.setup_warning?Q("Join request approved, but default Space access needs repair.","warning"):Q(u==="approve"?"Join request approved.":"Join request denied.","success")}catch(f){if(!Dt(p))return;if(Bx(f))try{await n(),Q("This legacy coordinator join request no longer exists. Pending requests were refreshed.","warning")}catch{Q("This legacy coordinator join request no longer exists. Refresh pending requests before reviewing another request.","warning")}else Q("Could not review the legacy coordinator join request. Sharing policy is unchanged; check coordinator recovery status and retry.","warning")}finally{N.joinReviewPendingId="",N.joinReviewPendingAction="",t()}}async function l(d,u,p,f){if(Dt(N.devicesSnapshotTarget)&&r("status","devices")&&!(!d||N.deviceActionPendingId)){if(f==="disable"||f==="remove"){const m=Ys();if(!await pn({title:`${f==="disable"?"Disable":"Remove"} ${p||"this device"}?`,description:f==="disable"?"This device will stay enrolled but can no longer participate until you re-enable it.":"This removes the enrolled device record from the coordinator. The teammate would need a fresh invite or re-enrollment path to come back.",confirmLabel:f==="disable"?"Disable device":"Remove device",cancelLabel:f==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))return;if(!Dt(m)){Q("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!Tn(N.recovery,"status","devices")){Q("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!C.lastCoordinatorAdminDevices.find(v=>String(v.device_id||"")===d&&String(v.group_id||"")===u)||N.deviceActionPendingId){Q("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}}N.deviceActionPendingId=d,N.deviceActionPendingKind=f,t();try{const m=f==="rename"?"renamed":f==="disable"?"disabled":f==="enable"?"enabled":"removed";if(f==="rename"){const v=String(N.deviceRenameDrafts.get(d)||"").trim();if(!v){Q("Enter a device name before renaming it.","warning");return}await GS(d,u,v)}f==="disable"&&await HS(d,u),f==="enable"&&await KS(d,u),f==="remove"&&await VS(d,u);try{await n()}catch{Q(`Device ${m}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Q(`Device ${m}.`,"success")}catch(m){const v=f==="rename"&&m instanceof Error?Mx.get(m.message.trim()):void 0;if(qx(m))try{await n(),Q("This legacy coordinator device no longer exists. Enrolled devices were refreshed.","warning")}catch{Q("This legacy coordinator device no longer exists. Refresh enrolled devices before trying another action.","warning")}else Q(v||`Could not ${f} the legacy coordinator device. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{N.deviceActionPendingId="",N.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:i,runGroupAction:o,createInviteFromAdminPanel:s,reviewJoinRequestFromAdminPanel:c,runDeviceAction:l}}function Hx(){C.lastCoordinatorAdminGroups=[],C.lastCoordinatorAdminJoinRequests=[],C.lastCoordinatorAdminDevices=[],C.lastTeamInvite=null,C.coordinatorAdminTargetGroup="",cn(N.recovery,"groups",!1),cn(N.recovery,"joinRequests",!1),cn(N.recovery,"devices",!1),N.joinRequestsSnapshotTarget=null,N.devicesSnapshotTarget=null,N.groupRenameDrafts.clear(),N.groupPresentationAliases.clear(),N.deviceRenameDrafts.clear(),N.deviceRenameServerNames.clear(),N.groupPreferencesOpen.clear(),N.groupPreferencesDrafts.clear(),N.groupScopeManagementOpen.clear(),N.groupScopeManagementDrafts.clear(),N.inviteGroup="",N.teamSetupGuide=null}function Kx(){const e=kv();return Bo(N.recovery,"status"),Wd(N.recovery,"groups"),Wd(N.recovery,"joinRequests"),Wd(N.recovery,"devices"),e}async function $y(e){try{const t=await ul();if(!Yd(e))return"superseded";if(!t||typeof t!="object")throw new Error("Invalid status payload");const n=C.lastCoordinatorAdminStatus;return $n(n?.coordinator_url)!==$n(t.coordinator_url)&&Hx(),C.lastCoordinatorAdminStatus=t,Ds(N.recovery,"status"),"fresh"}catch{return Yd(e)?(cn(N.recovery,"status"),"failed"):"superseded"}}function Vx(){const e=C.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Legacy coordinator administration is ready",detail:"This viewer can manage legacy coordinator groups, invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Legacy coordinator setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using legacy invite and device actions.":"Finish configuring the coordinator target and group before using legacy administration actions."}:{readiness:"not_configured",title:"Legacy coordinator administration is not configured",detail:"Set a coordinator URL, group, and admin secret locally to enable remote coordinator administration from this viewer."}:N.recovery.status.availability==="unavailable"?{readiness:"partial",title:"Legacy coordinator status is unavailable",detail:"Current coordinator readiness could not be loaded. Retry before using legacy administration actions."}:{readiness:"partial",title:"Checking legacy coordinator readiness…",detail:"Loading local coordinator administration configuration from the viewer server."}}var{createGroupFromAdminPanel:zx,runGroupAction:Wx,createInviteFromAdminPanel:Jx,reviewJoinRequestFromAdminPanel:Yx,runDeviceAction:Xx}=Gx({renderShell:()=>Ur(),reloadData:()=>sc()});function Ur(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=C.lastCoordinatorAdminStatus,n=Vx(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!zE()?.archived_at,c=Tn(N.recovery,"status","groups"),l=c&&!s,d=Dt(N.joinRequestsSnapshotTarget),u=Dt(N.devicesSnapshotTarget),p=Tn(N.recovery,"status","joinRequests")&&d,f=Tn(N.recovery,"status","devices")&&u,m=Ln(),v=Zn().filter(M=>!M.archived_at).length,g=Zn().filter(M=>M.archived_at).length,h=d&&Array.isArray(C.lastCoordinatorAdminJoinRequests)?C.lastCoordinatorAdminJoinRequests.length:0,y=u&&Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices.length:0,w=n.readiness!=="ready"?n.detail:s?"The selected coordinator group is archived. Restore it or switch groups before creating legacy invites.":"",_=Rv(N.recovery),I=Dr(N.recovery,"status"),P=Dr(N.recovery,"groups"),k=d&&Dr(N.recovery,"joinRequests"),A=u&&Dr(N.recovery,"devices"),L=Di(N.recovery,"groups"),F=Di(N.recovery,"joinRequests"),T=Di(N.recovery,"devices");We(b("div",{class:"coordinator-admin-shell"},b("div",{class:"card coordinator-admin-header"},b("div",{class:"section-header"},b("h2",null,"Legacy coordinator administration")),b("div",{"aria-atomic":"true","aria-live":"polite",class:_?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":N.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:"coordinatorAdminRecoveryStatus",role:"status",tabIndex:-1},_?b(z,null,b("div",{class:"coordinator-admin-legacy-notice-copy"},b("h3",null,"Advanced coordinator data needs attention"),N.recoveryAnnouncement?b("p",{class:"peer-submeta"},N.recoveryAnnouncement):null,_.stale.length?b("p",{class:"peer-submeta"},`Stale: ${_.stale.join(", ")}. Previously loaded data is still shown.`):null,_.unavailable.length?b("p",{class:"peer-submeta"},`Unavailable: ${_.unavailable.join(", ")}. No current data is shown for ${_.unavailable.length===1?"that surface":"those surfaces"}.`):null,b("p",{class:"peer-submeta"},"Actions that depend on current coordinator data are disabled. This does not mean coordinator data was deleted.")),b("button",{class:"settings-button",disabled:_.retrying,onClick:()=>{N.recoveryAnnouncement="Retrying coordinator data…",N.recoveryRetryRequested=!0,sc()},type:"button"},_.retrying?"Retrying…":"Retry")):N.recoveryAnnouncement),b("div",{class:"coordinator-admin-summary-grid"},b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Coordinator group target"),b("strong",null,I||P?m||"None selected":"Unavailable")),b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Node discovery group"),b("strong",null,I?i||"None":"Unavailable")),b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Coordinator groups"),b("strong",null,P?`${v} active${g?` · ${g} archived`:""}`:L?"Setup required":"Unavailable")),b("div",{class:"coordinator-admin-summary-card"},b("span",{class:"section-meta"},"Selected group activity"),b("strong",null,`${k?h:F?"Setup required":"Unavailable"} join requests · ${A?y:T?"Setup required":"Unavailable"} devices`))),w?b("div",{class:"peer-meta coordinator-admin-inline-warning"},w):null,r?b("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),b("div",{class:"card coordinator-admin-sections"},b(Cv,{ariaLabel:"Legacy coordinator administration sections",listClassName:"coordinator-admin-tabs-list",onValueChange:M=>{N.activeSection=M||"groups",Ur()},tabs:[{value:"groups",label:"Coordinator groups"},{value:"invites",label:"Invites"},{value:"join-requests",label:"Join requests"},{value:"devices",label:"Devices"}],triggerClassName:"coordinator-admin-tab-trigger",value:N.activeSection},Lx({summary:n,fresh:c,createGroup:()=>{zx()},runGroup:(M,j,B)=>{Wx(M,j,B)},renderShell:Ur,reloadData:()=>{sc()}}),jx({summary:n,fresh:l,createInvite:()=>{Jx()},renderShell:Ur}),Ox({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(M,j)=>{Yx(M,j)}}),qT({summary:n,fresh:f,snapshotMatchesTarget:u,runDevice:(M,j,B,U)=>{Xx(M,j,B,U)}})),b("div",{class:"section-meta coordinator-admin-context-line"},s?"The selected coordinator group is archived. Switch or restore it to enable legacy invite operations.":m?"Actions below apply to the selected coordinator group.":"Select a coordinator group to manage legacy enrollment and Spaces."))),e),N.recoveryFocusPending&&(N.recoveryFocusPending=!1,queueMicrotask(()=>document.getElementById("coordinatorAdminRecoveryStatus")?.focus()))}function Qx(){Ur()}async function sc(){const e=kv(),t=()=>Yd(e);if(N.recoveryRetryRequested||(N.recoveryAnnouncement=""),Bo(N.recovery,"status"),Bo(N.recovery,"groups"),Bo(N.recovery,"joinRequests"),Bo(N.recovery,"devices"),Ur(),await $y(e)==="superseded")return;const n=String(C.lastCoordinatorAdminStatus?.active_group||"").trim();if(py(),C.lastCoordinatorAdminStatus?.readiness==="ready"&&Tn(N.recovery,"status")){try{const o=await lm();if(!t())return;C.lastShareOperations=Array.isArray(o.items)?o.items:[]}catch{if(!t())return}try{const o=await Uf(N.showArchivedGroups);if(!t())return;if(!Array.isArray(o?.items))throw new Error("Invalid groups payload");C.lastCoordinatorAdminGroups=o.items,Ds(N.recovery,"groups"),VE(),py()}catch{if(!t())return;cn(N.recovery,"groups")}const r=Ln(),i=Ys();try{if(!i)throw new Error("Missing coordinator administration target");const o=await US(r||n);if(!t())return;if(!Array.isArray(o?.items))throw new Error("Invalid join requests payload");C.lastCoordinatorAdminJoinRequests=o.items,N.joinRequestsSnapshotTarget=i,Ds(N.recovery,"joinRequests")}catch{if(!t())return;cn(N.recovery,"joinRequests",Dt(N.joinRequestsSnapshotTarget))}try{if(!i)throw new Error("Missing coordinator administration target");const o=await Gf(r||n,!0);if(!t())return;if(!Array.isArray(o?.items))throw new Error("Invalid devices payload");C.lastCoordinatorAdminDevices=o.items,N.devicesSnapshotTarget=i,Ds(N.recovery,"devices"),WE()}catch{if(!t())return;cn(N.recovery,"devices",Dt(N.devicesSnapshotTarget))}try{const o=await Fa();if(!t())return;N.availableProjects=o}catch{if(!t())return}}else N.recovery.status.availability==="fresh"?(Jd(N.recovery,"groups"),Jd(N.recovery,"joinRequests"),Jd(N.recovery,"devices"),N.joinRequestsSnapshotTarget=null,N.devicesSnapshotTarget=null):(cn(N.recovery,"groups"),cn(N.recovery,"joinRequests",Dt(N.joinRequestsSnapshotTarget)),cn(N.recovery,"devices",Dt(N.devicesSnapshotTarget)));t()&&(Iv([...C.lastCoordinatorAdminDevices,...C.lastCoordinatorAdminJoinRequests.map(r=>({device_id:String(r.device_id||"").trim()||`join-request:${String(r.request_id||"").trim()}`,display_name:r.display_name}))],N.unnamedDeviceAliases),As(C.lastCoordinatorAdminDevices,N.unnamedDeviceAliases),N.recoveryRetryRequested&&(N.recoveryAnnouncement=Rv(N.recovery)?"Retry finished, but some coordinator data still needs attention. Retained data remains unchanged.":C.lastCoordinatorAdminStatus?.readiness==="ready"?"Coordinator data refreshed. Current data is available.":"Coordinator status refreshed. Complete setup to load administration data.",N.recoveryFocusPending=!0),N.recoveryRetryRequested=!1,Ur())}function Mu(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var Fu=new WeakMap,Ly={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},Zx={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},e0={available:"Available",offline:"Offline",unknown:"Availability unknown"};function t0(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function n0(e,t){return t.get(e)??Zx}function r0(e){return e.reduce((t,n)=>!t||Ly[n.state]>Ly[t.state]?n:t,null)}function i0(e,t){return t==="needs_attention"?{label:"Review sharing",target:"sharing"}:e!=="available"?{label:"Check device health",target:"health"}:t==="waiting"||t==="pending"||t==="verifying"?{label:"View sharing status",target:"sharing"}:null}function o0(e,t,n,r,i=[]){const o=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&o.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),f=t0(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),m=_=>{const I=s.get(_);if(!I)return null;const P=n0(_,d);return{canonicalProjectIdentity:_,displayName:I,state:P.state,statusLabel:P.label,statusCopy:P.explanation,deliveredCopiesMayRemain:P.deliveredCopiesMayRemain}},v=f.flatMap(_=>{const I=m(_);return I?[I]:[]}),g=[],h=[...v,...g],y=r0(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:e0[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:v,inheritedProjects:g,unavailableProjectCount:f.length-v.length,statusState:y?.state??"no_projects",statusLabel:y?.statusLabel??"No directly shared Projects",statusCopy:y?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:h.some(_=>_.deliveredCopiesMayRemain),action:i0(w,y?.state??"no_projects")}}).sort((u,p)=>u.displayName.localeCompare(p.displayName)||u.identityName.localeCompare(p.identityName)),revokedDeviceCount:e.identityDevices.filter(u=>u.status==="revoked"&&o.has(u.identityId)).length}}function jy({empty:e,projects:t}){return t.length===0?a("p",{className:"small",children:e}):a("ul",{children:t.map(n=>a("li",{children:[a("strong",{children:n.displayName}),a("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function Yo(e){if(!(e instanceof fl))return"Identity setup is unavailable. Refresh Devices and try again.";const t={binding_preview_busy:"Identity setup is busy. Wait a moment, then retry.",binding_commit_busy:"Identity setup is busy. Wait a moment, then retry.",binding_evidence_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_retry_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_rebind_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_unchanged_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",binding_write_stale:"Device information changed after review. Refresh Devices, review the current details, and try again.",device_pairing_required:"Pair this device before assigning an Identity.",device_rebind_confirmation_required:"Reassignment requires a separate confirmation of the previous and target Identities.",device_inventory_incomplete:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",device_inventory_truncated:"The complete device inventory is unavailable. Refresh after coordinator evidence is available.",binding_write_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",binding_commit_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",device_evidence_conflict:"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.",target_identity_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_unavailable:"A selected device or Identity is no longer available. Refresh Devices and choose again.",device_not_found:"A selected device or Identity is no longer available. Refresh Devices and choose again.",deciding_identity_unavailable:"The deciding Identity is unavailable. Open Identity administration to restore or replace it, then try again."}[e.errorCode];return t||(e.statusCode===503?"Identity setup is busy. Wait a moment, then retry.":e.statusCode===409?"Device evidence conflicts with this setup. Refresh Devices or use Advanced review.":e.statusCode===404?"A selected device or Identity is no longer available. Refresh Devices and choose again.":"Identity setup could not be completed. Refresh Devices and try again.")}function cc(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:Xo(e)}}function Xo(e){return JSON.stringify({deviceId:e.deviceId,evidenceDeviceIds:[...e.evidenceDeviceIds].sort(),state:e.state,identityId:e.identityId,suggestedIdentityId:e.suggestedIdentityId,validatedFingerprint:e.validatedFingerprint,isLocal:e.isLocal,sources:[...e.sources].sort(),conflictCodes:[...e.conflictCodes].sort()})}function lc(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(o=>{const s=n.find(l=>l.deviceId===o.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===o.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var Oy="devices-commit-status";function jn(e){const t=document.getElementById(Oy);t&&(t.textContent=e)}function a0({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter($=>$.status==="active"&&$.mergedIntoIdentityId===null),o=new Map(i.map($=>[$.identityId,$.displayName])),s=new Set(o.keys()),[c,l]=x(()=>Object.fromEntries(n.map($=>[$.deviceId,cc($,s)]))),[d,u]=x(null),[p,f]=x(!1),[m,v]=x(!1),[g,h]=x(""),y=q(null),w=q(0),_=r.previewBindings??im,I=r.commitBindings??om,P=Mu(r),k=d!==null&&lc(d.preview,d.request,n,"bind"),A=Re(()=>n.filter($=>$.state==="setup_required"&&c[$.deviceId]?.selected),[c,n]),L=JSON.stringify({items:t.items.map(Xo),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),F=i.map($=>`${$.identityId}:${$.displayName}`).sort().join("|");K(()=>{d&&y.current?.focus()},[d]),K(()=>{w.current+=1,v(!1),l($=>Object.fromEntries(n.map(E=>{const S=$[E.deviceId];if(!S)return[E.deviceId,cc(E,s)];if(E.state!=="setup_required")return[E.deviceId,cc(E,s)];const D=S.targetIdentityId!==""&&s.has(S.targetIdentityId);return S.itemSignature===Xo(E)&&D?[E.deviceId,S]:S.explicit&&D?[E.deviceId,{...S,selected:!1,itemSignature:Xo(E)}]:[E.deviceId,cc(E,s)]}))),u(null),f(!1)},[L,F]);const T=($,E)=>{w.current+=1,v(!1),l(S=>({...S,[$]:{...S[$],...E}})),u(null),f(!1),h(""),jn("")},M=$=>({bindings:$.map(E=>{const S=c[E.deviceId];return{deviceId:E.deviceId,targetIdentityId:S?.targetIdentityId??"",confirmed:!0}})}),j=async $=>{if(P){h("Refresh Devices before reviewing Identity setup.");return}if($.some(D=>D.state!=="setup_required")){h("Only devices that require Identity setup can be reviewed here.");return}const E=$.find(D=>ms(t,D).blocked);if(E){h(ms(t,E).recovery??"Identity setup is unavailable.");return}if($.length===0||$.some(D=>!c[D.deviceId]?.targetIdentityId)){h("Choose an Identity for every selected device before review.");return}v(!0),h(""),jn("");const S=w.current;try{const D=M($),H=await _(D);S===w.current&&(lc(H,D,$,"bind")?u({preview:H,request:D}):h("Identity setup preview was incomplete. Refresh and try again."))}catch(D){S===w.current&&h(Yo(D))}S===w.current&&v(!1)},B=async()=>{if(!(!d||!p||P||!k)){v(!0),h("");try{await I({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),f(!1),jn("Identity setup completed.");const $=await r.onCommitted?.();jn($===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":$===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch($){h(Yo($))}v(!1)}},U=n.filter($=>$.state==="setup_required");return n.length===0?null:a(z,{children:[g?a("p",{role:"alert",children:g}):null,U.length>1?a("div",{className:"device-identity-setup-summary",children:[a("strong",{children:[U.length.toLocaleString()," devices need Identity setup"]}),a("button",{className:"settings-button",disabled:m||P||A.length===0,onClick:()=>{j(A)},type:"button",children:["Review ",A.length.toLocaleString()," selected"]})]}):null,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map(($,E)=>{const S=c[$.deviceId],D=ms(t,$),H=D.blocked||P,G=`device-inventory-title-${E}`;return a("li",{children:a("article",{"aria-labelledby":G,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${$.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:G,children:[$.displayName,$.isLocal?" (this device)":""]}),a("span",{className:"badge actor-badge",children:$.state==="setup_required"?"Setup required":$.state==="pairing_required"?"Pairing required":$.state==="conflicted"?"Review required":"Configured"})]}),$.state==="setup_required"?a(z,{children:[a("fieldset",{children:[a("legend",{children:"Assign an existing Identity"}),i.length===0?a("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,U.length>1?a("label",{children:[a("input",{"aria-label":`Select for setup: ${$.displayName}`,checked:S?.selected??!1,disabled:H,onInput:oe=>T($.deviceId,{selected:oe.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,a("label",{htmlFor:`${G}-identity`,children:"Identity"}),a("select",{"aria-label":`Choose an Identity for ${$.displayName}`,disabled:H,id:`${G}-identity`,onInput:oe=>T($.deviceId,{targetIdentityId:oe.currentTarget.value,explicit:!0}),value:S?.targetIdentityId??"",children:[a("option",{value:"",children:"Choose Identity…"}),i.map(oe=>a("option",{value:oe.identityId,children:oe.displayName},oe.identityId))]}),$.suggestedIdentityId&&o.has($.suggestedIdentityId)?a("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,D.recovery?a("p",{className:"small",children:D.recovery}):null]}),a("div",{className:"device-identity-card-actions",children:[i.length===0?a("button",{"aria-label":`Open Identity administration for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,a("button",{"aria-label":`Review this device: ${$.displayName}`,className:"settings-button",disabled:m||H||!S?.targetIdentityId,onClick:()=>{j([$])},type:"button",children:"Review this device"})]})]}):$.state==="pairing_required"?a(z,{children:[a("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),a("div",{className:"device-identity-card-actions",children:a("button",{"aria-label":`Go to pairing for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):$.state==="conflicted"?a(z,{children:[a("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),a("div",{className:"device-identity-card-actions",children:a("button",{"aria-label":`Open Advanced review for ${$.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},$.deviceId)})}),d?a("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[a("h3",{id:"device-identity-review-heading",ref:y,tabIndex:-1,children:"Review Identity setup"}),a("ul",{children:d.preview.outcomes.map($=>a("li",{children:[a("strong",{children:[$.displayName,":"]})," ",$.previousIdentityId?o.get($.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",o.get($.targetIdentityId)??"Unavailable Identity"]},$.deviceId))}),a("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),a("label",{children:[a("input",{checked:p,disabled:P,onInput:$=>f($.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),a("div",{className:"peer-actions",children:[a("button",{className:"settings-button",disabled:m,onClick:()=>{u(null),f(!1)},type:"button",children:"Back"}),a("button",{className:"settings-button sync-dialog-confirm",disabled:m||P||!p||!k,onClick:()=>{B()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function My({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const o=e.identities.filter(S=>S.status==="active"&&S.mergedIntoIdentityId===null&&S.identityId!==n.identityId),[s,c]=x(!1),[l,d]=x(""),[u,p]=x(!1),[f,m]=x(null),[v,g]=x(!1),[h,y]=x(!1),[w,_]=x(""),I=q(0),P=i,k=new Map(e.identities.map(S=>[S.identityId,S.displayName])),A=f?.preview.status==="ready"&&f.preview.outcomes.length===1?f.preview.outcomes[0]:null,L=f!==null&&lc(f.preview,f.request,[n],"rebind"),F=ms(t,n),T=F.blocked||Mu(r),M=`configured-rebind-trigger-${n.deviceId}`,j=o.find(S=>S.identityId===l)?.displayName??"",B=o.map(S=>S.identityId).sort().join("|"),U=Xo(n);K(()=>{I.current+=1,y(!1),l&&!o.some(S=>S.identityId===l)&&(d(""),p(!1)),m(null),g(!1)},[B,U]);const $=async()=>{if(T){_(F.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){_("Choose a target Identity and confirm the reassignment before review.");return}y(!0),_(""),jn("");const S=I.current;try{const D={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},H=await(r.previewBindings??im)(D);S===I.current&&(H.status!=="ready"?_(Yo(new fl(409,H.errorCode??"binding_preview_unavailable",H))):lc(H,D,[n],"rebind")?m({preview:H,request:D}):_("Identity reassignment preview was incomplete. Refresh and try again."))}catch(D){S===I.current&&_(Yo(D))}S===I.current&&y(!1)},E=async()=>{if(!(!f||!v||T||!L)){y(!0),_("");try{await(r.commitBindings??om)({...f.request,reviewedInventoryDigest:f.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),m(null),g(!1),jn("Identity reassignment completed.");const S=await r.onCommitted?.();jn(S===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":S===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(M)??document.getElementById("devices-heading"))?.focus()}catch(S){_(Yo(S))}y(!1)}};return a("div",{className:"device-identity-rebind",children:[a("button",{"aria-expanded":s,className:"settings-button",disabled:T,id:M,onClick:()=>{I.current+=1,y(!1),c(!s),m(null),g(!1),_(""),jn("")},type:"button",children:"Change Identity…"}),F.recovery?a("p",{className:"small",children:F.recovery}):null,s?a("fieldset",{children:[a("legend",{children:"Reassign this configured device"}),a("p",{children:[a("strong",{children:"Suggested current Identity (unconfirmed):"})," ",P]}),a("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),a("select",{disabled:T,id:`configured-rebind-${n.deviceId}`,onInput:S=>{I.current+=1,y(!1),d(S.currentTarget.value),p(!1),m(null),g(!1)},value:l,children:[a("option",{value:"",children:"Choose a different Identity…"}),o.map(S=>a("option",{value:S.identityId,children:S.displayName},S.identityId))]}),a("label",{children:[a("input",{checked:u,disabled:T||!l,onInput:S=>{I.current+=1,y(!1),p(S.currentTarget.checked),m(null),g(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",j||"the selected Identity"]}),a("button",{className:"settings-button",disabled:h||T,onClick:()=>{$()},type:"button",children:"Review reassignment"}),f?a("div",{className:"device-identity-rebind-review",children:[a("h4",{children:"Review reassignment"}),a("p",{children:[A?.displayName,":"," ",A?.previousIdentityId?k.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",k.get(A?.targetIdentityId??"")??"Unavailable Identity"]}),a("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),a("label",{children:[a("input",{checked:v,disabled:T,onInput:S=>g(S.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),a("button",{className:"settings-button sync-dialog-confirm",disabled:h||T||!v||!L,onClick:()=>{E()},type:"button",children:"Reassign Identity"})]}):null,w?a("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function s0({intent:e,options:t,projection:n}){if(t.loading)return a(gg,{label:"Loading Devices"});if(t.loadError)return a("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?a("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(f=>!t.inventory?.items.some(m=>m.state!=="configured"&&m.evidenceDeviceIds.includes(f.deviceId))),o=new Set(i.map(f=>f.deviceId)),s=t.inventoryUnavailable?a("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=vg(t.inventory),l=t.inventory?.items.filter(f=>f.state==="configured"&&!f.evidenceDeviceIds.some(m=>o.has(m)))??[],d=t.inventory?a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((f,m)=>{const v=`configured-inventory-title-${m}`,g=e.identities.find(h=>h.identityId===f.identityId)?.displayName??"Unavailable Identity";return a("li",{children:a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:f.displayName}),a("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),a("p",{children:[a("strong",{children:"Owning Identity:"})," ",g]}),a(My,{intent:e,inventory:t.inventory,item:f,options:t,previousIdentityName:g})]})},f.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?a("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[a("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),a("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),a("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?a(z,{children:[t.inventory.truncated?a("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?a("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,a(a0,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?a(z,{children:[r,s,u,p,d,a("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):a(z,{children:[r,s,u,p,d,a("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((f,m)=>{const v=`devices-card-title-${m}`,g=f.action,h=t.inventory?.items.find(y=>y.state==="configured"&&y.evidenceDeviceIds.includes(f.deviceId));return a("li",{children:a("article",{"aria-labelledby":v,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${f.deviceId}`,tabIndex:-1,children:[a("div",{className:"peer-title recipient-policy-sharing-card-title",children:[a("h3",{id:v,children:f.displayName}),a("span",{className:"badge actor-badge",children:[Mu(t)?"Device":"Configured"," ·"," ",f.availabilityLabel]})]}),a("dl",{className:"recipient-policy-sharing-details",children:[a("div",{children:[a("dt",{children:"Owning Identity"}),a("dd",{children:f.identityName})]}),a("div",{children:[a("dt",{children:"Availability"}),a("dd",{children:f.availabilityLabel})]}),f.isPairedPeer?a("div",{children:[a("dt",{children:"Codemem version"}),a("dd",{children:f.reportedRuntimeVersion??"Not reported"})]}):null,a("div",{children:[a("dt",{children:"Sharing status"}),a("dd",{children:[a("strong",{children:f.statusLabel})," — ",f.statusCopy]})]})]}),a("section",{"aria-labelledby":`${v}-direct`,children:[a("h4",{id:`${v}-direct`,children:"Direct Projects"}),a(jy,{empty:"No Projects are shared directly.",projects:f.directProjects})]}),a("section",{"aria-labelledby":`${v}-teams`,children:[a("h4",{id:`${v}-teams`,children:"Projects through Teams"}),a(jy,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:f.inheritedProjects})]}),f.unavailableProjectCount>0?a("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,f.deliveredCopiesMayRemain?a("p",{className:"small",children:[a("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,g&&t.onNavigate?a("button",{"aria-label":`${g.label} for ${f.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(g.target),ref:y=>{y&&Fu.set(y,{deviceId:f.deviceId,target:g.target})},type:"button",children:g.label}):null,h&&t.inventory?a(My,{intent:e,inventory:t.inventory,item:h,options:t,previousIdentityName:f.identityName}):null]})},f.deviceId)})}),n.revokedDeviceCount>0?a("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function dc(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?Fu.get(s):void 0,d=o0(t,n,r,i,o.peerRuntimeMetadata);if(We(a("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[a("div",{className:"recipient-policy-sharing-header",children:[a("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),a("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),a(s0,{intent:t,options:o,projection:d}),a("p",{"aria-live":"polite",id:Oy,role:"status"})]}),e),jn(""),!o.loading&&C.pendingDeviceIdentityFocus!==void 0){const u=C.pendingDeviceIdentityFocus,p=o.inventory?.items.find(m=>m.deviceId===u||m.evidenceDeviceIds.includes(u??"")),f=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(m=>document.getElementById(`device-identity-card-${m}`)).find(m=>m instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)C.pendingDeviceIdentityFocus=void 0;else if(f){C.pendingDeviceIdentityFocus=void 0,f.focus();return}else if(!o.inventoryUnavailable&&!o.refreshError){C.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=Fu.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function c0(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function qr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function l0(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const o=Math.round(i/60);if(o<60)return`${o}m ago`;const s=Math.round(o/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function qi(e){if(!e)return null;const t=new Date(e).getTime();if(!Number.isFinite(t))return null;const n=Math.floor((Date.now()-t)/1e3);return n>=0?n:0}function rr(e){return e==null?"n/a":e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}d`}function Fy(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function d0(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r)||r<=0)return"n/a";const i=(n+r)/r;return!Number.isFinite(i)||i<=0?"n/a":`${i.toFixed(i>=10?0:1)}x`}function Bu(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const o=n/i;return Number.isFinite(o)?`${Math.round(o*100)}%`:"n/a"}function Qo(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:o}=n[r],s=t/o,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function u0(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function Zo(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function uc(e){if(!e)return[];if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]}function By(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function p0(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function f0(e,t=2){if(!e.length)return"";const n=e.map(o=>String(o).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function Uy(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function m0(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function h0(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,o=0;for(;o<n.length-1&&r(i)>=1024;)i/=1024,o+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[o]}`}function qy(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===C.lastStatsPayload?.identity?.actor_id)}function pc(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function g0(e){if(!e)return[];const t=String(e).split(`
|
|
42
|
+
`).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function v0(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(o=>o.trim()).filter(Boolean),i=[];for(const o of r)if(!(o.length<18)&&(i.push(o),i.length>=t))break;return i}function Gy(e){const t=Zo(e.title),n=Zo(e.body_text);if(!t&&!n)return!0;const r=n||t;if(r.length<10||t&&n&&t===n&&r.length<40)return!0;const i=t.charAt(0);return!!((i==="└"||i==="›")&&r.length<40||t.startsWith("list ")&&r.length<20||r==="ls"||r==="list ls")}function Hy(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function Rt(e){return`${String(e.kind||"").toLowerCase()}:${Hy(e)}`}function y0(e){if(e.tags!=null)return uc(e.tags);const t=uc(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function b0(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function _0(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function w0(e){if(qy(e))return"You";const t=String(e.actor_id||"").trim(),n=Ci(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function S0(e,t={}){if(qy(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Ci(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Ky(e,t){const n=new Map;return e.forEach(r=>{n.set(Rt(r),r)}),t.forEach(r=>{n.set(Rt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function C0(e,t){const n=new Set(t.map(Rt));return Ky(e.filter(r=>!n.has(Rt(r))),t)}var AU=560;function I0(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function fc(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function mc(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function P0(e,t){const n=new Set(t.map(Rt));return e.filter(r=>!n.has(Rt(r))).length}var R0=Object.defineProperty,nt=(e,t)=>R0(e,"name",{value:t,configurable:!0}),[Uu,xU]=lt("Tooltip",[Xn]),hc=Xn(),k0="TooltipProvider",T0=700,qu="tooltip.open",[N0,Gu]=Uu(k0),E0=nt(e=>{const{__scopeTooltip:t,delayDuration:n=T0,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=q(!0),c=q(!1),l=q(0);return K(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(N0,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:se(()=>{r<=0||(window.clearTimeout(l.current),s.current=!1)},[r]),onClose:se(()=>{r<=0||(window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r))},[r]),isPointerInTransitRef:c,onPointerInTransitChange:se(d=>{c.current=d},[]),disableHoverableContent:i,children:o})},"TooltipProvider"),Hu="Tooltip",[A0,ea]=Uu(Hu),x0=nt(e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=Gu(Hu,e.__scopeTooltip),d=hc(t),[u,p]=x(null),[f,m]=x(void 0),v=Nt(),g=q(0),h=s??l.disableHoverableContent,y=c??l.delayDuration,w=q(!1),[_,I]=Et({prop:r,defaultProp:i??!1,onChange:nt(T=>{T?(l.onOpen(),document.dispatchEvent(new CustomEvent(qu))):l.onClose(),o?.(T)},"onChange"),caller:Hu}),P=Re(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),k=se(()=>{window.clearTimeout(g.current),g.current=0,w.current=!1,I(!0)},[I]),A=se(()=>{window.clearTimeout(g.current),g.current=0,I(!1)},[I]),L=se(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{w.current=!0,I(!0),g.current=0},y)},[y,I]);return K(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),a(zs,{...d,children:a(A0,{scope:t,contentId:f??v,setContentId:m,open:_,stateAttribute:P,trigger:u,onTriggerChange:p,onTriggerEnter:se(()=>{l.isOpenDelayedRef.current?L():k()},[l.isOpenDelayedRef,L,k]),onTriggerLeave:se(()=>{h?A():(window.clearTimeout(g.current),g.current=0)},[A,h]),onOpen:k,onClose:A,disableHoverableContent:h,children:n})})},"Tooltip"),Vy="TooltipTrigger",D0=J(nt(function(t,n){const{__scopeTooltip:r,...i}=t,o=ea(Vy,r),s=Gu(Vy,r),c=hc(r),l=q(null),d=Se(n,l,o.onTriggerChange),u=q(!1),p=q(!1),f=se(()=>u.current=!1,[]);return K(()=>()=>document.removeEventListener("pointerup",f),[f]),a(Vo,{asChild:!0,...c,children:a(ve.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...i,ref:d,onPointerMove:ne(t.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ne(t.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ne(t.onPointerDown,()=>{o.open&&o.onClose(),u.current=!0,document.addEventListener("pointerup",f,{once:!0})}),onFocus:ne(t.onFocus,()=>{u.current||o.onOpen()}),onBlur:ne(t.onBlur,o.onClose),onClick:ne(t.onClick,o.onClose)})})},"TooltipTrigger")),zy="TooltipPortal",[$0,L0]=Uu(zy,{forceMount:void 0}),j0=nt(e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=ea(zy,t);return a($0,{scope:t,forceMount:n,children:a(Pt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),ta="TooltipContent",O0=J(nt(function(t,n){const r=L0(ta,t.__scopeTooltip),{forceMount:i=r.forceMount,side:o="top",...s}=t,c=ea(ta,t.__scopeTooltip);return a(Pt,{present:i||c.open,children:c.disableHoverableContent?a(Wy,{side:o,...s,ref:n}):a(M0,{side:o,...s,ref:n})})},"TooltipContent")),M0=J(nt(function(t,n){const r=ea(ta,t.__scopeTooltip),i=Gu(ta,t.__scopeTooltip),o=q(null),s=Se(n,o),[c,l]=x(null),{trigger:d,onClose:u}=r,p=o.current,{onPointerInTransitChange:f}=i,m=se(()=>{l(null),f(!1)},[f]),v=se((g,h)=>{const y=g.currentTarget,w={x:g.clientX,y:g.clientY},_=Yy(w,Jy(w,y.getBoundingClientRect())),I=Xy(h.getBoundingClientRect()),P=Zy([..._,...I]);l(P),f(!0)},[f]);return K(()=>()=>m(),[m]),K(()=>{if(d&&p){const g=nt(y=>v(y,p),"handleTriggerLeave"),h=nt(y=>v(y,d),"handleContentLeave");return d.addEventListener("pointerleave",g),p.addEventListener("pointerleave",h),()=>{d.removeEventListener("pointerleave",g),p.removeEventListener("pointerleave",h)}}},[d,p,v,m]),K(()=>{if(c){const g=nt(h=>{const y=h.target,w={x:h.clientX,y:h.clientY},_=d?.contains(y)||p?.contains(y),I=!Qy(w,c);_?m():I&&(m(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[d,p,c,u,m]),a(Wy,{...t,ref:s})},"TooltipContentHoverable")),F0=Ch("TooltipContent"),Wy=J(nt(function(t,n){const{__scopeTooltip:r,children:i,"aria-label":o,id:s,onEscapeKeyDown:c,onPointerDownOutside:l,...d}=t,u=ea(ta,r),p=hc(r),{onClose:f}=u;K(()=>(document.addEventListener(qu,f),()=>document.removeEventListener(qu,f)),[f]),K(()=>{if(u.trigger){const v=nt(g=>{g.target instanceof Node&&g.target.contains(u.trigger)&&f()},"handleScroll");return window.addEventListener("scroll",v,{capture:!0}),()=>window.removeEventListener("scroll",v,{capture:!0})}},[u.trigger,f]);const{setContentId:m}=u;return Xe(()=>(m(s),()=>{m(void 0)}),[s,m]),a(hi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:v=>v.preventDefault(),onDismiss:f,children:a(Ws,{"data-state":u.stateAttribute,role:o?void 0:"tooltip",id:o?void 0:u.contentId,...p,...d,ref:n,style:{...d.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[a(F0,{children:i}),o?a(uk,{id:u.contentId,role:"tooltip",children:o}):null]})})},"TooltipContentImpl")),B0=J(nt(function(t,n){const{__scopeTooltip:r,...i}=t,o=hc(r);return a(vE,{...o,...i,ref:n})},"TooltipArrow"));function Jy(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),o=Math.abs(t.left-e.x);switch(Math.min(n,r,i,o)){case o:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}nt(Jy,"getExitSideFromRect");function Yy(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n})}return r}nt(Yy,"getPaddedExitPoints");function Xy(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}nt(Xy,"getPointsFromRect");function Qy(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,s=t.length-1;o<t.length;s=o++){const c=t[o],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}nt(Qy,"isPointInPolygon");function Zy(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),eb(t)}nt(Zy,"getHull");function eb(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const o=t[t.length-1],s=t[t.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const o=n[n.length-1],s=n[n.length-2];if((o.x-s.x)*(i.y-s.y)>=(o.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}nt(eb,"getHullPresorted");var U0=E0,q0=x0,G0=D0,H0=j0,K0=O0,V0=B0;function Ku({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(U0,{delayDuration:t,skipDelayDuration:n,children:e})}function gc({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:o=!0,disabled:s=!1}){return s?a(z,{children:e}):a(q0,{children:[a(G0,{asChild:o,children:e}),a(H0,{children:a(K0,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(V0,{className:"tooltip-arrow"})]})})]})}function z0(e){e.dataset.feedRenderRoot="preact"}function W0(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function J0(e,t){z0(e),We(b(Ku,null,t),e)}function Y0(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function X0(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function Vu(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function Q0(e){const t=pc(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=Zo(n),o=Zo(r),s=!!r&&o!==i,c=uc(e?.facts||t?.facts||[]),l=c.length?c:g0(r||n),d=l.length?l:v0(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function Z0(e){const t=[];return e.hasSummary&&t.push({id:"summary",label:"Summary"}),e.hasFacts&&t.push({id:"facts",label:"Facts"}),e.hasNarrative&&t.push({id:"narrative",label:"Narrative"}),t}function eD(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function tD(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function nD(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function rD(e,t){const n=C.feedTypeFilter==="observations"?" · observations":C.feedTypeFilter==="summaries"?" · session summaries":"",r=b0(C.feedScopeFilter),i=!C.feedQuery.trim()&&C.lastFeedFilteredCount?` · ${C.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${C.feedQuery.trim()?` · matching "${C.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function vc({label:e,candidates:t}){return t.length===0?null:b("div",{className:"trace-group"},b("div",{className:"section-meta"},e),b("div",{className:"feed-list"},t.map(n=>b("div",{className:"feed-card",key:`${e}:${n.id}`},b("div",{className:"feed-card-header"},[b("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),b("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),b("div",{className:"feed-card-body"},[b("div",null,n.preview||"No preview available."),n.reasons.length?b("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function iD({open:e}){const[t,n]=x(()=>String(C.feedQuery||"")),[r,i]=x(!1),[o,s]=x(!1),[c,l]=x(""),[d,u]=x(!1),[p,f]=x(""),[m,v]=x(""),[g,h]=x(null),y=q(0),w=String(C.feedQuery||""),_=String(t||"").trim(),I=C.currentProject||null,P=X0(c),k=Vu({project:I,query:_,workingSetFiles:P}),A=g&&Vu({project:g.inputs.project,query:g.inputs.query,workingSetFiles:g.inputs.working_set_files})===k?g:null,L=p&&m===k?p:"";K(()=>{y.current+=1,u(!1),f(""),v(""),h(U=>!U||U.inputs.query!==_||U.inputs.project!==I?null:U)},[k]),K(()=>{e&&!r&&(n(Y0({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const F=async()=>{const U=_,$=I,E=P,S=Vu({project:$,query:U,workingSetFiles:E}),D=y.current+1;if(y.current=D,!U){f("Enter a query to inspect."),v(S),h(null);return}u(!0),f(""),v("");try{const H=await YS({context:U,project:$,working_set_files:E});if(D!==y.current)return;h(H)}catch(H){if(D!==y.current)return;f(H instanceof Error?H.message:String(H)),v(S),h(null)}finally{D===y.current&&u(!1)}},T=A?.retrieval.candidates.filter(U=>U.disposition==="selected")||[],M=A?.retrieval.candidates.filter(U=>U.disposition==="dropped")||[],j=A?.retrieval.candidates.filter(U=>U.disposition==="deduped")||[],B=A?.retrieval.candidates.filter(U=>U.disposition==="trimmed")||[];return e?b("div",{className:"feed-inspector"},b("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[b("div",{className:"feed-card-header"},[b("div",{className:"feed-card-title"},"Context Inspector"),b("div",{className:"feed-card-meta"},o?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),b("div",{className:"feed-card-body"},[b("input",{className:"feed-search",onInput:U=>{n(String(U.currentTarget.value||"")),s(!0),h(null),f(""),v("")},placeholder:"Trace a pack query…",value:t}),b("div",{className:"section-meta",style:"margin-top:8px;"},o?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),b("textarea",{className:"feed-inspector-files",onInput:U=>l(String(U.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),b("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},b("button",{className:"toggle-button active",disabled:d,onClick:()=>{F()},type:"button"},d?"Tracing…":"Run trace"),A?b("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),g&&!A?b("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,L?b("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},L):null]),A?b(z,null,[b(vc,{label:"Selected",candidates:T}),b(vc,{label:"Dropped",candidates:M}),b(vc,{label:"Deduped",candidates:j}),b(vc,{label:"Trimmed",candidates:B}),b("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?b("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(U=>`kept #${U.kept} from [${U.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?b("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,b("div",{className:"section-meta"},"Final pack"),b("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var oD={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function zu({variant:e,tone:t,title:n,children:r}){const i=oD[e],o=t?`${i} ${t}`:i;return a("span",{className:o,title:n,children:r})}function tb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function aD(e){if(Array.isArray(e))return e}function sD(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,o,s,c=[],l=!0,d=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function cD(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
43
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function lD(e,t){return aD(e)||sD(e,t)||dD(e,t)||cD()}function dD(e,t){if(e){if(typeof e=="string")return tb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?tb(e,t):void 0}}var nb=Object.entries,rb=Object.setPrototypeOf,uD=Object.isFrozen,pD=Object.getPrototypeOf,fD=Object.getOwnPropertyDescriptor,rt=Object.freeze,st=Object.seal,Gi=Object.create,ib=typeof Reflect<"u"&&Reflect,Wu=ib.apply,Ju=ib.construct;rt||(rt=function(t){return t}),st||(st=function(t){return t}),Wu||(Wu=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return t.apply(n,i)}),Ju||(Ju=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new t(...r)});var Gr=Qe(Array.prototype.forEach),mD=Qe(Array.prototype.lastIndexOf),ob=Qe(Array.prototype.pop),na=Qe(Array.prototype.push),hD=Qe(Array.prototype.splice),Hi=Array.isArray,ra=Qe(String.prototype.toLowerCase),Yu=Qe(String.prototype.toString),ab=Qe(String.prototype.match),ia=Qe(String.prototype.replace),sb=Qe(String.prototype.indexOf),gD=Qe(String.prototype.trim),vD=Qe(Number.prototype.toString),yD=Qe(Boolean.prototype.toString),cb=typeof BigInt>"u"?null:Qe(BigInt.prototype.toString),lb=typeof Symbol>"u"?null:Qe(Symbol.prototype.toString),kt=Qe(Object.prototype.hasOwnProperty),oa=Qe(Object.prototype.toString),gt=Qe(RegExp.prototype.test),Hr=bD(TypeError);function Qe(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Wu(e,t,r)}}function bD(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Ju(e,n)}}function Ae(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ra;if(rb&&rb(e,null),!Hi(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(uD(t)||(t[r]=o),i=o)}e[i]=!0}return e}function _D(e){for(let t=0;t<e.length;t++)kt(e,t)||(e[t]=null);return e}function $t(e){const t=Gi(null);for(const r of nb(e)){var n=lD(r,2);const i=n[0],o=n[1];kt(e,i)&&(Hi(o)?t[i]=_D(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=$t(o):t[i]=o)}return t}function wD(e){switch(typeof e){case"string":return e;case"number":return vD(e);case"boolean":return yD(e);case"bigint":return cb?cb(e):"0";case"symbol":return lb?lb(e):"Symbol()";case"undefined":return oa(e);case"function":case"object":{if(e===null)return oa(e);const t=e,n=Yt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:oa(r)}return oa(e)}default:return oa(e)}}function Yt(e,t){for(;e!==null;){const r=fD(e,t);if(r){if(r.get)return Qe(r.get);if(typeof r.value=="function")return Qe(r.value)}e=pD(e)}function n(){return null}return n}function SD(e){try{return gt(e,""),!0}catch{return!1}}var db=rt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Xu=rt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Qu=rt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),CD=rt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Zu=rt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),ID=rt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ub=rt(["#text"]),pb=rt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),ep=rt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),fb=rt(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),yc=rt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),PD=st(/{{[\w\W]*|^[\w\W]*}}/g),RD=st(/<%[\w\W]*|^[\w\W]*%>/g),kD=st(/\${[\w\W]*/g),TD=st(/^data-[\-\w.\u00B7-\uFFFF]+$/),ND=st(/^aria-[\-\w]+$/),mb=st(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ED=st(/^(?:\w+script|data):/i),AD=st(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xD=st(/^html$/i),DD=st(/^[a-z][.\w]*(-[.\w]+)+$/i),hb=st(/<[/\w!]/g),gb=st(/<[/\w]/g),$D=st(/<\/no(script|embed|frames)/i),LD=st(/\/>/i),Lt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},vb=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],jD=rt(Ae({},vb)),OD=(function(){const e={};return Gr(vb,t=>{e[t]=st(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),rt(e)})(),MD=function(){return typeof window>"u"?null:window},FD=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const o="dompurify"+(r?"#"+r:"");try{return t.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},yb=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},ir=function(t,n,r,i){return kt(t,n)&&Hi(t[n])?Ae(i.base?$t(i.base):{},t[n],i.transform):r},tp=function(t,n,r){const i=kt(t,n)?t[n]:void 0;return i&&typeof i=="object"?$t(i):r()};function bb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:MD();const t=X=>bb(X);if(t.version="3.4.14",t.removed=[],!e||!e.document||e.document.nodeType!==Lt.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,i=r.currentScript;e.DocumentFragment;const o=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,f=Yt(p,"cloneNode"),m=Yt(p,"remove"),v=Yt(p,"nextSibling"),g=Yt(p,"childNodes"),h=Yt(p,"parentNode"),y=Yt(p,"shadowRoot"),w=Yt(p,"attributes"),_=s&&s.prototype?Yt(s.prototype,"nodeType"):null,I=s&&s.prototype?Yt(s.prototype,"nodeName"):null,P=s&&s.prototype?Yt(s.prototype,"ownerDocument"):null,k=function(R){return _?_(R):R.nodeType},A=function(R){return I?I(R):R.nodeName};if(typeof o=="function"){const X=n.createElement("template");X.content&&X.content.ownerDocument&&(n=X.content.ownerDocument)}let L,F="",T,M=!1,j=0;const B=function(){if(j>0)throw Hr('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},U=function(R){B(),j++;try{return L.createHTML(R)}finally{j--}},$=function(R){B(),j++;try{return L.createScriptURL(R)}finally{j--}},E=function(){return M||(T=FD(u,i),M=!0),T},S=n,D=S.implementation,H=S.createNodeIterator,G=S.createDocumentFragment,oe=S.getElementsByTagName,ae=r.importNode;let ee=yb();t.isSupported=typeof nb=="function"&&typeof h=="function"&&D&&D.createHTMLDocument!==void 0;const ie=PD,Ce=RD,Ie=kD,Ne=TD,le=ND,ye=ED,Y=AD,ce=DD;let ge=mb,pe=null;const He=Ae({},[...db,...Xu,...Qu,...Zu,...ub]);let de=null;const W=Ae({},[...pb,...ep,...fb,...yc]);let Pe=Object.seal(Gi(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),re=null,je=null;const it=Object.seal(Gi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let hr=!0,Zt=!0,Un=!1,gr=!0,me=!1,ot=!0,Ze=!1,ao=!1,so=null,ai=null,co=!1,vn=!1,_t=!1,yn=!1,nl=!0,sS=!1;const cS="user-content-";let kf=!0,Tf=!1,lo={},uo=null;const lS=Ae({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let dS=null;const uS=Ae({},["audio","video","img","source","image","track"]);let pS=null;const fS=Ae({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),rl="http://www.w3.org/1998/Math/MathML",il="http://www.w3.org/2000/svg",bn="http://www.w3.org/1999/xhtml";let po=bn,Nf=!1,Ef=null;const rU=Ae({},[rl,il,bn],Yu),mS=rt(["mi","mo","mn","ms","mtext"]);let Af=Ae({},mS);const hS=rt(["annotation-xml"]);let xf=Ae({},hS);const iU=Ae({},["title","style","font","a","script"]);let Oa=null;const oU=["application/xhtml+xml","text/html"],aU="text/html";let Ye=null,fo=null;const sU=n.createElement("form"),gS=function(R){return R instanceof RegExp||R instanceof Function},Df=function(){let R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(fo&&fo===R)return;(!R||typeof R!="object")&&(R={}),R=$t(R),Oa=oU.indexOf(R.PARSER_MEDIA_TYPE)===-1?aU:R.PARSER_MEDIA_TYPE,Ye=Oa==="application/xhtml+xml"?Yu:ra,pe=ir(R,"ALLOWED_TAGS",He,{transform:Ye}),de=ir(R,"ALLOWED_ATTR",W,{transform:Ye}),Ef=ir(R,"ALLOWED_NAMESPACES",rU,{transform:Yu}),pS=ir(R,"ADD_URI_SAFE_ATTR",fS,{transform:Ye,base:fS}),dS=ir(R,"ADD_DATA_URI_TAGS",uS,{transform:Ye,base:uS}),uo=ir(R,"FORBID_CONTENTS",lS,{transform:Ye}),re=ir(R,"FORBID_TAGS",$t({}),{transform:Ye}),je=ir(R,"FORBID_ATTR",$t({}),{transform:Ye}),lo=kt(R,"USE_PROFILES")?R.USE_PROFILES&&typeof R.USE_PROFILES=="object"?$t(R.USE_PROFILES):R.USE_PROFILES:!1,hr=R.ALLOW_ARIA_ATTR!==!1,Zt=R.ALLOW_DATA_ATTR!==!1,Un=R.ALLOW_UNKNOWN_PROTOCOLS||!1,gr=R.ALLOW_SELF_CLOSE_IN_ATTR!==!1,me=R.SAFE_FOR_TEMPLATES||!1,ot=R.SAFE_FOR_XML!==!1,Ze=R.WHOLE_DOCUMENT||!1,vn=R.RETURN_DOM||!1,_t=R.RETURN_DOM_FRAGMENT||!1,yn=R.RETURN_TRUSTED_TYPE||!1,co=R.FORCE_BODY||!1,nl=R.SANITIZE_DOM!==!1,sS=R.SANITIZE_NAMED_PROPS||!1,kf=R.KEEP_CONTENT!==!1,Tf=R.IN_PLACE||!1,ge=SD(R.ALLOWED_URI_REGEXP)?R.ALLOWED_URI_REGEXP:mb,po=typeof R.NAMESPACE=="string"?R.NAMESPACE:bn,Af=tp(R,"MATHML_TEXT_INTEGRATION_POINTS",()=>Ae({},mS)),xf=tp(R,"HTML_INTEGRATION_POINTS",()=>Ae({},hS));const O=tp(R,"CUSTOM_ELEMENT_HANDLING",()=>Gi(null));if(Pe=Gi(null),kt(O,"tagNameCheck")&&gS(O.tagNameCheck)&&(Pe.tagNameCheck=O.tagNameCheck),kt(O,"attributeNameCheck")&&gS(O.attributeNameCheck)&&(Pe.attributeNameCheck=O.attributeNameCheck),kt(O,"allowCustomizedBuiltInElements")&&typeof O.allowCustomizedBuiltInElements=="boolean"&&(Pe.allowCustomizedBuiltInElements=O.allowCustomizedBuiltInElements),st(Pe),me&&(Zt=!1),_t&&(vn=!0),lo&&(pe=Ae({},ub),de=Gi(null),lo.html===!0&&(Ae(pe,db),Ae(de,pb)),lo.svg===!0&&(Ae(pe,Xu),Ae(de,ep),Ae(de,yc)),lo.svgFilters===!0&&(Ae(pe,Qu),Ae(de,ep),Ae(de,yc)),lo.mathMl===!0&&(Ae(pe,Zu),Ae(de,fb),Ae(de,yc))),it.tagCheck=null,it.attributeCheck=null,kt(R,"ADD_TAGS")&&(typeof R.ADD_TAGS=="function"?it.tagCheck=R.ADD_TAGS:Hi(R.ADD_TAGS)&&(pe===He&&(pe=$t(pe)),Ae(pe,R.ADD_TAGS,Ye))),kt(R,"ADD_ATTR")&&(typeof R.ADD_ATTR=="function"?it.attributeCheck=R.ADD_ATTR:Hi(R.ADD_ATTR)&&(de===W&&(de=$t(de)),Ae(de,R.ADD_ATTR,Ye))),kt(R,"ADD_FORBID_CONTENTS")&&Hi(R.ADD_FORBID_CONTENTS)&&(uo===lS&&(uo=$t(uo)),Ae(uo,R.ADD_FORBID_CONTENTS,Ye)),kf&&(pe["#text"]=!0),Ze&&Ae(pe,["html","head","body"]),pe.table&&(Ae(pe,["tbody"]),delete re.tbody),R.TRUSTED_TYPES_POLICY){if(typeof R.TRUSTED_TYPES_POLICY.createHTML!="function")throw Hr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof R.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Hr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const V=L;L=R.TRUSTED_TYPES_POLICY;try{F=U("")}catch(te){throw L=V,te}}else R.TRUSTED_TYPES_POLICY===null?(L=void 0,F=""):(L===void 0&&(L=E()),L&&typeof F=="string"&&(F=U("")));rt&&rt(R),fo=R},vS=Ae({},[...Xu,...Qu,...CD]),yS=Ae({},[...Zu,...ID]),cU=function(R,O,V){return O.namespaceURI===bn?R==="svg":O.namespaceURI===rl?R==="svg"&&(V==="annotation-xml"||Af[V]):!!vS[R]},lU=function(R,O,V){return O.namespaceURI===bn?R==="math":O.namespaceURI===il?R==="math"&&xf[V]:!!yS[R]},dU=function(R,O,V){return O.namespaceURI===il&&!xf[V]||O.namespaceURI===rl&&!Af[V]?!1:!yS[R]&&(iU[R]||!vS[R])},uU=function(R){let O=h(R);(!O||!O.tagName)&&(O={namespaceURI:po,tagName:"template"});const V=ra(R.tagName),te=ra(O.tagName);return Ef[R.namespaceURI]?R.namespaceURI===il?cU(V,O,te):R.namespaceURI===rl?lU(V,O,te):R.namespaceURI===bn?dU(V,O,te):!!(Oa==="application/xhtml+xml"&&Ef[R.namespaceURI]):!1},vr=function(R){na(t.removed,{element:R});try{h(R).removeChild(R)}catch{if(m(R),!h(R))throw Hr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},bS=function(R,O,V){try{R.removeAttributeNode(O)}catch{try{R.removeAttribute(V)}catch{}}},ol=function(R){al(R);const O=g(R);if(O){const te=[];Gr(O,ue=>{na(te,ue)}),Gr(te,ue=>{try{m(ue)}catch{}})}const V=w(R);if(V)for(let te=V.length-1;te>=0;--te){const ue=V[te],be=ue&&ue.name;typeof be=="string"&&bS(R,ue,be)}},si=function(R,O,V){if(!V)try{V=O.getAttributeNode(R)}catch{V=null}na(t.removed,{attribute:V||null,from:O});try{V?O.removeAttributeNode(V):O.removeAttribute(R)}catch{try{O.removeAttribute(R)}catch{}}if(R==="is")if(vn||_t)try{vr(O)}catch{}else try{O.setAttribute(R,"")}catch{}},pU=function(R){const O=w(R);if(O)for(let V=O.length-1;V>=0;--V){const te=O[V],ue=te&&te.name;typeof ue!="string"||de[Ye(ue)]||bS(R,te,ue)}},al=function(R){const O=[R];for(;O.length>0;){const V=O.pop();k(V)===Lt.element&&pU(V);const te=g(V);if(te)for(let ue=te.length-1;ue>=0;--ue)O.push(te[ue])}},_S=function(R,O){return ot?R==="patchsrc"?!0:R==="for"&&O!=="label"&&O!=="output":!1},fU=function(R){if(!ot)return;const O=[R];for(;O.length>0;){const V=O.pop(),te=k(V);if(te===Lt.processingInstruction||te===Lt.comment&>(gb,V.data)){try{m(V)}catch{}continue}if(te===Lt.element){const be=V,xe=Ye(A(V));try{be.hasAttribute&&be.hasAttribute("patchsrc")&&be.removeAttribute("patchsrc"),be.hasAttribute&&be.hasAttribute("for")&&_S("for",xe)&&be.removeAttribute("for")}catch{}}const ue=g(V);if(ue)for(let be=ue.length-1;be>=0;--be)O.push(ue[be])}},wS=function(R){let O=null,V=null;if(co)R="<remove></remove>"+R;else{const be=ab(R,/^[\r\n\t ]+/);V=be&&be[0]}Oa==="application/xhtml+xml"&&po===bn&&(R='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+R+"</body></html>");const te=L?U(R):R;if(po===bn)try{O=new d().parseFromString(te,Oa)}catch{}if(!O||!O.documentElement){O=D.createDocument(po,"template",null);try{O.documentElement.innerHTML=Nf?F:te}catch{}}const ue=O.body||O.documentElement;return R&&V&&ue.insertBefore(n.createTextNode(V),ue.childNodes[0]||null),po===bn?oe.call(O,Ze?"html":"body")[0]:Ze?O.documentElement:ue},SS=function(R){const O=P?P(R):R.ownerDocument;return H.call(O||R,R,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},sl=function(R){return R=ia(R,ie," "),R=ia(R,Ce," "),R=ia(R,Ie," "),R},$f=function(R){var O;R.normalize();const V=P?P(R):R.ownerDocument,te=H.call(V||R,R,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let ue=te.nextNode();for(;ue;)ue.data=sl(ue.data),ue=te.nextNode();const be=(O=R.querySelectorAll)===null||O===void 0?void 0:O.call(R,"template");be&&Gr(be,xe=>{mo(xe.content)&&$f(xe.content)})},cl=function(R){const O=I?I(R):null;return typeof O!="string"||Ye(O)!=="form"?!1:typeof R.nodeName!="string"||typeof R.textContent!="string"||typeof R.removeChild!="function"||R.attributes!==w(R)||typeof R.removeAttribute!="function"||typeof R.setAttribute!="function"||typeof R.namespaceURI!="string"||typeof R.insertBefore!="function"||typeof R.hasChildNodes!="function"||R.nodeType!==_(R)||R.childNodes!==g(R)},mo=function(R){if(!_||typeof R!="object"||R===null)return!1;try{return _(R)===Lt.documentFragment}catch{return!1}},Ma=function(R){if(!_||typeof R!="object"||R===null)return!1;try{return typeof _(R)=="number"}catch{return!1}};function _n(X,R,O){X.length!==0&&Gr(X,V=>{V.call(t,R,O,fo)})}const mU=function(R,O){return!!(ot&&R.hasChildNodes()&&!Ma(R.firstElementChild)&>(hb,R.textContent)&>(hb,R.innerHTML)||ot&&R.namespaceURI===bn&&jD[O]&&(Ma(R.firstElementChild)||typeof R.textContent=="string"&>(OD[O],R.textContent))||R.nodeType===Lt.processingInstruction||ot&&R.nodeType===Lt.comment&>(gb,R.data))},ll=function(R,O){if(R instanceof RegExp)return gt(R,O);if(R instanceof Function){for(var V=arguments.length,te=new Array(V>2?V-2:0),ue=2;ue<V;ue++)te[ue-2]=arguments[ue];return!!R(O,...te)}return!1},hU=function(R,O,V){if(!re[O]&&kS(O)&&ll(Pe.tagNameCheck,O))return!1;if(kf&&!uo[O]){const te=h(R),ue=g(R);if(ue&&te){const be=ue.length;for(let xe=be-1;xe>=0;--xe){const St=R===V?f(ue[xe],!0):ue[xe];te.insertBefore(St,v(R))}}}return vr(R),!0},CS=function(R,O,V,te){return R.length===0?O:O===V||O===te?$t(O):O},IS=function(R,O){return R===O||h(R)!==null?!1:(Tf&&al(R),!0)},PS=function(R,O){if(_n(ee.beforeSanitizeElements,R,null),IS(R,O))return!0;if(cl(R))return vr(R),!0;const V=Ye(A(R));if(pe=CS(ee.uponSanitizeElement,pe,He,so),_n(ee.uponSanitizeElement,R,{tagName:V,allowedTags:pe}),IS(R,O))return!0;if(mU(R,V))return vr(R),!0;if(re[V]||!(it.tagCheck instanceof Function&&it.tagCheck(V))&&!pe[V]){const te=hU(R,V,O);return te===!1&&_n(ee.afterSanitizeElements,R,null),te}if(k(R)===Lt.element&&!uU(R)||(V==="noscript"||V==="noembed"||V==="noframes")&>($D,R.innerHTML))return vr(R),!0;if(me&&R.nodeType===Lt.text){const te=sl(R.textContent);R.textContent!==te&&(na(t.removed,{element:R.cloneNode()}),R.textContent=te)}return _n(ee.afterSanitizeElements,R,null),!1},RS=function(R,O,V){if(je[O]||_S(O,R)||nl&&(O==="id"||O==="name")&&(V in n||V in sU))return!1;const te=de[O]||it.attributeCheck instanceof Function&&it.attributeCheck(O,R);return Zt&>(Ne,O)||hr&>(le,O)?!0:te?pS[O]||gt(ge,ia(V,Y,""))||(O==="src"||O==="xlink:href"||O==="href")&&R!=="script"&&sb(V,"data:")===0&&dS[R]||Un&&!gt(ye,ia(V,Y,""))?!0:!V:kS(R)&&ll(Pe.tagNameCheck,R)&&ll(Pe.attributeNameCheck,O,R)||O==="is"&&Pe.allowCustomizedBuiltInElements&&ll(Pe.tagNameCheck,V)},gU=Ae({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),kS=function(R){return!gU[ra(R)]&>(ce,R)},vU=function(R,O,V,te){if(L&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!V)switch(u.getAttributeType(R,O)){case"TrustedHTML":return U(te);case"TrustedScriptURL":return $(te)}return te},yU=function(R,O,V,te){try{V?R.setAttributeNS(V,O,te):R.setAttribute(O,te),cl(R)?vr(R):ob(t.removed)}catch{si(O,R)}},TS=function(R){_n(ee.beforeSanitizeAttributes,R,null);const O=R.attributes;if(!O||cl(R))return;de=CS(ee.uponSanitizeAttribute,de,W,ai);const V={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:de,forceKeepAttr:void 0};let te=O.length;const ue=Ye(R.nodeName);for(;te--;){const be=O[te],xe=be.name,St=be.namespaceURI,en=be.value,Tt=Ye(xe),jf=en;let Ct=xe==="value"?jf:gD(jf);if(V.attrName=Tt,V.attrValue=Ct,V.keepAttr=!0,V.forceKeepAttr=void 0,_n(ee.uponSanitizeAttribute,R,V),Ct=V.attrValue,sS&&(Tt==="id"||Tt==="name")&&sb(Ct,cS)!==0&&(si(xe,R,be),Ct=cS+Ct),ot&>(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ct)){si(xe,R,be);continue}if(Tt==="attributename"&&ab(Ct,"href")){si(xe,R,be);continue}if(!V.forceKeepAttr){if(!V.keepAttr){si(xe,R,be);continue}if(!gr&>(LD,Ct)){si(xe,R,be);continue}if(me&&(Ct=sl(Ct)),!RS(ue,Tt,Ct)){si(xe,R,be);continue}Ct=vU(ue,Tt,St,Ct),Ct!==jf&&yU(R,xe,St,Ct)}}_n(ee.afterSanitizeAttributes,R,null)},dl=function(R){let O=null;const V=SS(R);for(_n(ee.beforeSanitizeShadowDOM,R,null);O=V.nextNode();)if(_n(ee.uponSanitizeShadowNode,O,null),PS(O,R),TS(O),mo(O.content)&&dl(O.content),k(O)===Lt.element){const te=y(O);mo(te)&&(Lf(te),dl(te))}_n(ee.afterSanitizeShadowDOM,R,null)},Lf=function(R){const O=[{node:R,shadow:null}];for(;O.length>0;){const V=O.pop();if(V.shadow){dl(V.shadow);continue}const te=V.node,ue=k(te)===Lt.element,be=g(te);if(be)for(let xe=be.length-1;xe>=0;--xe)O.push({node:be[xe],shadow:null});if(ue){const xe=I?I(te):null;if(typeof xe=="string"&&Ye(xe)==="template"){const St=te.content;mo(St)&&O.push({node:St,shadow:null})}}if(ue){const xe=y(te);mo(xe)&&O.push({node:null,shadow:xe},{node:xe,shadow:null})}}};return t.sanitize=function(X){let R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},O=null,V=null,te=null,ue=null;if(Nf=!X,Nf&&(X="<!-->"),typeof X!="string"&&!Ma(X)&&(X=wD(X),typeof X!="string"))throw Hr("dirty is not a string, aborting");if(!t.isSupported)return X;ao?(pe=so,de=ai):Df(R),(ee.uponSanitizeElement.length>0||ee.uponSanitizeAttribute.length>0)&&(pe=$t(pe)),ee.uponSanitizeAttribute.length>0&&(de=$t(de)),t.removed=[];const be=Tf&&typeof X!="string"&&Ma(X);if(be){fU(X);const en=A(X);if(typeof en=="string"){const Tt=Ye(en);if(!pe[Tt]||re[Tt])throw ol(X),Hr("root node is forbidden and cannot be sanitized in-place")}if(cl(X))throw ol(X),Hr("root node is clobbered and cannot be sanitized in-place");try{Lf(X)}catch(Tt){throw ol(X),Tt}}else if(Ma(X))O=wS("<!---->"),V=O.ownerDocument.importNode(X,!0),V.nodeType===Lt.element&&V.nodeName==="BODY"||V.nodeName==="HTML"?O=V:O.appendChild(V),Lf(V);else{if(!vn&&!me&&!Ze&&X.indexOf("<")===-1)return L&&yn?U(X):X;if(O=wS(X),!O)return vn?null:yn?F:""}O&&co&&vr(O.firstChild);const xe=be?X:O;try{const en=SS(xe);for(;te=en.nextNode();)PS(te,xe),TS(te),mo(te.content)&&dl(te.content)}catch(en){throw be&&(ol(X),Gr(t.removed,Tt=>{Tt.element&&al(Tt.element)})),en}if(be)return Gr(t.removed,en=>{en.element&&al(en.element)}),me&&$f(X),X;if(vn){if(me&&$f(O),_t)for(ue=G.call(O.ownerDocument);O.firstChild;)ue.appendChild(O.firstChild);else ue=O;return(de.shadowroot||de.shadowrootmode)&&(ue=ae.call(r,ue,!0)),ue}let St=Ze?O.outerHTML:O.innerHTML;return Ze&&pe["!doctype"]&&O.ownerDocument&&O.ownerDocument.doctype&&O.ownerDocument.doctype.name&>(xD,O.ownerDocument.doctype.name)&&(St="<!DOCTYPE "+O.ownerDocument.doctype.name+`>
|
|
44
|
+
`+St),me&&(St=sl(St)),L&&yn?U(St):St},t.setConfig=function(){let X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Df(X),ao=!0,so=pe,ai=de},t.clearConfig=function(){fo=null,ao=!1,so=null,ai=null,L=T,F=""},t.isValidAttribute=function(X,R,O){fo||Df({});const V=Ye(X),te=Ye(R);return RS(V,te,O)},t.addHook=function(X,R){typeof R=="function"&&kt(ee,X)&&na(ee[X],R)},t.removeHook=function(X,R){if(kt(ee,X)){if(R!==void 0){const O=mD(ee[X],R);return O===-1?void 0:hD(ee[X],O,1)[0]}return ob(ee[X])}},t.removeHooks=function(X){kt(ee,X)&&(ee[X]=[])},t.removeAllHooks=function(){ee=yb()},t}var _b=bb();function np(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Kr=np();function wb(e){Kr=e}var Vr={exec:()=>null};function Ki(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function Te(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(vt.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var BD=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),vt={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Ki(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Ki(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Ki(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Ki(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Ki(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Ki(e=>new RegExp(`^ {0,${e}}>`))},UD=/^(?:[ \t]*(?:\n|$))+/,qD=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,GD=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,aa=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,HD=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,rp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Sb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Cb=Te(Sb).replace(/bull/g,rp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),KD=Te(Sb).replace(/bull/g,rp).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ip=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,VD=/^[^\n]+/,op=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,zD=Te(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",op).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),WD=Te(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,rp).getRegex(),bc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ap=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,JD=Te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ap).replace("tag",bc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ib=e=>Te(ip).replace("hr",aa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",bc).getRegex(),YD=Ib(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),XD=Ib(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),sp={blockquote:Te(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",XD).getRegex(),code:qD,def:zD,fences:GD,heading:HD,hr:aa,html:JD,lheading:Cb,list:WD,newline:UD,paragraph:YD,table:Vr,text:VD},Pb=Te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",aa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",bc).getRegex(),QD={...sp,lheading:KD,table:Pb,paragraph:Te(ip).replace("hr",aa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pb).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",bc).getRegex()},ZD={...sp,html:Te(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ap).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Vr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Te(ip).replace("hr",aa).replace("heading",` *#{1,6} *[^
|
|
45
|
+
]`).replace("lheading",Cb).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},e$=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,t$=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Rb=/^( {2,}|\\)\n(?!\s*$)/,n$=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,On=/[\p{P}\p{S}]/u,Vi=/[\s\p{P}\p{S}]/u,sa=/[^\s\p{P}\p{S}]/u,r$=Te(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Vi).getRegex(),i$=/[\p{Pi}\p{Ps}"']/u,kb=/(?!~)[\p{P}\p{S}]/u,o$=/(?!~)[\s\p{P}\p{S}]/u,a$=/(?:[^\s\p{P}\p{S}]|~)/u,s$=Te(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",BD?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Tb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,c$=Te(Tb,"u").replace(/punct/g,On).getRegex(),l$=Te(Tb,"u").replace(/punct/g,kb).getRegex(),d$=Te(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,"u").replace(/openQuote/g,i$).replace(/punct/g,On).getRegex(),Nb="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",u$=Te(Nb,"gu").replace(/notPunctSpace/g,sa).replace(/punctSpace/g,Vi).replace(/punct/g,On).getRegex(),p$=Te(Nb,"gu").replace(/notPunctSpace/g,a$).replace(/punctSpace/g,o$).replace(/punct/g,kb).getRegex(),f$=Te("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,sa).replace(/punctSpace/g,Vi).replace(/punct/g,On).getRegex(),m$=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,sa).replace(/punctSpace/g,Vi).replace(/punct/g,On).getRegex(),h$=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,sa).replace(/punctSpace/g,Vi).replace(/punct/g,On).getRegex(),g$=Te(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,On).getRegex(),v$=Te("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,sa).replace(/punctSpace/g,Vi).replace(/punct/g,On).getRegex(),y$=Te(/\\(punct)/,"gu").replace(/punct/g,On).getRegex(),b$=Te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),_$=Te(ap).replace("(?:-->|$)","-->").getRegex(),w$=Te("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_$).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_c=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,S$=Te(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",_c).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Eb=Te(/^!?\[(label)\]\[(ref)\]/).replace("label",_c).replace("ref",op).getRegex(),Ab=Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",op).getRegex(),C$=Te("reflink|nolink(?!\\()","g").replace("reflink",Eb).replace("nolink",Ab).getRegex(),xb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,cp={_backpedal:Vr,anyPunctuation:y$,autolink:b$,blockSkip:s$,br:Rb,code:t$,del:Vr,delLDelim:Vr,delRDelim:Vr,emStrongLDelim:c$,emStrongRDelimAst:u$,emStrongRDelimUnd:m$,escape:e$,link:S$,nolink:Ab,punctuation:r$,reflink:Eb,reflinkSearch:C$,tag:w$,text:n$,url:Vr},I$={...cp,emStrongLDelim:d$,emStrongRDelimAst:f$,emStrongRDelimUnd:h$,link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",_c).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_c).getRegex()},lp={...cp,emStrongRDelimAst:p$,emStrongLDelim:l$,delLDelim:g$,delRDelim:v$,url:Te(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",xb).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Te(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",xb).getRegex()},P$={...lp,br:Te(Rb).replace("{2,}","*").getRegex(),text:Te(lp.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},wc={normal:sp,gfm:QD,pedantic:ZD},ca={normal:cp,gfm:lp,breaks:P$,pedantic:I$},R$={"&":"&","<":"<",">":">",'"':""","'":"'"},Db=e=>R$[e];function fn(e,t){if(t){if(vt.escapeTest.test(e))return e.replace(vt.escapeReplace,Db)}else if(vt.escapeTestNoEncode.test(e))return e.replace(vt.escapeReplaceNoEncode,Db);return e}function $b(e){try{e=encodeURI(e).replace(vt.percentDecode,"%")}catch{return null}return e}function Lb(e,t){let n=e.replace(vt.findPipe,(i,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(vt.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(vt.slashPipe,"|");return n}function or(e,t,n){let r=e.length;if(r===0)return"";let i=0;for(;i<r;){let o=e.charAt(r-i-1);if(o===t&&!n)i++;else if(o!==t&&n)i++;else break}return e.slice(0,r-i)}function jb(e){let t=e.split(`
|
|
46
|
+
`),n=t.length-1;for(;n>=0&&vt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
47
|
+
`)}function k$(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function T$(e,t=0){let n=t,r="";for(let i of e)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function Ob(e,t,n,r,i){let o=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";r.state.inLink=!0;let d=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let p=r.inlineTokens(c),f=r.state.linkEmitted;if(r.state.linkEmitted=d,r.state.inLink=!1,!l){if(f){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:l?"image":"link",raw:n,href:o,title:s,text:c,tokens:p}}function N$(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
48
|
+
`).map(o=>{let s=o.match(n.other.beginningSpace);if(s===null)return o;let[c]=s;return c.length>=i.length?o.slice(i.length):o}).join(`
|
|
49
|
+
`)}var Sc=class{options;rules;lexer;constructor(e){this.options=e||Kr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:jb(t[0]);return{type:"code",raw:n,codeBlockStyle:"indented",text:n.replace(this.rules.other.codeRemoveIndent,"")}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=N$(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=or(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:or(t[0],`
|
|
50
|
+
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:or(t[0],`
|
|
51
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=or(t[0],`
|
|
56
52
|
`).split(`
|
|
57
|
-
`),r="",i="",
|
|
53
|
+
`),r="",i="",o=[];for(;n.length>0;){let s=!1,c=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))c.push(n[l]),s=!0;else if(!s)c.push(n[l]);else break;n=n.slice(l);let d=c.join(`
|
|
58
54
|
`),u=d.replace(this.rules.other.blockquoteSetextReplace,`
|
|
59
55
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
60
56
|
${d}`:d,i=i?`${i}
|
|
61
|
-
${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,
|
|
57
|
+
${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=p,n.length===0)break;let f=o.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let m=f,v=n.join(`
|
|
58
|
+
`),g=m.raw+`
|
|
59
|
+
`+v.replace(this.rules.other.blockquoteSetextReplace2,""),h=this.blockquote(g);o[o.length-1]=h,r=`${r}
|
|
60
|
+
${v}`,i=i.substring(0,i.length-m.text.length)+h.text;break}else if(f?.type==="list"){let m=f,v=m.raw+`
|
|
62
61
|
`+n.join(`
|
|
63
|
-
`),
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`,1)
|
|
68
|
-
`,1)[0],
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
`),
|
|
75
|
-
`):[],a={type:"table",raw:jn(t[0],`
|
|
76
|
-
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?a.align.push("right"):this.rules.other.tableAlignCenter.test(s)?a.align.push("center"):this.rules.other.tableAlignLeft.test(s)?a.align.push("left"):a.align.push(null);for(let s=0;s<n.length;s++)a.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:a.align[s]});for(let s of i)a.rows.push(Uy(s,a.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:jn(t[0],`
|
|
62
|
+
`),g=this.list(v);o[o.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,i=i.substring(0,i.length-m.raw.length)+g.raw,n=v.substring(o.at(-1).raw.length).split(`
|
|
63
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let o=this.rules.other.listItemRegex(n),s=!1;for(;e;){let l=!1,d="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=T$(t[2].split(`
|
|
64
|
+
`,1)[0],t[1].length),f=e.split(`
|
|
65
|
+
`,1)[0],m=!p.trim(),v=0;if(this.options.pedantic?(v=2,u=p.trimStart()):m?v=t[1].length+1:(v=p.search(this.rules.other.nonSpaceChar),v=v>4?1:v,u=p.slice(v),v+=t[1].length),m&&this.rules.other.blankLine.test(f)&&(d+=f+`
|
|
66
|
+
`,e=e.substring(f.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(v),h=this.rules.other.hrRegex(v),y=this.rules.other.fencesBeginRegex(v),w=this.rules.other.headingBeginRegex(v),_=this.rules.other.htmlBeginRegex(v),I=this.rules.other.blockquoteBeginRegex(v);for(;e;){let P=e.split(`
|
|
67
|
+
`,1)[0],k;if(f=P,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),k=f):k=f.replace(this.rules.other.tabCharGlobal," "),y.test(f)||w.test(f)||_.test(f)||I.test(f)||g.test(f)||h.test(f))break;if(k.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
|
|
68
|
+
`+k.slice(v);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||y.test(p)||w.test(p)||h.test(p))break;u+=`
|
|
69
|
+
`+f}m=!f.trim(),d+=P+`
|
|
70
|
+
`,e=e.substring(P.length+1),p=k.slice(v)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(s=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=d}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!i.loose){let d=l.tokens.filter(u=>u.type==="space");i.loose=d.length>0&&d.some(u=>this.rules.other.anyLine.test(u.raw))}for(let l of i.items){let d=l.tokens[0];if(l.task&&(d?.type==="text"||d?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=p.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=p.raw+l.tokens[0].raw,l.tokens[0].text=p.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(p)):l.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):l.tokens.unshift(p)}}else l.task&&(l.task=!1)}if(i.loose)for(let l of i.items){l.loose=!0;for(let d of l.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=jb(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:or(t[0],`
|
|
71
|
+
`),href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Lb(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
72
|
+
`):[],o={type:"table",raw:or(t[0],`
|
|
73
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(Lb(s,o.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:o.align[l]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:or(t[0],`
|
|
77
74
|
`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
78
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let
|
|
79
|
-
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(
|
|
80
|
-
`:n.push(
|
|
75
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=or(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=k$(t[2],"()");if(o===-2)return;if(o>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ob(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Ob(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,c=i,l=0,d=r[0][0],u=n===d,p=d==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(r=p.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){c+=s;continue}else if(r[5]||r[6]){if(i%3&&!((i+s)%3)){l+=s;continue}if(u)break}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let f=[...r[0]][0].length,m=e.slice(0,i+r.index+f+s);if(Math.min(i,s)%2){let g=m.slice(1,-1);return{type:"em",raw:m,text:g,tokens:this.lexer.inlineTokens(g)}}let v=m.slice(2,-2);return{type:"strong",raw:m,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,o,s,c=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+i);(r=l.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))continue;if(r[3]||r[4]){c+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c);let d=[...r[0]][0].length,u=e.slice(0,i+r.index+d+s),p=u.slice(i,-i);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Xt=class Of{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Kr,this.options.tokenizer=this.options.tokenizer||new Sc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let n={other:vt,block:wc.normal,inline:ca.normal};this.options.pedantic?(n.block=wc.pedantic,n.inline=ca.pedantic):this.options.gfm&&(n.block=wc.gfm,this.options.breaks?n.inline=ca.breaks:n.inline=ca.gfm),this.tokenizer.rules=n}static get rules(){return{block:wc,inline:ca}}static lex(t,n){return new Of(n).lex(t)}static lexInline(t,n){return new Of(n).inlineTokens(t)}lex(t){t=t.replace(vt.carriageReturn,`
|
|
76
|
+
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(vt.tabCharGlobal," ").replace(vt.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(c=>(o=c.call({lexer:this},t,n))?(t=t.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let c=n.at(-1);o.raw.length===1&&c!==void 0?c.raw+=`
|
|
77
|
+
`:n.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
81
78
|
`)?"":`
|
|
82
|
-
`)+
|
|
83
|
-
`+
|
|
79
|
+
`)+o.raw,c.text+=`
|
|
80
|
+
`+o.text,this.inlineQueue.at(-1).src=c.text):n.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
84
81
|
`)?"":`
|
|
85
|
-
`)+
|
|
86
|
-
`+
|
|
82
|
+
`)+o.raw,c.text+=`
|
|
83
|
+
`+o.raw,this.inlineQueue.at(-1).src=c.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),n.push(o);continue}let s=t;if(this.options.extensions?.startBlock){let c=1/0,l=t.slice(1),d;this.options.extensions.startBlock.forEach(u=>{d=u.call({lexer:this},l),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(s=t.substring(0,c+1))}if(this.state.top&&(o=this.tokenizer.paragraph(s))){let c=n.at(-1);r&&c?.type==="paragraph"?(c.raw+=(c.raw.endsWith(`
|
|
87
84
|
`)?"":`
|
|
88
|
-
`)+
|
|
89
|
-
`+
|
|
85
|
+
`)+o.raw,c.text+=`
|
|
86
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(o),r=s.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let c=n.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
90
87
|
`)?"":`
|
|
91
|
-
`)+
|
|
92
|
-
`+
|
|
93
|
-
`;return r?'<pre><code class="language-'+
|
|
94
|
-
`:"<pre><code>"+(n?i:
|
|
88
|
+
`)+o.raw,c.text+=`
|
|
89
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}linkInText(t){if(!t.includes("["))return!1;let n=this.tokenizer.rules.inline.link;for(let r of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(n.test(r[0])&&t.charAt(r.index-1)!=="!")return!0;for(let r of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=r[0],o=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(o+1,-1)))&&!(o>1&&this.linkInText(i.slice(1,o-1))))return!0}return!1}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t;if(this.tokens.links&&t.includes("[")){let c=this.tokenizer.rules.inline.reflinkSearch,l=d=>{let u=d.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,d.slice(u+1,-1)))return d;if(u>1&&d.charAt(0)!=="!"){let p=d.slice(1,u-1);if(this.linkInText(p))return"["+p.replace(c,l)+"]["+"a".repeat(d.length-u-2)+"]"}return"["+"a".repeat(d.length-2)+"]"};r=r.replace(c,l)}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,c=>"+".repeat(c.length)),r=r.replace(this.tokenizer.rules.inline.blockSkip,(c,l,d)=>{let u=d?d.length:0;return c.slice(0,u)+"["+"a".repeat(c.length-u-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,o="",s=1/0;for(;t;){if(t.length<s)s=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(o=""),i=!1;let c;if(this.options.extensions?.inline?.some(d=>(c=d.call({lexer:this},t,n))?(t=t.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(c.raw.length);let d=n.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(t,r,o)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(t)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(t,r,o)){t=t.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(t)){t=t.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(t))){t=t.substring(c.raw.length),n.push(c);continue}let l=t;if(this.options.extensions?.startInline){let d=1/0,u=t.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},u),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(l=t.substring(0,d+1))}if(c=this.tokenizer.inlineText(l)){t=t.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(o=c.raw.slice(-1)),i=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},Cc=class{options;parser;constructor(e){this.options=e||Kr}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(vt.notSpaceStart)?.[0],i=e.replace(vt.endingNewline,"")+`
|
|
90
|
+
`;return r?'<pre><code class="language-'+fn(r)+'">'+(n?i:fn(i,!0))+`</code></pre>
|
|
91
|
+
`:"<pre><code>"+(n?i:fn(i,!0))+`</code></pre>
|
|
95
92
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
96
93
|
${this.parser.parse(e)}</blockquote>
|
|
97
94
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
98
95
|
`}hr(e){return`<hr>
|
|
99
|
-
`}list(e){let t=e.ordered,n=e.start,r="";for(let s=0;s<e.items.length;s++){let c=e.items[s];r+=this.listitem(c)}let i=t?"ol":"ul",
|
|
96
|
+
`}list(e){let t=e.ordered,n=e.start,r="";for(let s=0;s<e.items.length;s++){let c=e.items[s];r+=this.listitem(c)}let i=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+i+o+`>
|
|
100
97
|
`+r+"</"+i+`>
|
|
101
98
|
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
102
99
|
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
103
|
-
`}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let r="";for(let i=0;i<e.rows.length;i++){let
|
|
100
|
+
`}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let r="";for(let i=0;i<e.rows.length;i++){let o=e.rows[i];n="";for(let s=0;s<o.length;s++)n+=this.tablecell(o[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
|
|
104
101
|
<thead>
|
|
105
102
|
`+t+`</thead>
|
|
106
103
|
`+r+`</table>
|
|
107
104
|
`}tablerow({text:e}){return`<tr>
|
|
108
105
|
${e}</tr>
|
|
109
106
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
110
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${
|
|
111
|
-
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+Qt(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},gr=new c0;function De(e,t){return gr.parse(e,t)}De.options=De.setOptions=function(e){return gr.setOptions(e),De.defaults=gr.defaults,ky(De.defaults),De},De.getDefaults=Ld,De.defaults=fr,De.use=function(...e){return gr.use(...e),De.defaults=gr.defaults,ky(De.defaults),De},De.walkTokens=function(e,t){return gr.walkTokens(e,t)},De.parseInline=gr.parseInline,De.Parser=jt,De.parser=jt.parse,De.Renderer=Ms,De.TextRenderer=Hd,De.Lexer=Ot,De.lexer=Ot.lex,De.Tokenizer=$s,De.Hooks=_a,De.parse=De;var pF=De.options,mF=De.setOptions,fF=De.use,hF=De.walkTokens,gF=De.parseInline,vF=De,yF=jt.parse,bF=Ot.lex,l0={ALLOWED_TAGS:["p","br","strong","em","code","pre","ul","ol","li","blockquote","a","h1","h2","h3","h4","h5","h6","hr"],ALLOWED_ATTR:["href","title"],ALLOW_DATA_ATTR:!1};function d0(e){const t=String(e||"").trim();if(!t)return!1;if(t.startsWith("#")||t.startsWith("/"))return!0;const n=t.toLowerCase();return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("mailto:")}Iy.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(d0(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function qd(e){const t=De.parse(String(e||""),{async:!1});return Iy.sanitize(t,l0)}function u0(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=Object.keys(e);return t.filter(r=>n.includes(r)).map(r=>{const i=String(e[r]||"").trim();return i?y("div",{className:"summary-section",key:r},y("div",{className:"summary-section-label"},XA(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:qd(i)}})):null}).filter(Boolean)}function p0(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const a=r.indexOf(":"),s=r.slice(0,a).trim(),c=r.slice(a+1).trim();return!s||!c?null:y("div",{className:"summary-section",key:`${s}-${i}`},y("div",{className:"summary-section-label"},s),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:qd(c)}}))}).filter(Boolean);if(n.length)return y("div",{className:"feed-body facts"},n)}return y("div",{className:"feed-body"},y("ul",null,t.map((n,r)=>y("li",{key:`${n}-${r}`},n))))}function qy(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:qd(n)}}):null}function m0(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const a=String(e?.body_text||"").trim();if(a.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(a);d;d=l.exec(a)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function Os(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function f0(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Os(e,t)?"session_summary":n||"change"}var Kd=["Enter"," "],h0=["ArrowDown","PageUp","Home"],Ky=["ArrowUp","PageDown","End"],g0=[...h0,...Ky],v0={ltr:[...Kd,"ArrowRight"],rtl:[...Kd,"ArrowLeft"]},y0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},wa="Menu",[Sa,b0,_0]=Uo(wa),[vr,Vy]=st(wa,[_0,Pn,zr]),Ca=Pn(),Wy=zr(),[zy,Fn]=vr(wa),[w0,Na]=vr(wa),Jy=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:s=!0}=e,c=Ca(t),[l,d]=x(null),u=B(!1),p=lt(a),m=ea(i);return J(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),o(ia,{...c,children:o(zy,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:o(w0,{scope:t,onClose:se(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Jy.displayName=wa;var S0="MenuAnchor",Vd=V((e,t)=>{const{__scopeMenu:n,...r}=e,i=Ca(n);return o(aa,{...i,...r,ref:t})});Vd.displayName=S0;var Wd="MenuPortal",[C0,Yy]=vr(Wd,{forceMount:void 0}),Xy=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=Fn(Wd,t);return o(C0,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Zn,{asChild:!0,container:i,children:r})})})};Xy.displayName=Wd;var kt="MenuContent",[N0,zd]=vr(kt),Qy=V((e,t)=>{const n=Yy(kt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=Fn(kt,e.__scopeMenu),s=Na(kt,e.__scopeMenu);return o(Sa.Provider,{scope:e.__scopeMenu,children:o(nt,{present:r||a.open,children:o(Sa.Slot,{scope:e.__scopeMenu,children:s.modal?o(T0,{...i,ref:t}):o(I0,{...i,ref:t})})})})}),T0=V((e,t)=>{const n=Fn(kt,e.__scopeMenu),r=B(null),i=Se(t,r);return J(()=>{const a=r.current;if(a)return Io(a)},[]),o(Jd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Q(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),I0=V((e,t)=>{const n=Fn(kt,e.__scopeMenu);return o(Jd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),k0=Xn("MenuContent.ScrollLock"),Jd=V((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,disableOutsideScroll:g,...h}=e,v=Fn(kt,n),w=Na(kt,n),b=Ca(n),S=Wy(n),C=b0(n),[T,P]=x(null),k=B(null),M=Se(t,k,v.onContentChange),U=B(0),E=B(""),j=B(0),O=B(null),q=B("right"),L=B(0),R=g?Ui:Z,A=g?{as:k0,allowPinchZoom:!0}:void 0,I=F=>{const K=E.current+F,ce=C().filter(he=>!he.disabled),ie=document.activeElement,re=ce.find(he=>he.ref.current===ie)?.textValue,ye=B0(ce.map(he=>he.textValue),K,re),Y=ce.find(he=>he.textValue===ye)?.ref.current;(function he(ne){E.current=ne,window.clearTimeout(U.current),ne!==""&&(U.current=window.setTimeout(()=>he(""),1e3))})(K),Y&&setTimeout(()=>Y.focus())};J(()=>()=>window.clearTimeout(U.current),[]),yo();const D=se(F=>q.current===O.current?.side&&G0(F,O.current?.area),[]);return o(N0,{scope:n,searchRef:E,onItemEnter:se(F=>{D(F)&&F.preventDefault()},[D]),onItemLeave:se(F=>{D(F)||(k.current?.focus(),P(null))},[D]),onTriggerLeave:se(F=>{D(F)&&F.preventDefault()},[D]),pointerGraceTimerRef:j,onPointerGraceIntentChange:se(F=>{O.current=F},[]),children:o(R,{...A,children:o(Fi,{asChild:!0,trapped:i,onMountAutoFocus:Q(a,F=>{F.preventDefault(),k.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:o(Qn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:o(Pl,{asChild:!0,...S,dir:w.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:P,onEntryFocus:Q(l,F=>{w.isUsingKeyboardRef.current||F.preventDefault()}),preventScrollOnEntryFocus:!0,children:o(os,{role:"menu","aria-orientation":"vertical","data-state":hb(v.open),"data-radix-menu-content":"",dir:w.dir,...b,...h,ref:M,style:{outline:"none",...h.style},onKeyDown:Q(h.onKeyDown,F=>{const K=F.target.closest("[data-radix-menu-content]")===F.currentTarget,ce=F.ctrlKey||F.altKey||F.metaKey,ie=F.key.length===1;K&&(F.key==="Tab"&&F.preventDefault(),!ce&&ie&&I(F.key));const re=k.current;if(F.target!==re||!g0.includes(F.key))return;F.preventDefault();const ye=C().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);Ky.includes(F.key)&&ye.reverse(),j0(ye)}),onBlur:Q(e.onBlur,F=>{F.currentTarget.contains(F.target)||(window.clearTimeout(U.current),E.current="")}),onPointerMove:Q(e.onPointerMove,Ia(F=>{const K=F.target,ce=L.current!==F.clientX;F.currentTarget.contains(K)&&ce&&(q.current=F.clientX>L.current?"right":"left",L.current=F.clientX)}))})})})})})})});Qy.displayName=kt;var E0="MenuGroup",Yd=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{role:"group",...r,ref:t})});Yd.displayName=E0;var P0="MenuLabel",Zy=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{...r,ref:t})});Zy.displayName=P0;var js="MenuItem",eb="menu.itemSelect",Fs=V((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,a=B(null),s=Na(js,e.__scopeMenu),c=zd(js,e.__scopeMenu),l=Se(t,a),d=B(!1),u=()=>{const p=a.current;if(!n&&p){const m=new CustomEvent(eb,{bubbles:!0,cancelable:!0});p.addEventListener(eb,f=>r?.(f),{once:!0}),Kc(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return o(tb,{...i,ref:l,disabled:n,onClick:Q(e.onClick,u),onPointerDown:p=>{e.onPointerDown?.(p),d.current=!0},onPointerUp:Q(e.onPointerUp,p=>{d.current||p.currentTarget?.click()}),onKeyDown:Q(e.onKeyDown,p=>{const m=c.searchRef.current!=="";n||m&&p.key===" "||Kd.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});Fs.displayName=js;var tb=V((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,s=zd(js,n),c=Wy(n),l=B(null),d=Se(t,l),[u,p]=x(!1),[m,f]=x("");return J(()=>{const g=l.current;g&&f((g.textContent??"").trim())},[a.children]),o(Sa.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:o(Al,{asChild:!0,...c,focusable:!r,children:o(pe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...a,ref:d,onPointerMove:Q(e.onPointerMove,Ia(g=>{r?s.onItemLeave(g):(s.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Q(e.onPointerLeave,Ia(g=>s.onItemLeave(g))),onFocus:Q(e.onFocus,()=>p(!0)),onBlur:Q(e.onBlur,()=>p(!1))})})})}),A0="MenuCheckboxItem",nb=V((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o(sb,{scope:e.__scopeMenu,checked:n,children:o(Fs,{role:"menuitemcheckbox","aria-checked":Bs(n)?"mixed":n,...i,ref:t,"data-state":Zd(n),onSelect:Q(i.onSelect,()=>r?.(Bs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});nb.displayName=A0;var rb="MenuRadioGroup",[x0,R0]=vr(rb,{value:void 0,onValueChange:()=>{}}),ib=V((e,t)=>{const{value:n,onValueChange:r,...i}=e,a=lt(r);return o(x0,{scope:e.__scopeMenu,value:n,onValueChange:a,children:o(Yd,{...i,ref:t})})});ib.displayName=rb;var ab="MenuRadioItem",ob=V((e,t)=>{const{value:n,...r}=e,i=R0(ab,e.__scopeMenu),a=n===i.value;return o(sb,{scope:e.__scopeMenu,checked:a,children:o(Fs,{role:"menuitemradio","aria-checked":a,...r,ref:t,"data-state":Zd(a),onSelect:Q(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});ob.displayName=ab;var Xd="MenuItemIndicator",[sb,D0]=vr(Xd,{checked:!1}),cb=V((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,a=D0(Xd,n);return o(nt,{present:r||Bs(a.checked)||a.checked===!0,children:o(pe.span,{...i,ref:t,"data-state":Zd(a.checked)})})});cb.displayName=Xd;var L0="MenuSeparator",lb=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});lb.displayName=L0;var $0="MenuArrow",db=V((e,t)=>{const{__scopeMenu:n,...r}=e,i=Ca(n);return o(ss,{...i,...r,ref:t})});db.displayName=$0;var Qd="MenuSub",[M0,ub]=vr(Qd),O0=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=Fn(Qd,t),s=Ca(t),[c,l]=x(null),[d,u]=x(null),p=lt(i);return J(()=>(a.open===!1&&p(!1),()=>p(!1)),[a.open,p]),o(ia,{...s,children:o(zy,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:o(M0,{scope:t,contentId:ct(),triggerId:ct(),trigger:c,onTriggerChange:l,children:n})})})};O0.displayName=Qd;var Ta="MenuSubTrigger",pb=V((e,t)=>{const n=Fn(Ta,e.__scopeMenu),r=Na(Ta,e.__scopeMenu),i=ub(Ta,e.__scopeMenu),a=zd(Ta,e.__scopeMenu),s=B(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=a,d={__scopeMenu:e.__scopeMenu},u=se(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return J(()=>u,[u]),J(()=>{const p=c.current;return()=>{window.clearTimeout(p),l(null)}},[c,l]),o(Vd,{asChild:!0,...d,children:o(tb,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":hb(n.open),...e,ref:go(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Q(e.onPointerMove,Ia(p=>{a.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(a.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:Q(e.onPointerLeave,Ia(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,g=f==="right",h=g?-5:5,v=m[g?"left":"right"],w=m[g?"right":"left"];a.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:v,y:m.top},{x:w,y:m.top},{x:w,y:m.bottom},{x:v,y:m.bottom}],side:f}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(p),p.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:Q(e.onKeyDown,p=>{const m=a.searchRef.current!=="";e.disabled||m&&p.key===" "||v0[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});pb.displayName=Ta;var mb="MenuSubContent",fb=V((e,t)=>{const n=Yy(kt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=Fn(kt,e.__scopeMenu),s=Na(kt,e.__scopeMenu),c=ub(mb,e.__scopeMenu),l=B(null),d=Se(t,l);return o(Sa.Provider,{scope:e.__scopeMenu,children:o(nt,{present:r||a.open,children:o(Sa.Slot,{scope:e.__scopeMenu,children:o(Jd,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Q(e.onFocusOutside,u=>{u.target!==c.trigger&&a.onOpenChange(!1)}),onEscapeKeyDown:Q(e.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:Q(e.onKeyDown,u=>{const p=u.currentTarget.contains(u.target),m=y0[s.dir].includes(u.key);p&&m&&(a.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});fb.displayName=mb;function hb(e){return e?"open":"closed"}function Bs(e){return e==="indeterminate"}function Zd(e){return Bs(e)?"indeterminate":e?"checked":"unchecked"}function j0(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function F0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function B0(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=F0(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function U0(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function G0(e,t){return t?U0({x:e.clientX,y:e.clientY},t):!1}function Ia(e){return t=>t.pointerType==="mouse"?e(t):void 0}var H0=Jy,q0=Vd,K0=Xy,V0=Qy,W0=Yd,z0=Zy,J0=Fs,Y0=nb,X0=ib,Q0=ob,Z0=cb,eD=lb,tD=db,nD=pb,rD=fb,Us="DropdownMenu",[iD,_F]=st(Us,[Vy]),pt=Vy(),[aD,gb]=iD(Us),vb=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:s,modal:c=!0}=e,l=pt(t),d=B(null),[u,p]=It({prop:i,defaultProp:a??!1,onChange:s,caller:Us});return o(aD,{scope:t,triggerId:ct(),triggerRef:d,contentId:ct(),open:u,onOpenChange:p,onOpenToggle:se(()=>p(m=>!m),[p]),modal:c,children:o(H0,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};vb.displayName=Us;var yb="DropdownMenuTrigger",bb=V((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=gb(yb,n),s=pt(n);return o(q0,{asChild:!0,...s,children:o(pe.button,{type:"button",id:a.triggerId,"aria-haspopup":"menu","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:go(t,a.triggerRef),onPointerDown:Q(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(a.onOpenToggle(),a.open||c.preventDefault())}),onKeyDown:Q(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&a.onOpenToggle(),c.key==="ArrowDown"&&a.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});bb.displayName=yb;var oD="DropdownMenuPortal",_b=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pt(t);return o(K0,{...r,...n})};_b.displayName=oD;var wb="DropdownMenuContent",Sb=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=gb(wb,n),a=pt(n),s=B(!1);return o(V0,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:Q(e.onCloseAutoFocus,c=>{s.current||i.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Q(e.onInteractOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;(!i.modal||u)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Sb.displayName=wb;var sD="DropdownMenuGroup",cD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(W0,{...i,...r,ref:t})});cD.displayName=sD;var lD="DropdownMenuLabel",dD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(z0,{...i,...r,ref:t})});dD.displayName=lD;var uD="DropdownMenuItem",Cb=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(J0,{...i,...r,ref:t})});Cb.displayName=uD;var pD="DropdownMenuCheckboxItem",mD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(Y0,{...i,...r,ref:t})});mD.displayName=pD;var fD="DropdownMenuRadioGroup",hD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(X0,{...i,...r,ref:t})});hD.displayName=fD;var gD="DropdownMenuRadioItem",vD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(Q0,{...i,...r,ref:t})});vD.displayName=gD;var yD="DropdownMenuItemIndicator",bD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(Z0,{...i,...r,ref:t})});bD.displayName=yD;var _D="DropdownMenuSeparator",wD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(eD,{...i,...r,ref:t})});wD.displayName=_D;var SD="DropdownMenuArrow",CD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(tD,{...i,...r,ref:t})});CD.displayName=SD;var ND="DropdownMenuSubTrigger",TD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(nD,{...i,...r,ref:t})});TD.displayName=ND;var ID="DropdownMenuSubContent",kD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(rD,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});kD.displayName=ID;var ED=vb,PD=bb,AD=_b,xD=Sb,Nb=Cb;function RD({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(ED,null,y(PD,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(AD,null,y(xD,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(Nb,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(Nb,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function DD({modes:e,active:t,onSelect:n}){return e.length<=1?null:y("div",{className:"feed-toggle"},e.map(r=>y("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function eu({label:e,variant:t=""}){return y(Id,{variant:"provenance",tone:t||void 0},e)}function LD({tag:e}){const t=Jv(e);return t?y(Id,{variant:"tag",title:String(e)},t):null}function $D({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const a=Cs(e?.metadata_json),s=Os(e,a),c=f0(e,a),l=ft(e),d=e.title||"(untitled)",u=s&&a?.request?a.request:d,p=e.created_at||e.created_at_utc,m=zA(p),f=rx(e),g=Ss(e.files||[]),h=e.project||"",v=ox(e),w=sx(e,a),b=String(e.visibility||a?.visibility||"private").trim(),S=String(e.workspace_kind||a?.workspace_kind||"").trim(),C=String(e.origin_source||a?.origin_source||"").trim(),T=String(e.trust_state||a?.trust_state||"").trim(),P=f.length?` · ${f.map(ve=>Jv(ve)).join(", ")}`:"",k=g.length?` · ${QA(g)}`:"",M=Number(e.id||0),U=M>0?`ID ${M}`:"",[E,j]=x(_.newItemKeys.has(l)),O=s?m0({...e,metadata_json:a}):null,q=s?null:Ox({...e,metadata_json:a}),L=q?jx(q):[],R=q?Fx(q):"summary",A=_.itemViewState.get(l),[I,D]=x(q&&A&&L.some(ve=>ve.id===A)?A:R),F=`${l}:${I}`,[K,ce]=x(_.itemExpandState.get(F)===!0),[ie,re]=x(b==="shared"?"shared":"private"),[ye,Y]=x(!1),[he,ne]=x(!1),[ke,ge]=x(!1),ae=O?u0(O):[];J(()=>{q&&(L.some(ve=>ve.id===I)||D(R))},[I,R,L,q]),J(()=>{_.itemViewState.set(l,I)},[I,l]),J(()=>{const ve=`${l}:${I}`;ce(_.itemExpandState.get(ve)===!0)},[I,l]),J(()=>{re(b==="shared"?"shared":"private")},[b]),J(()=>{if(!E)return;const ve=window.setTimeout(()=>{_.newItemKeys.delete(l),j(!1)},700);return()=>window.clearTimeout(ve)},[E,l]);const xe=ie,de=xe==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",Te=[h?`Project ${h}`:"No project",m].filter(Boolean).join(" · "),ue=[S&&S!==b?`Workspace ${S}`:"",C?`From ${C}`:"",w,T&&T!=="trusted"?ax(T):""].filter(Boolean).join(" · "),z=[`${P}${k}`.trim(),ue].filter(Boolean).join(" · "),G=!!q&&Bx(I,q),W=[I==="facts"?"feed-body facts":"feed-body",G&&!K?Ux(I).join(" "):""].filter(Boolean).join(" "),be=s?ae.length?y("div",{className:"feed-body facts"},ae):qy(String(e.body_text||""))||y("div",{className:"feed-body"}):q?I==="facts"?p0(q.facts)||y("div",{className:W}):qy(I==="narrative"?q.narrative:q.summary,W)||y("div",{className:W}):y("div",{className:"feed-body"});async function Ce(ve){const vt=xe;re(ve),Y(!0);try{const Nt=await Zw(M,ve);Nt?.item&&(t(Nt.item),r()),oe(ve==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Nt){re(vt),oe(Nt instanceof Error?Nt.message:"Failed to save visibility.","warning")}finally{Y(!1)}}async function ht(){const ve=String(e.project||"").trim(),vt=ve,Nt=String(u||"this memory").trim(),Ii=Nt.length>80?`${Nt.slice(0,79).trimEnd()}…`:Nt,Ya=ve?`Move "${Ii}" from "${ve}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${Ii}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let bn=[];try{bn=(await eo()).filter(yt=>yt&&yt!==ve)}catch{}const Pr=await pd({title:"Assign to project",description:Ya,initialValue:vt,placeholder:"Pick one or type a new project name",suggestions:bn,confirmLabel:"Move",cancelLabel:"Cancel",validate:yt=>{const Wn=yt.trim();return Wn?Wn===ve?"Already assigned to this project.":null:"Enter a project name."}});if(Pr==null)return;const Vn=Pr.trim();if(!(!Vn||Vn===ve)){ge(!0);try{const yt=await eS(M,Vn),Wn=Number(yt.moved_memory_count||1);oe(Wn>1?`Moved ${Wn} memories from this session to "${yt.project}".`:`Moved to "${yt.project}".`),await i(),r()}catch(yt){oe(yt instanceof Error?yt.message:"Failed to move memory.","warning")}finally{ge(!1)}}}async function Ft(){const ve=String(u||"this memory").trim();if(await Jt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${ve.length>80?`${ve.slice(0,79).trimEnd()}…`:ve}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){ne(!0);try{await tS(M),n(M),r(),await i(),oe("Memory forgotten and removed from the active feed.")}catch(vt){oe(vt instanceof Error?vt.message:"Failed to forget memory.","warning")}finally{ne(!1)}}}const gt=c.replace(/_/g," "),yn=g.length?y("div",{className:"feed-files"},g.map((ve,vt)=>y("span",{className:"feed-file",key:`${String(ve)}-${vt}`},String(ve)))):null;return y("article",{className:`feed-item ${c}${E?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(Id,{variant:"kind",tone:c},gt)),y("div",{className:"feed-card-body"},y("div",{className:"feed-card-header"},y("div",{className:"feed-header"},y("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:xI(u,_.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},Te)),y("div",{className:"feed-actions"},q?y(DD,{active:I,modes:L,onSelect:ve=>D(ve)}):null,y(Es,{label:WA(p),side:"left"},y("div",{className:"small feed-age"},m)),e.owned_by_self&&M>0?y(RD,{assignProjectDisabled:ke,disabled:he,onAssignProject:()=>{ht()},onForget:()=>{Ft()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(eu,{label:v,variant:v==="You"?"mine":"author"}),y(eu,{label:b||"private",variant:b||"private"}),U?y(Es,{label:`Memory database id ${M}`,side:"top"},y(eu,{label:U,variant:"memory-id"})):null),y("div",{className:"feed-meta"},z||"No tags, files, or provenance details attached."),be,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},f.length?y("div",{className:"feed-tags"},f.map((ve,vt)=>y(LD,{key:`${String(ve)}-${vt}`,tag:ve}))):null,e.owned_by_self&&M>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:ye,onChange:ve=>{Ce(String(ve.currentTarget.value)==="shared"?"shared":"private")},value:xe},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},de)):null),y("div",{className:"feed-footer-right"},G?y("button",{className:"feed-expand",onClick:()=>{const ve=!K;_.itemExpandState.set(F,ve),ce(ve)},type:"button"},K?"Collapse":"Expand"):null)),yn))}function MD({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return y("div",{className:"feed-skeleton-item","aria-hidden":"true"},y("div",{className:"feed-skeleton-banner"}),y("div",{className:"feed-skeleton-body"},y("div",{className:`feed-skeleton-line ${n}`}),y("div",{className:`feed-skeleton-line ${r}`}),y("div",{className:"feed-skeleton-footer"},y("div",{className:"feed-skeleton-chip w-36"}),y("div",{className:"feed-skeleton-chip w-56"}),y("div",{className:"feed-skeleton-chip"}))))}function OD({items:e,loadingText:t,ops:n}){if(t)return y("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>y(MD,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!_.feedQuery.trim()||_.feedTypeFilter!=="all"||_.feedScopeFilter!=="all";return y("div",{className:"small feed-empty-state"},y("strong",null,r?"No memories match the current filters.":"No memories yet."),y("div",null,r?"Try clearing filters, changing the scope, or using a broader search.":"Memories and session summaries will appear here once codemem has something worth keeping."))}return y(Z,null,e.map(r=>y($D,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function Tb({id:e,active:t,options:n,onSelect:r}){return y("div",{className:"feed-toggle",id:e},n.map(({value:i,label:a})=>{const s=i===t;return y("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},a)}))}function jD({text:e}){return y("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function FD({query:e,onQuery:t}){return y("input",{"aria-label":"Search memories",className:"feed-search",id:"feedSearch",onInput:n=>{t(String(n.currentTarget.value||""))},placeholder:"Search title, body, tags…",type:"search",value:e})}function BD({errorText:e,items:t,loadingText:n,ops:r}){const[i,a]=x(!1);return y(Z,null,y("div",{className:"feed-controls"},y(jD,{text:n||Gx(t.length,r.hasMorePages())}),y("div",{className:"feed-controls-right"},y(FD,{query:_.feedQuery,onQuery:r.updateFeedQuery}),y(Tb,{active:_.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==_.feedScopeFilter&&(Ah(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y(Tb,{active:_.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==_.feedTypeFilter&&(qI(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),y("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>a(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),y(Hx,{open:i}),y("div",{className:"feed-list",id:"feedList"},y(Z,null,e?y("div",{className:"small feed-empty-state",role:"alert"},y("strong",null,e),y("div",null,"Check the viewer connection, then retry the Feed."),y("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null,!e||t.length>0?y(OD,{items:t,loadingText:n,ops:r}):null)))}function UD(e){return _.feedTypeFilter==="observations"?e.filter(t=>!Os(t,Cs(t?.metadata_json))):_.feedTypeFilter==="summaries"?e.filter(t=>Os(t,Cs(t?.metadata_json))):e}function GD(e){const t=e.map(n=>`${Qv(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${_.feedTypeFilter}|${_.feedScopeFilter}|${_.currentProject}|${ua(_.feedQuery)}|${t.join("|")}`}var Ib="",ka=0,Ea=0,ui=!0,pi=!0,Gs=null,HD=0,Et=null,kb=!1,mi=0,tu="all",Eb="",Pa=null,fi="",wF=250;function Pb(e){Ib=e,tu=_.feedScopeFilter,Eb=_.feedQuery.trim(),fi="",mi+=1,ka=0,Ea=0,ui=!0,pi=!0,_.lastFeedItems=[],_.pendingFeedItems=null,_.lastFeedFilteredCount=0,_.lastFeedSignature="",_.newItemKeys.clear(),_.itemViewState.clear(),_.itemExpandState.clear()}function nu(){return ui||pi}function qD(e){const t=ft(e);_.lastFeedItems=_.lastFeedItems.map(n=>ft(n)===t?e:n)}function KD(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};_.lastFeedItems=_.lastFeedItems.filter(n),Array.isArray(_.pendingFeedItems)&&(_.pendingFeedItems=_.pendingFeedItems.filter(n));for(const r of t){_.newItemKeys.delete(r),_.itemViewState.delete(r);for(const i of Array.from(_.itemExpandState.keys()))i.startsWith(`${r}:`)&&_.itemExpandState.delete(i)}}async function VD(){if(!nu())return;const e=mi;if(Gs===e)return;const t=_.currentProject||"",n=_.feedQuery.trim(),r=ka,i=Ea;Gs=e;try{const[a,s]=await Promise.all([ui?Ip(t,{limit:20,offset:r,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),pi?kp(t,{limit:50,offset:i,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==mi||t!==(_.currentProject||"")||n!==_.feedQuery.trim())return;const c=s.items||[],l=a.items||[],d=n?l:l.filter(p=>!Xv(p));_.lastFeedFilteredCount+=l.length-d.length,pi=Ns(s,c.length,50),ui=Ns(a,l.length,20),Ea=Ts(s,i+c.length),ka=Ts(a,r+l.length);const u=[...c,...d];_.lastFeedItems=Zv(_.lastFeedItems,u),yr()}finally{Gs===e&&(Gs=null)}}function Ab(){_.activeTab==="feed"&&(Pa||Et||nu()&&lx()&&VD())}var WD={replaceFeedItem:qD,removeFeedItem:KD,updateFeedView:e=>yr(e),loadFeedData:()=>au(),updateFeedQuery:e=>JD(e),hasMorePages:nu};function ru(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;Lx(n,y(BD,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:WD}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function iu(e="Loading selected project..."){ru([],{loadingText:e})}function zD(){Dx(),ru(_.lastFeedItems,_.lastFeedItems.length||_.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),kb||(window.addEventListener("scroll",()=>{Ab()},{passive:!0}),kb=!0)}function JD(e){if(e===_.feedQuery)return;const t=_.feedQuery.trim();_.feedQuery=e,e.trim()!==t&&(Pb(_.currentProject||""),iu("Searching memories…"),Pa&&clearTimeout(Pa),Pa=setTimeout(()=>{Pa=null,au().catch(()=>{})},250))}function yr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=UD(_.lastFeedItems),r=GD(n),i=e||r!==_.lastFeedSignature;_.lastFeedSignature=r,i&&ru(n,{errorText:fi||void 0}),window.scrollTo({top:t}),Ab()}async function au(){const e=_.currentProject||"",t=_.feedScopeFilter!==tu,n=_.feedQuery.trim(),r=n!==Eb;(e!==Ib||t||r)&&(Pb(e),iu(r?"Searching memories…":void 0));const i=mi,a=++HD;Et={generation:i,requestId:a};const s=!!fi;s&&(fi="",_.lastFeedItems.length>0?yr(!0):iu(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([Ip(e,{limit:20,offset:0,scope:_.feedScopeFilter,q:n||void 0}),kp(e,{limit:50,offset:0,scope:_.feedScopeFilter,q:n||void 0})]);if(Et?.generation!==i||Et.requestId!==a||i!==mi||e!==(_.currentProject||"")||n!==_.feedQuery.trim())return;const p=u.items||[],m=d.items||[],f=n?m:m.filter(b=>!Xv(b)),g=m.length-f.length,h=[...p,...f].sort((b,S)=>new Date(S.created_at||0).getTime()-new Date(b.created_at||0).getTime()),v=cx(_.lastFeedItems,h),w=_.lastFeedItems;if(dx(v,w)&&w.length>0){const b=new Set(w.map(ft));v.forEach(S=>{b.has(ft(S))||_.newItemKeys.add(ft(S))})}_.pendingFeedItems=null,_.lastFeedItems=v,fi="",_.lastFeedFilteredCount=Math.max(_.lastFeedFilteredCount,g),pi=Ns(u,p.length,50),ui=Ns(d,m.length,20),Ea=Math.max(Ea,Ts(u,p.length)),ka=Math.max(ka,Ts(d,m.length)),tu=_.feedScopeFilter,Et?.generation===i&&Et.requestId===a&&(Et=null),yr(s)}catch(c){throw Et?.generation===i&&Et.requestId===a&&i===mi&&e===(_.currentProject||"")&&n===_.feedQuery.trim()&&(ui=!1,pi=!1,fi="Feed unavailable. Refresh and try again.",yr(!0)),c}finally{Et?.generation===i&&Et.requestId===a&&(Et=null)}}var YD=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function xb(e){return!!YD.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function SF(e){return e}function XD(e){return e.latest_version?e.stale?{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:xb(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function QD({status:e}){const t=XD(e),n=e.update_available||e.stale||!e.latest_version||!xb(e.current_version);return y("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},y("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),y("div",{class:"health-update-copy"},y("h2",null,t.title),y("p",null,t.detail),n&&e.recommended_action?y("p",{class:"health-update-guidance"},y("span",{class:"health-update-guidance-label"},"Recommended action"),y("code",null,e.recommended_action)):null))}function ZD(e,t){e&&(e.hidden=!t,Ge(t?y(QD,{status:t}):null,e))}function eL({label:e,value:t,detail:n,icon:r,className:i,title:a}){const s=y("div",{class:`stat${i?` ${i}`:""}`,style:a?"cursor: help;":void 0},r?y("i",{"data-lucide":r,class:"stat-icon"}):null,y("div",{class:"stat-content"},y("div",{class:"value"},t),y("div",{class:"label"},e),n?y("div",{class:"small"},n):null));return a?y(Es,{label:a},s):s}function tL({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action()}catch{}t.disabled=!1,t.textContent=r}}function a(){!e.command||!n||Xi(e.command,n)}return y("div",{class:"health-action"},y("div",{class:"health-action-text"},e.label,e.command?y("span",{class:"health-action-command"},e.command):null),y("div",{class:"health-action-buttons"},e.action?y("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?y("button",{class:"settings-button health-action-copy",onClick:a,ref:s=>{n=s}},"Copy"):null))}function nL(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function rL({label:e,value:t,icon:n,tooltip:r}){const i=y("div",{class:"stat",style:r?"cursor: help;":void 0},y("i",{"data-lucide":n,class:"stat-icon"}),y("div",{class:"stat-content"},y("div",{class:"value"},nL(t)),y("div",{class:"label"},e)));return r?y(Es,{label:r},i):i}function Rb(e,t){e&&Ge(y(Nd,null,t.map(n=>y(rL,{...n,key:`${n.label}-${n.icon}`}))),e)}function Db(e,t){e&&Ge(y(Z,null,t),e)}function ou(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function iL(e,t){e&&Ge(y(Nd,null,t.map(n=>y(eL,{...n,key:n.key??n.label}))),e)}function aL(e,t){if(e){if(!t.length){e.hidden=!0,Ge(null,e);return}e.hidden=!1,Ge(y(Z,null,t.slice(0,3).map((n,r)=>y(tL,{item:n,key:`${n.label}-${r}`}))),e)}}var Lb="scope_id_backfill";function $b(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;ZD(document.getElementById("healthUpdateBanner"),_.lastUpdateStatus);const i=_.lastStatsPayload||{},a=_.lastUsagePayload||{},s=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},c=_.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(ue=>ue.kind===Lb),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},g=a.totals_filtered||a.totals||a.totals_global||i.usage?.totals||{},h=Array.isArray(a.recent_packs)?a.recent_packs:[],v=h.length?h[0]?.created_at:null,w=h.length?h[0]?.metadata_json||{}:{},b=Number(w?.exact_duplicates_collapsed||0),S=Number(s.pending||0),C=Number(p.errored_batches||0),T=Number(m.flush_success_rate??1),P=Number(m.dropped_event_rate||0),k=bd(g.tokens_saved,g.tokens_read),M=YA(k),U=Number(f.tags_coverage||0),E=String(c.daemon_state||"unknown"),j=E==="offline-peers"?"Offline peers":E==="needs_attention"?"Needs attention":E==="rebootstrapping"?"Rebootstrapping":zv(E),O=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers.length:0,q=E==="disabled"||c.enabled===!1,L=E==="offline-peers",R=!q&&O===0;let A=q?"Disabled":R?"No peers":j;const I=ai(c.last_sync_at||c.last_sync_at_utc||null),D=ai(v),F=I!==null&&I>7200,K=I!==null&&I<=300,ce=S>=200;let ie=0;const re=[];S>=1e3?(ie+=40,re.push("high raw-event backlog")):S>=200&&(ie+=24,re.push("growing raw-event backlog")),C>0&&S>=200&&(ie+=C>=5?10:6,re.push("batch errors during backlog pressure")),T<.95&&(ie+=20,re.push("lower flush success")),P>.02?(ie+=24,re.push("high dropped-event rate")):P>.005&&(ie+=10,re.push("non-trivial dropped-event rate")),!q&&!R&&(E==="error"?(ie+=36,re.push("sync daemon reports errors")):E==="needs_attention"?(ie+=40,re.push("sync needs manual attention")):E==="stopped"?(ie+=22,re.push("sync daemon stopped")):E==="degraded"&&!K&&(ie+=20,re.push("sync daemon degraded")),L?(ie+=4,re.push("all peers currently offline"),F&&(ie+=4,re.push("offline peers and sync not recent"))):F?(ie+=26,re.push("sync looks stale")):I!==null&&I>1800&&(ie+=12,re.push("sync not recent"))),M!==null&&M<10&&(ie+=8,re.push("low retrieval reduction")),D!==null&&D>86400&&(ie+=12,re.push("memory pack activity is old"));let ye="Healthy",Y="status-healthy";ie>=60?(ye="Attention",Y="status-attention"):ie>=25&&(ye="Degraded",Y="status-degraded");const he=Y==="status-healthy";r&&(r.className=`health-dot ${Y}`,r.title=ye);const ne=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${b.toLocaleString()} deduped in latest pack`,ke=S>0?"Queue is actively draining":"Queue is clear",ge=q?"Sync disabled":R?"No peers configured":L?`${O} peers offline · last sync ${$n(I)} ago`:`${O} peers · last sync ${$n(I)} ago`;he&&!q&&!R&&(L?A="Peers offline":E==="degraded"&&K&&(A="Syncing"));const ae=`last pack ${$n(D)} ago`,xe=l.map(ue=>{const z=Number(ue.progress?.current||0),G=typeof ue.progress?.total=="number"?ue.progress.total:null,W=String(ue.progress?.unit||"items"),be=G&&G>0?` (${Math.round(100*z/G)}%)`:"",Ce=G&&G>0?`${z.toLocaleString()}/${G.toLocaleString()} ${W}${be}`:`${z.toLocaleString()} ${W}`,ht=ue.status==="failed",Ft=ue.status==="completed",gt=ue.kind===Lb,yn=ht?"Failed":Ft?"Complete":Ce,ve=ht?String(ue.error||"unknown error").trim():Ft?gt?`${Ce} · one-time Sharing-domain upgrade finished`:Ce:gt?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(ue.kind||ue.title||"background-maintenance"),label:String(ue.title||ue.kind||"Background maintenance"),value:yn,detail:ve,icon:ht?"alert-triangle":Ft?"check-circle":"loader",className:ht?"status-attention":void 0,title:ht?`Error: ${ue.error||"unknown"}`:Ft?`${String(ue.title||"Maintenance")} finished`:gt?`${String(ue.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(ue.title||"Maintenance")} in progress`}});iL(e,[{key:"overall-health",label:"Overall health",value:ye,detail:`Weighted score ${ie}`,icon:"heart-pulse",className:`health-primary ${Y}`,title:re.length?`Main signals: ${re.join(", ")}`:"No major risk signals detected"},...xe,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:ke,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:k,detail:ne,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:A,detail:ge,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:$n(D),detail:ae,icon:"clock-3",title:"Recency of last memory pack activity"}]);const de=async()=>{await Cc()},Te=[];ce?(Te.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),Te.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):E==="stopped"?Te.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!q&&!R&&!he&&(E==="error"||E==="degraded")?(Te.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:de,actionLabel:"Sync now"}),Te.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!q&&!R&&F&&Te.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:de,actionLabel:"Sync now"}),U>0&&U<.7&&Te.length<2&&Te.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&Te.length<3&&Te.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),aL(n,Te),t.textContent=re.length?`Why this status: ${re.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",ou()}function oL(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=_.lastUsagePayload||{},r=_.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,a=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(T=>T.event==="pack")||null,c=Array.isArray(n?.recent_packs)?n.recent_packs:[],l=c.length?c[0]:null,d=l?.metadata_json||{},u=l?.created_at||"",p=Number(s?.count||0),m=Number(l?.tokens_read||0),f=Number(l?.tokens_saved||0),g=Number(d?.exact_duplicates_collapsed||0),h=!!d?.exact_dedupe_enabled,v=bd(f,m),w=p?`${p} packs`:"No packs yet",b=u?`Last pack: ${pr(u)}`:"",S=a?"Project":"All projects",C=[{label:"Last pack savings",value:l?`${da(f)} (${v})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?da(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?g.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:l?h?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];Db(t,[S,w,b].filter(Boolean).join(" · ")),Rb(e,C),ou()}function sL(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=_.lastStatsPayload||{},r=_.lastUsagePayload||{},i=_.lastRawEventsPayload&&typeof _.lastRawEventsPayload=="object"?_.lastRawEventsPayload:{},a=n.database||{},s=_.currentProject,c=r?.totals_global||r?.totals||n.usage?.totals||{},l=r?.totals_filtered||null,d=!!(s&&l),u=d?l:c,p=Number(i.sessions||0),m=Number(i.pending||0),f=d?`
|
|
112
|
-
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",
|
|
113
|
-
Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",
|
|
114
|
-
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",v=[{label:d?"Savings (project)":"Savings",value:da(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${h}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:da(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${g}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:bd(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${JA(u.tokens_saved,u.tokens_read)}.`+g+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:da(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${f}`,icon:"pencil"},{label:"Active memories",value:a.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:Wv(a.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Wv(a.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?v.push({label:"Raw events pending",value:m,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&v.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Rb(e,v),t){const w=s?` · project: ${s}`:"";Db(t,`DB: ${ZA(a.path||"unknown")} · ${ex(a.size_bytes||0)}${w}`)}ou()}async function cL(){const e=_.lastStatsPayload?.identity?.actor_id||null,t=_.activeTab==="health"&&!_.lastUpdateStatus?YS().catch(XS):Promise.resolve(_.lastUpdateStatus),[n,r,i,a,s]=await Promise.all([aS(),oS(_.currentProject),sS(_.currentProject),cS(_.currentProject),t]);_.lastStatsPayload=n||{},_.lastUsagePayload=r||{},_.lastRawEventsPayload=a||{},_.lastUpdateStatus=s;const c=_.lastStatsPayload?.identity?.actor_id||null;sL(),oL(),$b(),_.activeTab==="feed"&&e!==c&&yr(!0)}var lL={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function Mb(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function dL(e){return e.targetIdentityRef??e.existingIdentityRef??""}function uL({blocked:e,blockedDescriptionId:t,busy:n,detail:r,device:i,index:a,onAssign:s,onClear:c,onDecision:l}){const d=`legacy-team-device-identity-${a}`,u=`legacy-team-device-evidence-${a}`,p=`legacy-team-device-assignment-help-${a}`,m=dL(i),f=i.targetIdentityRef??"",[g,h]=x(m);J(()=>h(m),[m]);const v=r.identityChoices.some(L=>L.identityRef===g),w=Mb(r,i.existingIdentityRef),b=Mb(r,i.suggestedIdentityRef),S=e||n,C=S||!i.enabled,T=i.expectation.kind==="existing"&&i.verifiedEvidenceKind!=="active_assignment",P=!!g&&!v,k=T||P||!f||g!==f,M=S||k,U=C||!g||T||P||g===f,E=!i.enabled||k,j=e?t:void 0,O=[u,E?p:void 0,j].filter(Boolean).join(" "),q=[u,j].filter(Boolean).join(" ");return o("fieldset",{"aria-busy":n?"true":"false",className:"legacy-team-device-row",id:`legacy-team-device-row-${a}`,tabIndex:i.decision==="unresolved"?-1:void 0,children:[o("legend",{children:i.displayName}),o("div",{className:"small legacy-team-device-evidence",id:u,children:[o("span",{children:i.enabled?"Current Team device":"Device no longer active on this Team"}),w?o("span",{children:["Current assignment: ",w,i.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!w&&b?o("span",{children:["Suggested person: ",b]}):null,o("span",{children:["Decision: ",lL[i.decision]]})]}),o("label",{htmlFor:d,children:"Person using this device"}),o("select",{"aria-describedby":O,className:"feed-search legacy-team-device-select",disabled:C,id:d,onChange:L=>h(L.currentTarget.value),value:g,children:[o("option",{value:"",children:"Choose a person"}),g&&!v?o("option",{value:g,children:"Current server assignment"}):null,r.identityChoices.map(L=>o("option",{value:L.identityRef,children:L.displayName},L.identityRef))]}),i.enabled?P?o("p",{className:"small",id:p,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):T?o("p",{className:"small",id:p,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!g||!f||g!==f?o("p",{className:"small",id:p,children:g?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:o("p",{className:"small",id:p,children:"Inactive devices can only be removed from this Team."}),o("div",{className:"legacy-team-device-actions",children:[o("button",{"aria-describedby":O,"aria-disabled":U?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{U||s(i,g)},type:"button",children:"Save assignment"}),i.enabled?o(Z,{children:[o("button",{"aria-describedby":O,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{M||l(i,"included",f)},type:"button",children:"Include"}),o("button",{"aria-describedby":q,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||l(i,"excluded")},type:"button",children:"Exclude"})]}):o("button",{"aria-describedby":q,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||l(i,"removed")},type:"button",children:"Remove"}),i.decision!=="unresolved"?o("button",{"aria-describedby":q,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||c(i)},type:"button",children:"Clear decision"}):null]})]})}function pL(e){return o("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[o("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),o("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),o("div",{className:"legacy-team-device-list",children:e.detail.devices.map((t,n)=>y(uL,{...e,busy:e.busyDeviceRef===t.deviceRef,device:t,index:n,key:t.deviceRef}))})]})}function mL(e){return e.resolvedProjectRef?e.mappingChoices.find(t=>t.resolvedProjectRef===e.resolvedProjectRef)?.displayName??"Unavailable Project":null}function fL({blocked:e,blockedDescriptionId:t,busy:n,index:r,onMap:i,project:a}){const s=Lr(),c=`${s}-mapping`,l=`${s}-help`,d=a.resolvedProjectRef??"",u=a.mappingChoices.some(b=>b.resolvedProjectRef===d)?d:"",p=JSON.stringify(a.mappingChoices.map(b=>b.resolvedProjectRef)),[m,f]=x(u);J(()=>f(u),[u,p]);const g=e||n,h=g||!m||m===d,v=mL(a),w=[m?void 0:l,e?t:void 0].filter(Boolean).join(" ");return o("fieldset",{"aria-busy":n?"true":"false",className:"legacy-team-project-row",id:`legacy-team-project-row-${r}`,tabIndex:a.resolution==="unresolved"?-1:void 0,children:[o("legend",{children:a.displayName}),a.resolution==="deterministic"?o("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):o(Z,{children:[o("p",{className:"small",children:v?`Saved mapping: ${v}`:"This Project still needs a mapping."}),o("label",{htmlFor:c,children:"Canonical Project"}),o("select",{"aria-describedby":w||void 0,className:"feed-search legacy-team-project-select",disabled:g,id:c,onChange:b=>f(b.currentTarget.value),value:m,children:[o("option",{value:"",children:"Choose a Project"}),a.mappingChoices.map(b=>o("option",{value:b.resolvedProjectRef,children:b.displayName},b.resolvedProjectRef))]}),m?null:o("p",{className:"small",id:l,children:"Choose and save one of the server-provided Project mappings."}),o("button",{"aria-describedby":w||void 0,"aria-disabled":h?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{h||i(a,m)},type:"button",children:"Save mapping"})]})]})}function hL(e){const t=e.detail.projects.filter(r=>r.resolution==="deterministic").length,n=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return o("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[o("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),o("p",{children:[e.detail.unresolvedProjectCount.toLocaleString()," of ",n.toLocaleString()," ","Team Projects still need a mapping."]}),t>0?o("p",{className:"small",children:["Automatically mapped Projects are part of this draft and appear in the final access review before activation. The ",t.toLocaleString()," automatic"," ",t===1?"mapping was":"mappings were"," resolved from server evidence and ",t===1?"is":"are"," listed below for review."]}):null,o("div",{className:"legacy-team-project-list",children:e.detail.projects.map((r,i)=>o(fL,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,busy:e.busyProjectRef===r.projectRef,index:i,onMap:e.onMap,project:r},r.projectRef))}),e.detail.unresolvedProjectCount===0?o("button",{"aria-describedby":e.blocked?e.blockedDescriptionId:void 0,"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"}):null]})}var Aa={add:"Add",update:"Update",remove:"Remove"},gL=10;function Ct(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function su(e,t,n){const r=new Map;for(const i of e){const a=t(i),s=a.trim().toLowerCase(),c=n(i),l=r.get(s)??{displayName:a,projectRefs:new Set,changeCount:0};l.projectRefs.add(c),l.changeCount+=1,r.set(s,l)}return[...r.values()]}function cu(e){return`${e.displayName} — ${Ct(e.projectRefs.size,"Project with this name","Projects with this name")}`}function xa({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const a=!!(r&&r.length<n.length),s=a&&n.length>gL;return o("section",{children:[o("h4",{children:i}),n.length>0?o(Z,{children:[a&&r?o("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>o("li",{children:c},`${i}-summary-${l}`))}):null,s?o("details",{children:[o("summary",{children:["Show all ",Ct(n.length,`exact ${t}`)]}),o(Ob,{items:n,title:i})]}):o(Ob,{items:n,title:i})]}):o("p",{className:"small",children:e})]})}function Ob({items:e,title:t}){return o("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>o("li",{children:n},`${t}-${r}`))})}function vL({blocked:e,blockedDescriptionId:t,detail:n,onFinish:r}){const i=n.accessDelta,a=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[s,c]=x(null),l=s===a,d=e||!l,u=[l?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),p=i.teamChanges.map(k=>{const M=k.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":k.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Aa[k.change]} ${k.teamDisplayName}: change device access from ${M} to the reviewed device list.`}),m=i.membershipChanges.map(k=>`${Aa[k.change]} ${k.identityDisplayName} ${k.change==="remove"?"from":"to"} ${k.teamDisplayName}.`),f=i.projectChanges.map(k=>`${Aa[k.change]} ${k.projectDisplayName}: ${k.fromResolvedProjectDisplayName??"no Project"} to ${k.toResolvedProjectDisplayName??"no Project"}.`),g=i.recipientChanges.map(k=>`${Aa[k.change]} ${k.recipientDisplayName} ${k.change==="remove"?"from":"as"} a recipient for ${k.canonicalProjectDisplayName}.`),h=i.deviceAccessChanges.map(k=>`${Aa[k.change]} ${k.deviceDisplayName} access ${k.change==="remove"?"from":"to"} ${k.canonicalProjectDisplayName}.`),v=i.teamChanges.length+i.membershipChanges.length+i.projectChanges.length+i.recipientChanges.length+i.deviceAccessChanges.length,w=su(i.projectChanges,k=>k.projectDisplayName,k=>k.projectRef),b=su(i.recipientChanges,k=>k.canonicalProjectDisplayName,k=>k.canonicalProjectRef),S=su(i.deviceAccessChanges,k=>k.canonicalProjectDisplayName,k=>k.canonicalProjectRef),C=n.devices.filter(k=>k.decision==="included").length,T=[Ct(i.teamChanges.length,"Team policy change"),Ct(i.membershipChanges.length,"membership change"),Ct(i.projectChanges.length,"Project change"),Ct(i.recipientChanges.length,"recipient change"),Ct(i.deviceAccessChanges.length,"device-access change")],P=`${Ct(n.projects.length,"Project")} included; ${Ct(C,"included device")}.`;return o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:"Review every server-confirmed access change before activating this Team."}),o("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[o("p",{children:[o("strong",{children:Ct(v,"exact access change")})," to review."]}),o("ul",{children:T.map(k=>o("li",{children:k},k))}),o("p",{className:"small",children:["Scope: ",P]})]}),o("div",{className:"legacy-team-setup-delta",children:[o(xa,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:p,title:"Team policy"}),o(xa,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),o(xa,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:f,summaryItems:w.map(k=>`${cu(k)}, ${Ct(k.changeCount,"Project change")}`),title:"Projects"}),o(xa,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:g,summaryItems:b.map(k=>`${cu(k)}, ${Ct(k.changeCount,"recipient change")}`),title:"Recipients"}),o(xa,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:h,summaryItems:S.map(k=>`${cu(k)}, ${Ct(k.changeCount,"device-access change")}`),title:"Device access"})]}),o("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[o("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:l,onClick:k=>{e&&k.preventDefault()},onChange:k=>{if(e){k.currentTarget.checked=l;return}c(k.currentTarget.checked?a:null)},type:"checkbox"}),o("span",{children:"I reviewed every access change above and approve activating this Team."})]}),o("button",{"aria-describedby":u||void 0,"aria-disabled":d?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{d||r(n)},type:"button",children:"Finish Team setup"})]})}var yL={role:"list"},lu={role:"listitem"},br="Team setup changed since it was last reviewed. Reload the latest details to continue.",bL="The change was saved, but the latest Team setup details could not be loaded. Reload before continuing.",hi=new Set(["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"]),_L={clearDecision:CS,finish:IS,loadDetail:_S,onCompleted:()=>{},refreshCandidate:TS,saveAssignment:wS,saveDecision:SS,saveProjectMapping:NS},Hs=null,Ra=null,qs=null;function jb(e){return e?(qs=document.activeElement instanceof HTMLElement?document.activeElement:null,Ra?Ra(e):Hs=e,!0):!1}function wL(e){if(!e?.isConnected||e.tabIndex<0||e.matches(":disabled")||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;for(let t=e;t;t=t.parentElement){const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!1}return!0}function Fb(e,t=!1){return e.draftState==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function Da(e){return e.draftState==="completed"?!1:e.draftState==="stale"||!e.canFinish&&e.conflictState!==null&&hi.has(e.conflictState)}function SL(e){return du(e)?br:"Team setup details are temporarily unavailable. Retry to load the latest details."}function du(e){return e instanceof Gt&&hi.has(e.errorCode)}function Ks(e){return du(e)?br:e instanceof Gt&&e.errorCode==="team_setup_roster_unavailable"?"Team device details are temporarily unavailable. Reload the latest details before trying again.":"This device change could not be saved. Reload the latest details before trying again."}function CL(e){return e instanceof Gt&&hi.has(e.errorCode)?br:"This Project mapping could not be saved. Reload the latest details before trying again."}function NL(e){return e instanceof Gt&&hi.has(e.errorCode)?br:"Team setup could not be refreshed. Retry to load the latest server details."}function TL(e){return e instanceof Gt&&hi.has(e.errorCode)?br:"Team setup could not be finished. Reload the latest details before trying again."}function IL({detail:e,step:t}){return t==="completed"?o("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[o("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),o("p",{children:"This Team is ready for Project sharing."})]}):t==="devices"||t==="projects"?null:o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for current server confirmation evidence."}),o("p",{className:"small",children:"Next setup action: confirm the server-provided access review before finishing."})]})}function kL({dependencies:e}){const[t,n]=x(null),[r,i]=x(null),[a,s]=x("devices"),[c,l]=x(!1),[d,u]=x(null),[p,m]=x(0),[f,g]=x(null),[h,v]=x(null),[w,b]=x(""),[S,C]=x(!1),T=B(!1),P=B(null),k=B(!1),M=B(!1),U=B(!1),E=B(null),j=B(!1),O=B(0),q=B(null),L=z=>{const G=q.current;if(G?.attemptId===z&&G.candidateRef===t)return G.promise;const W=Promise.resolve().then(()=>e.onCompleted()),be=()=>{q.current?.promise===Ce&&(q.current=null)},Ce=W.then(be,ht=>{throw be(),ht});return q.current={attemptId:z,candidateRef:t,promise:Ce},Ce},R=(z,G)=>{b("Team setup complete. Sharing and Projects are refreshing."),L(z).then(()=>{O.current===G&&b("Team setup complete. Sharing and Projects are up to date.")},()=>{O.current===G&&b("Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control.")})};if(J(()=>{if(Ra=z=>{if(j.current){b("Wait for the current Team setup change to finish before opening another Team.");return}O.current+=1,M.current=!1,U.current=!1,E.current=null,n(z),i(null),u(null),b(""),m(G=>G+1)},Hs){const z=Hs;Hs=null,Ra(z)}return()=>{Ra=null}},[]),J(()=>{if(!t)return;let z=!0;const G=M.current;return M.current=!1,l(!0),(G?e.refreshCandidate(t).then(()=>e.loadDetail(t)):e.loadDetail(t)).then(W=>{if(!z)return;U.current=Da(W),i(W);const be=Fb(W,E.current===W.attemptId);be==="projects"&&(E.current=W.attemptId),s(be),u(Da(W)?br:null),l(!1),W.draftState==="completed"&&R(W.attemptId,O.current)},W=>{z&&(U.current=G||du(W),u(SL(W)),l(!1))}),()=>{z=!1}},[t,e,p]),J(()=>{if(P.current){const z=P.current;P.current=null,k.current=!1,document.getElementById(z)?.focus();return}k.current&&(k.current=!1,document.getElementById(`legacy-team-setup-step-${a}`)?.focus())},[a]),J(()=>{if(!(c||!T.current)){if(T.current=!1,d){(document.getElementById("legacy-team-setup-retry")??document.getElementById("legacy-team-setup-refresh"))?.focus();return}document.getElementById(`legacy-team-setup-step-${a}`)?.focus()}},[d,c,a]),!t)return null;const A=r?`Set up ${r.candidate.displayName}`:"Set up Team",I=()=>{if(j.current){b("Team setup will stay open while this change saves. Close it after saving finishes.");return}T.current=!1,P.current=null,k.current=!1,M.current=!1,U.current=!1,E.current=null,O.current+=1,n(null),i(null),u(null),l(!1),g(null),v(null),b(""),s("devices")},D=z=>{if(z==="projects"&&r&&(E.current=r.attemptId),z===a){document.getElementById(`legacy-team-setup-step-${z}`)?.focus();return}k.current=!0,s(z)},F=(z,G)=>{b(G);const W=z==="devices"?r?.devices.findIndex(Ce=>Ce.decision==="unresolved"):r?.projects.findIndex(Ce=>Ce.resolution==="unresolved"),be=W!==void 0&&W>=0?z==="devices"?`legacy-team-device-row-${W}`:`legacy-team-project-row-${W}`:null;if(be&&z===a){document.getElementById(be)?.focus();return}P.current=be,D(z)},K=r?r.unresolvedDeviceCount>0:!1,ce=r?r.unresolvedProjectCount>0:!1,ie=r?Da(r):!1,re=c||S||!!d,ye=d?"legacy-team-setup-error":c?"legacy-team-setup-refresh-status":S?"legacy-team-setup-operation-status":void 0,Y=(z,G)=>{U.current=Da(z),i(z),s(W=>{const be=G&&W==="devices"&&z.draftState!=="completed"&&z.unresolvedDeviceCount>0?"devices":Fb(z,E.current===z.attemptId);return be==="projects"&&(E.current=z.attemptId),be!==W&&(k.current=!0),be}),u(Da(z)?br:null)},he=async()=>{const z=await e.loadDetail(t);return Y(z,!0),z},ne=async(z,G=Ks)=>{const W=G(z);if(b(""),u(W),!(!(z instanceof Gt)||!hi.has(z.errorCode))){try{const be=await e.loadDetail(t);if(Y(be,!0),be.draftState==="completed"){u(null),R(be.attemptId,O.current);return}U.current=!0}catch{U.current=!0}u(W)}},ke=async(z,G,W,be,Ce,ht)=>{if(!(re||j.current)){j.current=!0,C(!0),be(z),b(G),u(null);try{try{await ht()}catch(Ft){await ne(Ft,Ce);return}try{await he(),b(W)}catch{b(""),u(bL)}}finally{j.current=!1,C(!1),be(null)}}},ge=(z,G)=>{const W=r;W&&ke(z.deviceRef,`Saving the assignment for ${z.displayName}.`,`${z.displayName} saved.`,g,Ks,()=>e.saveAssignment(t,z.deviceRef,{attemptId:W.attemptId,targetIdentityRef:G,expectation:z.expectation}))},ae=(z,G,W)=>{const be=r;if(be){if(G==="included"&&!W){b(`Save a person assignment before including ${z.displayName}.`);return}ke(z.deviceRef,`Saving the decision for ${z.displayName}.`,`${z.displayName} saved.`,g,Ks,async()=>{G==="included"&&W?await e.saveDecision(t,z.deviceRef,{attemptId:be.attemptId,decision:"included",expectedTargetIdentityRef:W}):G!=="included"&&await e.saveDecision(t,z.deviceRef,{attemptId:be.attemptId,decision:G})})}},xe=z=>{const G=r;G&&ke(z.deviceRef,`Clearing the decision for ${z.displayName}.`,`${z.displayName} saved.`,g,Ks,()=>e.clearDecision(t,z.deviceRef,{attemptId:G.attemptId}))},de=(z,G)=>{const W=r;W&&ke(z.projectRef,`Saving the mapping for ${z.displayName}.`,`${z.displayName} saved.`,v,CL,()=>e.saveProjectMapping(t,z.projectRef,{attemptId:W.attemptId,resolvedProjectRef:G}))},Te=()=>{if(c||S||j.current)return;const z=O.current;j.current=!0,C(!0),b("Refreshing Team setup from the latest server state."),u(null),e.refreshCandidate(t).then(he).then(G=>{if(G.draftState==="completed"){R(G.attemptId,z);return}b("Team setup refreshed.")}).catch(G=>ne(G,NL)).finally(()=>{j.current=!1,C(!1)})},ue=z=>{if(re||j.current)return;const G=O.current;j.current=!0,C(!0),b("Finishing Team setup."),u(null),e.finish(t,{attemptId:z.attemptId,finishDigest:z.finishDigest,confirmedAccessDeltaDigest:z.accessDeltaDigest,confirmedViewerAccessDeltaDigest:z.viewerAccessDeltaDigest}).then(()=>{k.current=!0,s("completed"),R(z.attemptId,G)},W=>ne(W,TL)).finally(()=>{j.current=!1,C(!1)})};return o(Br,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:z=>{z.preventDefault();const G=document.querySelector('.tab-btn[aria-current="page"]');(wL(qs)?qs:G)?.focus(),qs=null},onOpenAutoFocus:z=>{const G=document.getElementById("legacy-team-setup-title");G&&(z.preventDefault(),G.focus())},onOpenChange:z=>{z||I()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:o("div",{"aria-busy":c||S?"true":"false",className:"modal-card legacy-team-setup-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"legacy-team-setup-title",tabIndex:-1,children:A}),o(Oi,{ariaDisabled:S,ariaLabel:`Close ${A}`,onClick:I})]}),o("div",{className:"modal-body legacy-team-setup-body",children:[o("p",{className:"small",id:"legacy-team-setup-description",children:"Review the server-provided device and Project work before this Team can be used for sharing."}),c&&!r?o("p",{role:"status",children:"Loading the latest Team setup details…"}):null,d?o("div",{className:"legacy-team-setup-error",children:[o("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:d}),!r||!ie?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{c||S||(T.current=!0,M.current=U.current,m(z=>z+1))},type:"button",children:c?"Retrying…":"Retry"}):null]}):null,r?o(Z,{children:[a!=="completed"?o(Z,{children:[o("ol",{...yL,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[o("li",{...lu,className:"legacy-team-setup-step",children:[o("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:"1"}),o("button",{"aria-label":"Step 1: Devices","aria-current":a==="devices"?"step":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>D("devices"),type:"button",children:"Devices"})]}),o("li",{...lu,className:"legacy-team-setup-step",children:[o("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:"2"}),o("button",{"aria-label":"Step 2: Projects","aria-current":a==="projects"?"step":void 0,"aria-describedby":K?"legacy-team-setup-block-devices":void 0,"aria-disabled":K?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{K?F("devices","Finish the device decisions before mapping Projects."):D("projects")},type:"button",children:"Projects"})]}),o("li",{...lu,className:"legacy-team-setup-step",children:[o("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:"3"}),o("button",{"aria-label":"Step 3: Review","aria-current":a==="review"?"step":void 0,"aria-describedby":K?"legacy-team-setup-block-devices":ce?"legacy-team-setup-block-projects":void 0,"aria-disabled":K||ce?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{K?F("devices","Finish the device decisions before reviewing access."):ce?F("projects","Finish the Project mappings before reviewing access."):D("review")},type:"button",children:"Review"})]})]}),K?o("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,ce?o("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]}):null,c?o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:w}),ie?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-refresh",onClick:Te,type:"button",children:"Refresh Team setup"}):null,a==="devices"?o(pL,{blocked:re,blockedDescriptionId:ye,busyDeviceRef:f,detail:r,onAssign:ge,onClear:xe,onDecision:ae}):a==="projects"?o(hL,{blocked:re,blockedDescriptionId:ye,busyProjectRef:h,detail:r,onContinue:()=>D("review"),onMap:de}):a==="review"&&r.canFinish?o(vL,{blocked:re,blockedDescriptionId:ye,detail:r,onFinish:ue}):o(Z,{children:[o(IL,{detail:r,step:a}),a==="review"&&!r.canFinish&&!ie?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:Te,type:"button",children:"Refresh Team setup"}):null]})]}):null]}),o("div",{className:"modal-footer legacy-team-setup-actions",children:o("button",{"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:I,type:"button",children:"Close"})})]})})}function EL(e,t={}){Ge(o(kL,{dependencies:{..._L,...t}}),e)}var La=new WeakMap;function _r(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function PL(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-blocked-item";const n=document.createElement("div");n.className="project-inventory-row-header";const r=document.createElement("h3");r.className="project-inventory-title",r.textContent=e.finding;const i=document.createElement("span");return i.className="project-status-badge needs_attention",i.textContent="Blocked",n.append(r,i),t.append(n,_r(e.reason,"project-inventory-meta"),_r(`Owner: ${e.ownerLabel}`,"settings-note"),_r(`Repair: ${e.repairAction}`,"settings-note")),t}function AL(e,t){const n=`review:${JSON.stringify(t)}`;if(La.get(e)===n)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,La.set(e,n);return}e.hidden=!1;const r=document.createElement("section");r.className="card recipient-policy-review",r.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const i=document.createElement("h2");if(i.id="recipientPolicyReviewTitle",i.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",r.appendChild(i),t.continuity){const a=t.continuity.findingCount,s=_r(`${a.toLocaleString()} older sharing finding${a===1?" was":"s were"} not changed because Codemem could not safely translate ${a===1?"it":"them"} automatically.`,"settings-note");s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),t.blockedItems.length===0&&r.appendChild(_r("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),r.appendChild(s)}if(t.blockedItems.length>0){const a=_r("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),s=document.createElement("h3");s.className="recipient-policy-blocked-heading",s.textContent="Needs repair";const c=document.createElement("div");c.className="project-inventory-list recipient-policy-review-list";for(const l of t.blockedItems)c.appendChild(PL(l));r.append(a,s,c)}e.replaceChildren(r),La.set(e,n)}function xL(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(La.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const a=document.createElement("h2");a.textContent="Recipient migration review";const s=_r(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(a,s),e.replaceChildren(i),La.set(e,r)}var Bb=[["","All projects"],["needs_attention","Needs review"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","Received from peers"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],at=null,$a=0,uu=250,pu=[],mu=new Set,fu=new Set,Vs=new Map,Ws=new Map,wr=new Map,Ma=new Map,zs=!1,Oa=!1,Bn=!1,gi=0,ja=null,Pt=new Set,Ub=new WeakMap,Js={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},vi=Js,Un=!1,hu;function Gb(e=!1){if(!e&&ja)return ja;const t=Mp().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return ja=t,t.then(()=>{ja===t&&(ja=null)}),t}function qe(e){return document.getElementById(e)}function RL(e){return Bb.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function DL(e){switch(e){case"exact_mapping":return"assigned to a Space";case"pattern_mapping":return"assigned by matching rule";case"explicit_override":return"manually assigned";default:return"stays on this device"}}function yi(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function gu(e){return e.identity_source!=="unmapped"&&!yi(e)}function vu(e){return yi(e)?"Received from peers":Ys(e.resolved_scope_id)}function LL(e){return yi(e)?"source-owned project":DL(e.resolution_reason)}function $L(e){const t=e.person.display_name;switch(e.lifecycle.state){case"waiting_for_acceptance":return`Invitation sent to ${t}`;case"active":return`Shared with ${t}`;case"waiting_for_device":return`Sharing with ${t}`;case"needs_attention":return`Sharing with ${t} needs attention`;case"revoking":return`Removing sharing with ${t}`;case"revoked":return`Previously shared with ${t}`;case"cancelled":return`Invitation to ${t} cancelled`;default:return`Setting up sharing with ${t}`}}function Hb(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function qb(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Sr(){const e=Pt.size,t=qe("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!Bn||!Un,t.classList.add("project-selection-target"));const n=qe("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`);for(const r of document.querySelectorAll(".project-selection-checkbox")){const i=Ub.get(r)??[],a=i.filter(s=>Pt.has(s)).length;r.checked=i.length>0&&a===i.length,r.indeterminate=a>0&&a<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!Bn||!Un}function ML(e){const t=e.every(n=>Pt.has(n));for(const n of e)t?Pt.delete(n):Pt.add(n);Sr()}function Kb(e,t){const n=qb(e),r=document.createElement("label");r.className="project-selection-control project-selection-target";const i=document.createElement("input");i.className="project-selection-checkbox",i.dataset.projectFocusKey=`select:${n.join("|")}`,i.type="checkbox",i.setAttribute("aria-label",t),Ub.set(i,n),i.addEventListener("change",()=>ML(n));const a=document.createElement("span");return a.className="sr-only",a.textContent=t,r.append(i,a),r}function OL(e){if(!Un)return[];const t=new Set(e),n=new Map(vi.teams.filter(a=>a.status==="active").map(a=>[a.teamId,a.displayName])),r=new Map(vi.identities.filter(a=>a.status==="active"||a.status==="pending").map(a=>[a.identityId,a.displayName])),i=new Map;for(const a of vi.projectRecipients)if(!(a.status!=="active"||!t.has(a.canonicalProjectIdentity)))if(a.recipientKind==="team"){const s=n.get(a.teamId);s&&i.set(`team:${a.teamId}`,{key:`team:${a.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(a.identityId);s&&i.set(`identity:${a.identityId}`,{key:`identity:${a.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((a,s)=>`${a.kind}:${a.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function Vb(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=OL(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Un?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const a of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${a.kind.toLowerCase()}`,s.textContent=`${a.kind}: ${a.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function Wb(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!Bn||!Un,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{qi({mode:"project-manage",projectId:e[0]})})):(n.textContent="Share selected",n.setAttribute("aria-label",`Share selected identities for ${t}`),n.dataset.projectFocusKey=`share:${e.join("|")}`,n.addEventListener("click",()=>{for(const r of e)Pt.add(r);Sr(),qi({mode:"project-add",projectIds:[...e].sort()})})),n}function jL(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function yu(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function bu(e){return e.project||e.display_project||"Unnamed Project"}function zb(e){const t=String(e||"").trim();return t?_.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function FL(){return new Set(_.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function BL(e){return!Oa||e.authority_type!=="coordinator"||!e.group_id?!1:!FL().has(String(e.group_id).trim())}function Jb(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function Yb(){zs&&(zs=!1,at?.())}async function UL(){try{const e=await Za();_.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{_.lastCoordinatorAdminStatus=null,_.lastCoordinatorAdminGroups=[],Oa=!1;return}if(_.lastCoordinatorAdminStatus?.readiness!=="ready"||!_.lastCoordinatorAdminStatus.has_admin_secret){_.lastCoordinatorAdminGroups=[],Oa=!1;return}try{const e=await Cp(!1);_.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],Oa=!0}catch{_.lastCoordinatorAdminGroups=[],Oa=!1}}function GL(e){return e.kind==="team_default"}function _u(e){const t=e.label||"Untitled Space";return GL(e)?`${t} (default)`:t}function HL(e,t){const n=_u(e);return t.some(r=>r.scope_id!==e.scope_id&&_u(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function qL(e){const t=zb(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Space":`${e.authority_type||"Other"} Space`}function KL(e){return e?pu.find(t=>t.scope_id===e)??null:null}function Ys(e){const t=KL(e);return e?t?`${_u(t)} · ${qL(t)}`:"Unknown Space":"—"}function wu(){return pu.filter(e=>e.scope_id!=="legacy-shared-review"&&!BL(e))}function VL(e){return wu().some(t=>t.scope_id===e)}function Xb(...e){for(const t of e)if(t&&VL(t))return t;return e.find(t=>!!t)??""}function WL(e){const t=zb(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function zL(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function JL(){const e=new Map;for(const t of wu()){const n=zL(t),r=WL(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function Qb(e){for(const t of JL()){const n=document.createElement("optgroup");n.label=t.label;for(const r of t.scopes){const i=document.createElement("option");i.value=r.scope_id,i.textContent=HL(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function YL(e){switch(e.code){case"unknown_project_local_only":return"Current behavior";case"basename_collision_review":return"Name collision";case"scope_reassignment_old_copies":return"Previous copies";case"broad_org_domain_pattern":case"home_directory_org_domain_pattern":return"Broad mapping";default:return"Review item"}}async function Su(e,t,n=[]){try{await jS({...e.mapping_id&&e.resolution_reason==="exact_mapping"?{id:e.mapping_id}:{},...n.length>0?{confirmed_guardrail_tokens:n}:{},project_pattern:e.display_project,scope_id:t,workspace_identity:e.workspace_identity}),wr.delete(e.workspace_identity),Vs.delete(e.workspace_identity),oe("Project Space assignment updated. Device access grants are unchanged."),at?.()}catch(r){if(r instanceof no){wr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),at?.();return}oe(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function XL(e,t){const n=e.filter(gu);if(n.length!==0)try{await FS({mappings:n.map(r=>({...r.mapping_id&&r.resolution_reason==="exact_mapping"?{id:r.mapping_id}:{},project_pattern:r.display_project,scope_id:t,workspace_identity:r.workspace_identity}))}),oe(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),Ws.delete(yu(n[0])),at?.()}catch(r){oe(r instanceof no?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":r instanceof Error?r.message:"Unable to update project Spaces.","warning")}}async function QL(e){if(e.mapping_id!=null)try{await BS(e.mapping_id),wr.delete(e.workspace_identity),Vs.delete(e.workspace_identity),oe("Project Space assignment removed. The next fallback now applies."),at?.()}catch(t){oe(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function Zb(e,t=!1){try{const n=Ma.get(e.workspace_identity),r=await GS({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});Ma.delete(e.workspace_identity),oe(`Forgot ${r.forgotten_memory_count.toLocaleString()} local memor${r.forgotten_memory_count===1?"y":"ies"}. ${r.peer_owned_memory_count.toLocaleString()} peer-owned memor${r.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),at?.()}catch(n){if(n instanceof xp){Ma.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),at?.();return}oe(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function ZL(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await eo()).filter(i=>i&&i!==t)}catch{}const r=await pd({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const a=i.trim();return a?a===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await US({project:r.trim(),workspace_identity:e.workspace_identity});oe(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),at?.()}catch(i){oe(i instanceof Error?i.message:"Unable to change project.","warning")}}function e$(e){const t=document.createElement("div");if(t.className="project-inventory-actions",gu(e)&&e.memory_count!=null&&e.guardrail_warnings.every(f=>!f.requires_confirmation)){const f=document.createElement("button");f.className="settings-button",f.type="button",f.textContent="Share",f.disabled=!Bn,Bn||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>Do([e.workspace_identity])),t.appendChild(f)}if(yi(e)){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(f),t}if(e.identity_source==="unmapped"){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(f),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const a=wu().some(f=>f.scope_id===e.resolved_scope_id);if(!a&&e.resolved_scope_id){const f=document.createElement("option");f.value=e.resolved_scope_id,f.textContent=`${Ys(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}Qb(i),i.value=Xb(Vs.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!a,s.addEventListener("click",()=>{Su(e,i.value)}),i.addEventListener("change",()=>{Vs.set(e.workspace_identity,i.value),wr.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,at?.()}),i.addEventListener("blur",Yb);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Su(e,"local-default")});const l=document.createElement("button");l.className="settings-button",l.type="button",l.textContent="Remove mapping",l.disabled=e.mapping_id==null||e.resolution_reason!=="exact_mapping",l.addEventListener("click",()=>{QL(e)});const d=document.createElement("button");d.className="settings-button",d.type="button",d.textContent="Change project…",d.disabled=e.session_count===0,d.disabled&&(d.title="No sessions are available to reassign for this saved mapping."),d.addEventListener("click",()=>{ZL(e)});const u=document.createElement("button");u.className="settings-button danger",u.type="button",u.textContent="Forget local memories…",u.disabled=(e.memory_count??0)===0,u.addEventListener("click",()=>{Zb(e)}),t.append(n,i,s,c,l,d,u);const p=wr.get(e.workspace_identity);if(p){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.textContent="Confirmation required before saving this Space.";const h=document.createElement("p");h.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const v=document.createElement("ul");for(const S of p.warnings){const C=document.createElement("li"),T=document.createElement("strong");T.textContent=`${YL(S)}: `;const P=document.createElement("span");P.textContent=S.message,C.append(T,P),v.appendChild(C)}const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="I understand, save Space",w.addEventListener("click",()=>{const S=wr.get(e.workspace_identity);!S||S.scopeId!==i.value||Su(e,S.scopeId,S.requiredGuardrailTokens)});const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="Cancel",b.addEventListener("click",()=>{wr.delete(e.workspace_identity),at?.()}),f.append(g,h,v,w,b),t.appendChild(f)}const m=Ma.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.textContent="Confirm project memory cleanup.";const h=document.createElement("p");h.textContent=`${m.localOwnedMemoryCount.toLocaleString()} locally owned memor${m.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${m.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${m.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const v=document.createElement("p");v.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const w=document.createElement("button");w.className="settings-button danger",w.type="button",w.textContent="I understand, forget local memories",w.addEventListener("click",()=>{Zb(e,!0)});const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="Cancel",b.addEventListener("click",()=>{Ma.delete(e.workspace_identity),at?.()}),f.append(g,h,v,w,b),t.appendChild(f)}return t}function e_(e){const t=document.createElement("article");t.className="project-inventory-row";const n=`project-title-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;t.setAttribute("aria-labelledby",n);const r=document.createElement("div");r.className="project-inventory-row-header",Ao(e)&&r.appendChild(Kb([e],`Select ${e.display_project} for recipient sharing`));const i=document.createElement("h3");i.className="project-inventory-title",i.id=n,i.textContent=e.display_project,r.appendChild(i),Ao(e)&&r.appendChild(Wb([e.workspace_identity],e.display_project)),t.appendChild(r);const a=document.createElement("div");a.className="project-inventory-meta",a.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${Hb(e.latest_session_at)}`,t.appendChild(a),t.appendChild(Vb([e.workspace_identity]));const s=document.createElement("div");s.className="project-advanced-administration";const c=document.createElement("div");c.className="project-inventory-domain",c.textContent=vu(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${LL(e)} · ${e.identity_source} · ${Hb(e.latest_session_at)}`,s.appendChild(l),e.sharing&&e.sharing.length>0){const h=document.createElement("div");h.className="settings-note project-sharing-summary";const v=document.createElement("strong");v.textContent="Project sharing";const w=document.createElement("ul");w.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const b of e.sharing){const S=document.createElement("li"),C=document.createElement("strong");C.textContent=$L(b);const T=document.createElement("span");T.textContent=` — ${b.lifecycle.label}. ${b.lifecycle.explanation}`,S.append(C,T),w.appendChild(S)}h.append(v,w),s.appendChild(h)}if(yi(e)){const h=document.createElement("div");h.className="settings-note",h.textContent="Received memories keep the source device's project and Space assignment. Local reassignment controls are disabled here to avoid split-brain sync state.",s.appendChild(h)}const d=document.createElement("div");if(d.className="project-inventory-signal mono",d.textContent=jL(e),s.appendChild(d),e.suggested_scope_id&&e.suggested_scope_id!==e.resolved_scope_id){const h=document.createElement("div");h.className="settings-note project-suggestion-note",h.textContent=e.suggestion_reason?`Suggestion: ${e.suggestion_reason}`:`Suggestion: assign this project to ${Ys(e.suggested_scope_id)}.`,s.appendChild(h)}const u=(e.guardrail_warnings??[]).filter(h=>h.severity==="warning");if(u.length>0){const h=document.createElement("div");h.className="settings-note project-attention-note",h.textContent=`Needs attention: ${u.map(v=>v.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const v of e.statuses){const w=document.createElement("span");w.className=`project-status-badge ${v}`,w.textContent=RL(v),h.appendChild(w)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=mu.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?mu.add(e.workspace_identity):mu.delete(e.workspace_identity)});const m=document.createElement("summary");m.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(m),p.appendChild(s);const f=document.createElement("dl");f.className="project-detail-grid";const g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",vu(e)],["Suggested Space",e.suggested_scope_id?Ys(e.suggested_scope_id):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]];for(const[h,v]of g){const w=document.createElement("dt");w.textContent=h;const b=document.createElement("dd");b.textContent=v==null||v===""?"—":String(v),f.append(w,b)}return p.appendChild(f),p.appendChild(e$(e)),t.appendChild(p),t}function t$(e){const t=[...new Set(e.map(n=>vu(n)))];return t.length===1?t[0]:"Mixed Spaces"}function n$(e){if(e.length===1)return e_(e[0]);const t=yu(e[0]),n=e.filter(Ao),r=qb(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const a=bu(e[0]),s=`project-cluster-title-${t.replace(/[^a-z0-9_-]/gi,"-")}`;i.setAttribute("aria-labelledby",s);const c=document.createElement("div");c.className="project-inventory-row-header",n.length>0&&c.appendChild(Kb(n,`Select all identities for ${bu(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=a,c.appendChild(l),r.length>0&&c.appendChild(Wb(r,a)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=t$(e),d.appendChild(u);const p=e.reduce((S,C)=>S+(C.memory_count??0),0),m=e.reduce((S,C)=>S+C.session_count,0),f=document.createElement("div");f.className="project-inventory-meta",f.textContent=`${e.length} identities · ${m.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(f),i.appendChild(Vb(r));const g=document.createElement("div");g.className="project-inventory-actions";const h=e.filter(gu);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(yi)?"These project identities were received from peers. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.",g.appendChild(S),d.appendChild(g)}else{const S=h.map(E=>({project:E,warnings:(E.guardrail_warnings??[]).filter(j=>j.requires_confirmation)})),C=S.some(({warnings:E})=>E.length>0),T=new Set(h.map(E=>E.suggested_scope_id).filter(E=>!!E)),P=new Set(h.map(E=>E.resolved_scope_id)),k=document.createElement("select");k.className="project-domain-select",k.setAttribute("aria-label",`Space for ${bu(e[0])} group`);const M=document.createElement("option");M.value="",M.textContent="Choose Space…",k.appendChild(M),Qb(k),k.value=Xb(Ws.get(t));const U=document.createElement("button");if(U.className="settings-button",U.type="button",U.textContent=`Save Space for ${h.length} identit${h.length===1?"y":"ies"}`,U.disabled=!k.value||C,U.addEventListener("click",()=>{XL(h,k.value)}),k.addEventListener("change",()=>{k.value?Ws.set(t,k.value):Ws.delete(t),U.disabled=!k.value||C}),k.addEventListener("blur",Yb),g.append(k,U),T.size>1||P.size>1||C){const E=document.createElement("div");if(E.className="settings-note project-attention-note",E.textContent=C?"One or more identities in this group need individual review before bulk assignment.":"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment.",C){const j=document.createElement("ul");for(const{project:O,warnings:q}of S){if(q.length===0)continue;const L=document.createElement("li"),R=document.createElement("strong");R.textContent=`Blocked identity: ${O.workspace_identity}`;const A=document.createElement("span");A.textContent=` — ${q.map(I=>I.message).join(" ")}`,L.append(R,A),j.appendChild(L)}E.appendChild(j)}g.appendChild(E)}d.appendChild(g)}const v=document.createElement("details");v.className="project-inventory-details",v.open=fu.has(t),v.addEventListener("toggle",()=>{v.open?fu.add(t):fu.delete(t)});const w=document.createElement("summary"),b=e.reduce((S,C)=>S+(C.guardrail_warnings??[]).filter(T=>T.severity==="warning").length,0);w.textContent=b>0?`Advanced Project administration — ${b.toLocaleString()} item${b===1?"":"s"} need attention`:"Advanced Project administration",v.appendChild(w),v.appendChild(d);for(const S of e)v.appendChild(e_(S));return i.appendChild(v),i}function r$(e){const t=new Map;for(const n of e){const r=yu(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function t_(e){const t=qe("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function n_(){document.getElementById("projectsInventorySkeleton")?.remove()}function r_(e){const t=qe("projectsInventoryMeta"),n=qe("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;if(n_(),n.textContent="",e.projects.length===0)t_("No projects match those filters.");else for(const s of r$(e.projects))n.appendChild(n$(s));t.textContent=e.total===0?"0 project identities found":`${e.total} project identit${e.total===1?"y":"ies"} found · showing ${e.offset+1}-${Math.min(e.offset+e.projects.length,e.total)}`;const i=qe("projectsPrevPage"),a=qe("projectsNextPage");i&&(i.disabled=e.offset===0),a&&(a.disabled=!e.has_more),Sr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function i$(e,t){UL().then(()=>{t===gi&&(Jb()||r_(e))})}async function a$(){const e=new Map;let t=0;for(;;){const n=await io({limit:250,offset:t});for(const r of n.projects)e.set(r.workspace_identity,r);if(!n.has_more)break;t+=n.limit}return[...e.values()]}function i_(e,t,n){const r=qe("recipientPolicyManagementMount");r&&Of(r,xo(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Pt.clear(),Sr(),at?.()}})}function o$(e,t){const n=t?.candidates.filter(d=>d.status!=="ready")??[],r=e.querySelector(":scope > .project-team-setup-entry");r?.querySelector(".project-team-setup-status")?.remove();const i=r?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement?document.activeElement.dataset.teamSetupCandidateRef:void 0;if(n.length===0){r?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,i&&qe("projectsSearch")?.focus();return}const a=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===a){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=a;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),hu){const m=document.createElement("button");m.setAttribute("aria-label",`Finish setting up ${d.displayName}`),m.className="settings-button",m.type="button",m.textContent="Finish setting up this Team",m.dataset.teamSetupCandidateRef=d.candidateRef,m.addEventListener("click",()=>hu?.(d.candidateRef)),u.appendChild(m)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||qe("projectsSearch")?.focus()}}function s$(e){const t=e.querySelector(":scope > .project-team-setup-entry");if(!t)return;let n=t.querySelector(".project-team-setup-status");n||(n=document.createElement("p"),n.className="section-meta project-team-setup-status",n.setAttribute("role","status"),t.appendChild(n)),n.textContent="Team setup status is temporarily unavailable. The previous Team setup status is being shown.",e.hidden=!1}function c$(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}async function Cu(e={}){const t=qe("projectsInventoryMeta"),n=qe("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await Gb(!0)).ok:!0;if(Jb())return zs=!0,!e.requireTeamSetupSummary;zs=!1;const r=++gi;Bn=!1,Un=!1,Sr(),t.textContent="Loading project inventory…";try{const i=Gb(e.requireTeamSetupSummary===!0),[a,s,c,l,d]=await Promise.all([io({limit:uu,offset:$a,q:qe("projectsSearch")?.value.trim()||void 0,status:qe("projectsStatusFilter")?.value||void 0}),DS(),a$().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),RS().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),wc().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==gi)return e.requireTeamSetupSummary&&await i,!1;if(pu=s.scopes,Bn=c.ok,Un=d.ok,vi=d.ok?d.intent:Js,c.ok){const g=new Set(xo(c.projects).map(h=>h.canonicalProjectIdentity));for(const h of Pt)g.has(h)||Pt.delete(h)}const u=qe("projectShareFlowMount");u&&Hf(u,c.projects,{inventoryError:!c.ok});const p=qe("recipientPolicyReviewMount");if(p){const g=c$(p);"review"in l?AL(g,l.review):xL(g,l.error),p.hidden=g.hidden&&!p.querySelector(".project-team-setup-entry")}i_(c.projects,vi,!c.ok||!d.ok),r_(a),i$(a,r),i.then(g=>{if(r!==gi)return;const h=qe("recipientPolicyReviewMount");if(h){if(!g.ok){s$(h);return}o$(h,g.summary)}});const m=c.ok&&"review"in l&&d.ok;if(!e.requireTeamSetupSummary)return m;const f=await i;return r!==gi?!1:m&&f.ok}catch(i){if(r!==gi)return!1;Bn=!1,Un=!1,vi=Js;const a=qe("projectShareFlowMount");return a&&Hf(a,[],{inventoryError:!0}),i_([],Js,!0),Sr(),n_(),t.textContent="Project inventory failed to load.",t_(i instanceof Error?i.message:"Unable to load project inventory."),!1}}function l$(e,t={}){at=e,hu=t.onOpenTeamSetup,Pt.clear();const n=qe("projectsStatusFilter");if(n&&n.options.length===0)for(const[a,s]of Bb){const c=document.createElement("option");c.value=a,c.textContent=s,n.appendChild(c)}const r=()=>{$a=0,at?.()};qe("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),qe("projectsPrevPage")?.addEventListener("click",()=>{$a=Math.max(0,$a-uu),at?.()}),qe("projectsNextPage")?.addEventListener("click",()=>{$a+=uu,at?.()});const i=qe("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Pt.size!==0&&qi({mode:"project-add",projectIds:[...Pt].sort()})})),Sr()}function Nu(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(a=>a.trim()):r;if(t.requireNonEmpty&&i.some(a=>a.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function d$(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,a]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof a!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=a}return r}var a_="codemem-settings-advanced",o_="gpt-5.1-codex-mini",s_="claude-4.5-haiku",u$=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],p$={claudeCommand:"claude_command",codexCommand:"codex_command",observerProvider:"observer_provider",observerModel:"observer_model",observerTierRoutingEnabled:"observer_tier_routing_enabled",observerSimpleModel:"observer_simple_model",observerSimpleTemperature:"observer_simple_temperature",observerReasoningEffort:"observer_reasoning_effort",observerReasoningSummary:"observer_reasoning_summary",observerRichModel:"observer_rich_model",observerRichTemperature:"observer_rich_temperature",observerRichReasoningEffort:"observer_rich_reasoning_effort",observerRichReasoningSummary:"observer_rich_reasoning_summary",observerRichMaxOutputTokens:"observer_rich_max_output_tokens",observerRuntime:"observer_runtime",observerAuthSource:"observer_auth_source",observerAuthFile:"observer_auth_file",observerAuthCommand:"observer_auth_command",observerAuthTimeoutMs:"observer_auth_timeout_ms",observerAuthCacheTtlS:"observer_auth_cache_ttl_s",observerHeaders:"observer_headers",observerMaxChars:"observer_max_chars",packObservationLimit:"pack_observation_limit",packSessionLimit:"pack_session_limit",rawEventsSweeperIntervalS:"raw_events_sweeper_interval_s",syncEnabled:"sync_enabled",syncHost:"sync_host",syncPort:"sync_port",syncInterval:"sync_interval_s",syncMdns:"sync_mdns",syncCoordinatorUrl:"sync_coordinator_url",syncCoordinatorGroup:"sync_coordinator_group",syncCoordinatorTimeout:"sync_coordinator_timeout_s",syncCoordinatorPresenceTtl:"sync_coordinator_presence_ttl_s"},m$=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),f$={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",observerReasoningEffort:"",observerReasoningSummary:"",observerRichModel:"",observerRichTemperature:"",observerRichReasoningEffort:"",observerRichReasoningSummary:"",observerRichMaxOutputTokens:"",observerRuntime:"api_http",observerAuthSource:"auto",observerAuthFile:"",observerAuthCommand:"",observerAuthTimeoutMs:"",observerAuthCacheTtlS:"",observerHeaders:"",observerMaxChars:"",packObservationLimit:"",packSessionLimit:"",rawEventsSweeperIntervalS:"",syncEnabled:!1,syncHost:"",syncPort:"",syncInterval:"",syncMdns:!1,syncCoordinatorUrl:"",syncCoordinatorGroup:"",syncCoordinatorTimeout:"",syncCoordinatorPresenceTtl:""};function h$(){try{return globalThis.localStorage?.getItem(a_)==="1"}catch{return!1}}function g$(e){try{globalThis.localStorage?.setItem(a_,e?"1":"0")}catch{}}function vn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ae(e,t,n){if(vn(t,n))return t[n];if(vn(e,n))return e[n]}function Le(e){return e==null?"":String(e)}function Xs(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(!t||["0","false","no","off"].includes(t))return!1;if(["1","true","yes","on"].includes(t))return!0}return!!e}function v$(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function y$(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Je(e){const t=e.trim();return t===""?"":t}function b$(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:s_,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:o_,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:s_,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:"opencode/gpt-5.1-codex-mini",source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:o_,source:"Recommended (direct API)"}}function _$(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return Je(Le(n[t]));case"observer_runtime":return Je(Le(n.observer_runtime));case"observer_auth_source":return Je(Le(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([a,s])=>{typeof a=="string"&&a.trim()&&typeof s=="string"&&(i[a.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!vn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r!==0?r:""}case"sync_coordinator_timeout_s":case"sync_coordinator_presence_ttl_s":{if(!vn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!vn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)?r:""}case"sync_enabled":case"sync_mdns":case"observer_tier_routing_enabled":return Xs(n[t]);default:return vn(n,t)?n[t]:""}}function w$(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{vn(r,i)&&(r[i]=_$(t,i))}),r}function S$(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let a=[];try{a=Nu(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(C){if(!i||n.has("claude_command"))throw C;const T=r.claude_command;a=Array.isArray(T)?T.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let s=[];try{s=Nu(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(C){if(!i||n.has("codex_command"))throw C;const T=r.codex_command;s=Array.isArray(T)?T.filter(P=>typeof P=="string").map(P=>P.trim()).filter(P=>P.length>0):[]}let c=[];try{c=Nu(t.observerAuthCommand,{label:"observer auth command"})}catch(C){if(!i||n.has("observer_auth_command"))throw C;const T=r.observer_auth_command;c=Array.isArray(T)?T.filter(P=>typeof P=="string"):[]}let l={};try{l=d$(t.observerHeaders)}catch(C){if(!i||n.has("observer_headers"))throw C;const T=r.observer_headers;T&&typeof T=="object"&&!Array.isArray(T)&&Object.entries(T).forEach(([P,k])=>{typeof P=="string"&&P.trim()&&typeof k=="string"&&(l[P]=k)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),h=u===""?"":Number(u),v=p===""?"":Number(p),w=m===""?"":Number(m),b=Number(f),S=f===""?"":b;if(d!==""&&!Number.isFinite(g))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof v!="number"||!Number.isFinite(v)||v<0))throw new Error("rich tier temperature must be a non-negative number");if(m!==""&&(typeof w!="number"||!Number.isFinite(w)||w<=0||!Number.isInteger(w)))throw new Error("rich tier max output tokens must be a positive integer");if(f!==""&&(!Number.isFinite(b)||b<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:a,codex_command:s,observer_provider:Je(t.observerProvider),observer_model:Je(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Je(t.observerSimpleModel),observer_simple_temperature:h,observer_reasoning_effort:Je(t.observerReasoningEffort),observer_reasoning_summary:Je(t.observerReasoningSummary),observer_rich_model:Je(t.observerRichModel),observer_rich_temperature:v,observer_rich_reasoning_effort:Je(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Je(t.observerRichReasoningSummary),observer_rich_max_output_tokens:w,observer_runtime:Je(t.observerRuntime||"api_http")||"api_http",observer_auth_source:Je(t.observerAuthSource||"auto")||"auto",observer_auth_file:Je(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:g,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:S,sync_enabled:t.syncEnabled,sync_host:Je(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Je(t.syncCoordinatorUrl),sync_coordinator_group:Je(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function C$(e){const t=e.config||{},n=e.effective||{},r=Ae(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,m])=>typeof p=="string"&&p.trim()&&typeof m=="string")):{},a=Ae(t,n,"claude_command"),s=Array.isArray(a)?a.filter(p=>typeof p=="string"):[],c=Ae(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ae(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Le(Ae(t,n,"observer_provider")),observerModel:Le(Ae(t,n,"observer_model")),observerTierRoutingEnabled:Xs(Ae(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Le(Ae(t,n,"observer_simple_model")),observerSimpleTemperature:Le(Ae(t,n,"observer_simple_temperature")),observerReasoningEffort:Le(Ae(t,n,"observer_reasoning_effort")),observerReasoningSummary:Le(Ae(t,n,"observer_reasoning_summary")),observerRichModel:Le(Ae(t,n,"observer_rich_model")),observerRichTemperature:Le(Ae(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Le(Ae(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Le(Ae(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Le(Ae(t,n,"observer_rich_max_output_tokens")),observerRuntime:Le(Ae(t,n,"observer_runtime"))||"api_http",observerAuthSource:Le(Ae(t,n,"observer_auth_source"))||"auto",observerAuthFile:Le(Ae(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Le(Ae(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Le(Ae(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Le(Ae(t,n,"observer_max_chars")),packObservationLimit:Le(Ae(t,n,"pack_observation_limit")),packSessionLimit:Le(Ae(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Le(Ae(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Xs(Ae(t,n,"sync_enabled")),syncHost:Le(Ae(t,n,"sync_host")),syncPort:Le(Ae(t,n,"sync_port")),syncInterval:Le(Ae(t,n,"sync_interval_s")),syncMdns:Xs(Ae(t,n,"sync_mdns")),syncCoordinatorUrl:Le(Ae(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Le(Ae(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Le(Ae(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Le(Ae(t,n,"sync_coordinator_presence_ttl_s"))}}function N$(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=b$(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Je(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>vn(t,r))?"Env override":n.source}: ${n.model}`}function T$(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to Luna and richer batches to Terra with medium reasoning by default. Official OpenAI and OAuth Codex consumer requests always use Responses. The observer_openai_use_responses=false compatibility setting selects chat completions only for an explicitly configured custom OpenAI-compatible base URL. Sidecar runtimes route both tiers through their local CLI.":"Off: codemem uses the base observer settings from the Connection tab for all batches. Explicit user settings always win over built-in routing defaults."}function I$(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function k$(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Processing controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function E$(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while the Processing tab owns simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-5.4-mini` for Direct API, `gpt-5.1-codex-mini` for Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function P$(e){return!e}function A$(e,t,n){return t.has(e)||n.has(e)}function x$(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var X={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:h$(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...f$}}};function R$(){X.controller?.hideTooltip()}function Cr(e){if(X.controller){X.controller.setRenderState(e);return}X.renderState={...X.renderState,...e}}function D$(e){Cr({values:{...X.renderState.values,...e}})}function L$(e){const t=["observer","queue","sync"].includes(e)?e:"observer";X.activeTab=t,X.controller?.setActiveTab(t)}function Qs(e,t=!0){_.settingsDirty=e,t&&X.controller?.setDirty(e)}function $$(e){X.showAdvanced=e,X.controller?.setShowAdvanced(e)}function c_(){return X.open}function M$(e){return A$(e,X.protectedKeys,m$)}function l_(e={}){return S$({values:X.renderState.values,touchedKeys:X.touchedKeys,baseline:X.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function O$(e){Cr({observerStatus:e&&typeof e=="object"?e:null})}function j$(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},a=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=C$(t);X.envOverrides=i,X.protectedKeys=new Set(a),_.configDefaults=n,_.configPath=t.path||"",Cr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:_.configPath?`Config path: ${_.configPath}`:"Config path: n/a",providers:v$(t.providers),statusText:"No unsaved changes",values:s}),X.touchedKeys=new Set;try{X.baseline=w$(l_({allowUntouchedParseErrors:!0}),r,i)}catch{X.baseline={}}Qs(!1)}async function F$(){if(!X.open)try{const[e,t]=await Promise.all([Mw(),$w().catch(()=>null)]);j$(e),O$(t)}catch{}}function Tu(e){return String(e||"").replace(/_/g," ")}function Iu(e){const t=e.filter(n=>typeof n=="string"&&n.trim());return t.length===0?"":t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function B$(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function U$(e){const t=[];return e.oauth&&t.push("OAuth"),e.api_key&&t.push("API key"),e.env_var&&t.push("env var"),t.length?t.join(", "):"none"}function G$(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function H$({status:e}){if(!e)return o("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,a])=>a&&typeof a=="object");return o("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?o(Z,{children:[o("div",{className:"status-label",children:"Active observer"}),o("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",B$(t.auth?.method||"none")," ",o("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:o("i",{"aria-hidden":"true","data-lucide":t.auth?.token_present===!0?"check":"x"})})]})]}):o(Z,{children:[o("div",{className:"status-label",children:"Observer status"}),o("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),i.length?o(Z,{children:[o("div",{className:"status-label",children:"Available credentials"}),o("div",{children:i.map(([a,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return o("span",{className:"status-cred",children:[c>0?" · ":null,o("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?o("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(a),": ",U$(l)]},a)})})]}):null,r&&typeof r=="object"?o(Z,{children:[o("div",{className:"status-label",children:"Latest processing issue"}),o("div",{className:"status-issue",children:[o("div",{className:"status-issue-message",children:typeof r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),o("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${G$(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?o("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function d_(e,t){const n=t.getBoundingClientRect(),r=8,i=8,a=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-a/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-a-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Fa(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function q$(e){if(!e)return[];const t=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[href]",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(t)).filter(n=>{const r=n;return!r.hidden&&r.offsetParent!==null})}function K$(){const e=Oe("settingsModal");(q$(e)[0]||e)?.focus()}function V$(){const[e,t]=x({anchor:null,content:"",visible:!1}),n=B(null);return J(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},a=u=>{const p=Fa(u.target);p&&r(p)},s=u=>{const p=Fa(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=Fa(u.target);p&&r(p)},l=u=>{Fa(u.target)&&i()},d=u=>{const p=Fa(u.target);p&&(u.preventDefault(),t(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const f=p.dataset.tooltip?.trim()||"";return f?{anchor:p,content:f,visible:!0}:m}))};return document.addEventListener("pointerover",a),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",a),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),bt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&d_(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),J(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&d_(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:Re(()=>typeof document>"u"?null:cn(o("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function W$({DialogContent:e,onClose:t}){const[n,r]=x(X.open),[i,a]=x(["observer","queue","sync"].includes(X.activeTab)?X.activeTab:"observer"),[s,c]=x(_.settingsDirty),[l,d]=x(X.renderState),[u,p]=x(X.showAdvanced),{tooltipPortal:m,setTooltip:f}=V$();X.open=n,X.activeTab=i,_.settingsDirty=s,X.renderState=l,X.showAdvanced=u,J(()=>(X.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const v=["observer","queue","sync"].includes(h)?h:"observer";X.activeTab=v,a(v)},setDirty:h=>{_.settingsDirty=h,c(h)},setOpen:h=>{X.open=h,r(h)},setRenderState:h=>{const v={...X.renderState,...h};X.renderState=v,d(v)},setShowAdvanced:h=>{X.showAdvanced=h,g$(h),p(h)}},()=>{X.controller&&(X.controller=null)}),[]),J(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const g=se(()=>{X.startPolling&&X.refresh&&t(X.startPolling,X.refresh)},[t]);return o(Z,{children:[o(Br,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),K$()},onOpenChange:h=>{if(h){r(!0);return}g()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:o(e,{})}),m]})}function Ue({children:e,className:t="field",hidden:n=!1,id:r}){return o("div",{className:t,hidden:n,id:r,children:e})}function Ba({children:e,hidden:t=!1}){return o("div",{className:"settings-note",hidden:t,children:e})}function ku({detail:e,title:t}){return o("div",{className:"settings-section-intro",children:[o("div",{className:"settings-section-intro-title",children:t}),o("div",{className:"small settings-section-intro-detail",children:e})]})}function z$({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:a,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:m,observerStatusBannerSlot:f}){return o(Z,{children:[o(ku,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),f,o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Connection"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerProvider",children:"Model provider"}),o("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),o(Ln,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerModel",children:l()}),o("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),o(Ne,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),o("div",{className:"small",children:u()}),o("div",{className:"small",id:"observerModelHint",children:p()})]}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRuntime",children:"Connection mode"}),o("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),o(Ln,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),o(ii,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),o("div",{className:"small",children:m("codex_command")})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),o(ii,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),o("div",{className:"small",children:m("claude_command")})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),o(Ne,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),o("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Authentication"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),o("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),o(Ln,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),o(Ue,{hidden:!r,id:"observerAuthFileField",children:[o("label",{htmlFor:"observerAuthFile",children:"Token file path"}),o(Ne,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),o("div",{className:"small",children:m("observer_auth_file")})]}),o(Ue,{hidden:!i,id:"observerAuthCommandField",children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthCommand",children:"Token command"}),o("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),o(ii,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),o("div",{className:"small",children:m("observer_auth_command")})]}),o("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),o(Ba,{hidden:a(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),o(Ne,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),o(Ne,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),o("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),o(ii,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),o("div",{className:"small",children:m("observer_headers")})]})]})]})}function Zs({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:a,onCheckedChange:s}){const c=`${i}Label`;return o("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[o("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:a}),o(ei,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function J$({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:a}){return o(Z,{children:[o(ku,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Processing"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),o("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),o(Ne,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),o("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Tiered observer routing"}),o(Zs,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),o("div",{className:"small",children:a()}),o(Ba,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),o("div",{hidden:!t,children:[o("h4",{children:"Simple tier"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerSimpleModel",children:"Model"}),o("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(Ne,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),o("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),o(Ne,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),o("div",{className:"settings-advanced",hidden:!t||n(),children:[o("h4",{children:"Shared reasoning defaults"}),o("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),o(Ue,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),o(Ne,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),o(Ue,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),o(Ne,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),o("div",{hidden:!t,children:[o("h4",{children:"Rich tier"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRichModel",children:"Model"}),o("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(Ne,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),o("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),o(Ne,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),o(Ne,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),o(Ne,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),o(Ne,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),o("div",{className:"settings-group settings-advanced",hidden:n(),children:[o("h3",{className:"settings-group-title",children:"Pack limits"}),o(Ba,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),o(Ne,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),o("div",{className:"small",children:"Default number of observations to include in a pack."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),o(Ne,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),o("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function Y$({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return o(Z,{children:[o(ku,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Device Sync"}),o(Zs,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),o(Ne,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),o("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncHost",children:"Sync host"}),o(Ne,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncPort",children:"Sync port"}),o(Ne,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),o(Zs,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),o(Ne,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),o("div",{className:"small",children:i("sync_coordinator_url")})]}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),o(Ne,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),o("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:o(Ba,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),o(Ne,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),o(Ne,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function X$({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:a,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return o("div",{className:"modal-card",onKeyDown:p=>Wr(p,{onSubmit:s,disabled:u}),children:[o("div",{className:"modal-header",children:[o("h2",{id:"settingsTitle",children:"Settings"}),o(Oi,{ariaLabel:"Close settings",className:"modal-close-button",onClick:a})]}),o("div",{className:"modal-body",children:[o("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),o("div",{className:"settings-advanced-toolbar",children:[o(Zs,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),o("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:o("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),o(Ba,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),o(Jh,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:u$,triggerClassName:"settings-tab",value:t,children:[o(ir,{className:"settings-panel",forceMount:!0,value:"observer",children:o(z$,{...e,observerStatusBannerSlot:d})}),o(ir,{className:"settings-panel",forceMount:!0,value:"queue",children:o(J$,{...e})}),o(ir,{className:"settings-panel",forceMount:!0,value:"sync",children:o(Y$,{...e})})]}),o("div",{className:"small mono",id:"settingsPath",children:r.pathText}),o("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),o("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),o("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),o("div",{className:"modal-footer",children:[o("div",{className:"small",id:"settingsStatus",children:r.statusText}),o("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function Q$(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:a}=e,s={};return Object.entries(t).forEach(([c,l])=>{a(c)||vn(r,c)&&!i.has(c)||y$(l,n[c])||(s[c]=l)}),s}function Z$(e){const t=s=>{const c=p$[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function eM(e){const t=e?.effects,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=Array.isArray(n.hot_reloaded_keys)?n.hot_reloaded_keys.map(p=>Tu(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Tu(String(p))):[],a=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Tu(String(p))):[],s=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],c=Array.isArray(n.manual_actions)?n.manual_actions:[],l=n.sync&&typeof n.sync=="object"?n.sync:{},d=[];r.length&&d.push(`Applied now: ${Iu(r)}.`),i.length&&d.push(`Live settings updated: ${Iu(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),a.length&&d.push(`Restart required for ${Iu(a)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=a.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var tM=()=>N$(X.renderState.values,X.envOverrides),nM=()=>T$(X.renderState.values),rM=()=>I$(X.renderState.values),iM=()=>k$(X.renderState.values),aM=()=>E$(X.renderState.values),oM=()=>P$(X.showAdvanced),{onTextInput:sM,onSelectValueChange:cM,onSwitchInput:lM}=Z$({getTouchedKeys:()=>X.touchedKeys,getValues:()=>X.renderState.values,updateFormState:D$,setDirty:e=>Qs(e)});function dM(){const e=X.renderState.observerStatus;return o(H$,{status:e})}function uM(){const e=X.renderState.values,t=String(_.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return o(X$,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(X.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((a,s)=>a.localeCompare(s)).map(a=>({label:a,value:a})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:oM,onTextInput:sM,onSelectValueChange:cM,onSwitchInput:lM,getObserverModelLabel:rM,getObserverModelTooltip:iM,getObserverModelDescription:aM,getObserverModelHint:tM,getTieredRoutingHelperText:nM,protectedConfigHelp:x$},activeTab:X.activeTab,showAdvanced:X.showAdvanced,renderState:X.renderState,settingsDirty:_.settingsDirty,onClose:()=>{X.startPolling&&X.refresh&&ec(X.startPolling,X.refresh)},onSave:()=>{X.startPolling&&X.refresh&&hM(X.startPolling,X.refresh)},onActiveTabChange:L$,onAdvancedToggle:$$,observerStatusBannerSlot:o(dM,{})})}function pM(){return o(W$,{DialogContent:uM,onClose:ec})}function mM(){const e=Oe("settingsDialogMount");e&&Ge(o(pM,{}),e)}function u_(){Oe("settingsDialogMount")&&(X.shellMounted||(mM(),X.shellMounted=!0))}function fM(e){X.shellMounted||u_(),X.open=!0,X.previouslyFocused=document.activeElement,e(),X.controller?.setOpen(!0)}function ec(e,t){if(_.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){X.controller?.setOpen(!0);return}X.open=!1,X.controller?.setOpen(!1),R$(),(X.previouslyFocused&&typeof X.previouslyFocused.focus=="function"?X.previouslyFocused:_l("settingsButton"))?.focus(),X.previouslyFocused=null,X.touchedKeys=new Set,e(),t()}async function hM(e,t){if(!X.renderState.isSaving){Cr({isSaving:!0,statusText:"Saving changes…"});try{const n=Q$({current:l_({allowUntouchedParseErrors:!0}),baseline:X.baseline,envOverrides:X.envOverrides,touchedKeys:X.touchedKeys,isProtected:M$});if(Object.keys(n).length===0){Cr({isSaving:!1,statusText:"No unsaved changes"}),Qs(!1),ec(e,t);return}const r=eM(await Ow(n));Cr({isSaving:!1,statusText:"Saved changes"}),Qs(!1),ec(e,t),oe(r.message,r.type)}catch(n){Cr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function gM(e,t,n){X.startPolling=t,X.refresh=n,u_(),_l("settingsButton")?.addEventListener("click",()=>fM(e))}function vM(e){e.dataset.syncRenderRoot="preact"}function yM(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function et(e,t){vM(e),Ge(t,e)}function bi(e){e.dataset.syncRenderRoot==="preact"&&Ge(null,e)}function bM(e){const t=Object.values(e||{}).map(n=>!n||typeof n!="object"?"":String(n.last_ping_at||"").trim()).filter(Boolean).sort();return t[t.length-1]??null}function _M(e){return typeof e=="object"&&e!==null}function wM(e,t){return _.pairingCommandRaw="",{payloadText:e,hintText:t}}function SM(e){if(!_M(e))return wM("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return _.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function CM(){return{title:"Diagnostics still loading.",detail:"Wait a moment for local sync status. If it stays blank, refresh the page or check whether sync is enabled on this device."}}function NM(){return{title:"Diagnostics unavailable right now.",detail:"The viewer could not load sync status. Refresh this page, or check that the local codemem sync service is reachable before retrying."}}function TM(){const e=_.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function IM(){return{title:"Recent attempts unavailable right now.",detail:"Attempt history could not be loaded because sync diagnostics failed. Refresh the page after local sync status is reachable again."}}function kM(e,t){return e==="offline-peers"&&t?"Some recent failures may have happened before all peers went offline. Sync will resume automatically when a peer becomes reachable.":""}function EM({items:e}){return o(Z,{children:e.map((t,n)=>o("div",{class:"stat",children:o("div",{class:"stat-content",children:[o("div",{class:"value",children:t.value}),o("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function PM({attempts:e,note:t}){return o(Z,{children:[t?o("div",{class:"small",children:t}):null,e.map((n,r)=>o("div",{class:"diag-line",children:[o("div",{class:"left",children:[o("div",{children:[n.peerLabel," — ",n.status]}),n.detail?o("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?o("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null]}),o("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function p_({text:e}){return o(Z,{children:e})}function AM({title:e,detail:t}){return o("div",{class:"sync-empty-state",children:[o("strong",{children:e}),o("span",{children:t})]})}function xM(e,t){if(!t.length){bi(e);return}et(e,o(EM,{items:t}))}function RM(e,t,n){if(!t.length){bi(e);return}et(e,o(PM,{attempts:t,note:n}))}function Nr(e,t){et(e,o(AM,{...t}))}function m_(e,t,n){et(e,o(p_,{text:n.payloadText})),t&&et(t,o(p_,{text:n.hintText}))}function f_({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:a,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),m=B(!1);bt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),J(()=>{if(!e){m.current=!1;return}m.current||(m.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const f=o(Jo,{forceMount:!0,asChild:!0,children:o("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return o(zo,{open:e,onOpenChange:t,children:[o(eg,{asChild:!0,children:o("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?a:i})}),l?cn(f,l):f]})}function DM({open:e,onOpenChange:t}){return o(f_,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[o("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),o("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),o("div",{className:"actor-create-row",children:[o("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),o(Ne,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),o("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),o("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),o("div",{className:"sync-ttl-group",children:[o("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),o(Ne,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),o("span",{children:"hours"})]}),o("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),o("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),o(ii,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),o("div",{className:"peer-meta",id:"syncInviteAdminHint"}),o("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function LM({contentHost:e,open:t,onOpenChange:n}){return o(f_,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[o("div",{className:"peer-title",children:[o("strong",{children:"Pairing command"}),o("div",{className:"peer-actions",children:o("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),o("div",{className:"pairing-body",children:o("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),o("div",{className:"peer-meta",id:"pairingHint"})]})}function $M(e,t){et(e,o(DM,{...t}))}function MM(e,t){et(e,o(LM,{...t}))}function me(e){return String(e??"").trim()}function OM(e){return me(e).replace(/\s+/g," ").toLowerCase()}function jM(e){const t=me(e);return t?t.slice(0,8):"Unnamed device"}function h_(e){return me(e?.last_error).toLowerCase()}function g_(e){return e.includes("401")&&e.includes("unauthorized")}function v_(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var FM={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function y_(e){return e.device?.needs_local_approval?{state:"needs-your-approval",badgeLabel:"Needs your approval",description:"Another device already approved this pairing. Approve it here to finish the connection on both sides.",actionLabel:"Approve on this device"}:e.device?.waiting_for_peer_approval?{state:"waiting-for-other-device",badgeLabel:"Waiting on other device",description:"You already approved this pairing here. The other device still needs to approve this one before sync can work both ways.",actionLabel:null}:{state:"none",badgeLabel:null,description:null,actionLabel:null}}function BM(e){const t=y_(e);return!me(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function b_(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),a=qM(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${a}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>__(i)==="trust").length===n.length?{ok:!1,message:"This device no longer has two-way trust with the peer. Pair it again from the other device, or remove the stale local record if it should be gone.",warning:!0}:n.filter(i=>__(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review Space access for this device in Teams, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:me(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function __(e){if(e.failureCategory)return e.failureCategory;const t=Array.isArray(e.perScopeResults)?e.perScopeResults.filter(r=>r&&r.ok===!1).map(r=>r.failureCategory).filter(r=>!!r):[];if(t.length)return new Set(t).size===1?t[0]:"other";const n=me(e.error);return UM(n)?"trust":GM(n)?"scope":null}function UM(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function GM(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function HM(e){const t=me(e?.reason);return FM[t]??(t.replaceAll("_"," ")||"sync filters")}function qM(e){const t=new Map;for(const n of e){const r=HM(n),i=Math.max(0,Number(n?.skipped_count??0));i!==0&&t.set(r,(t.get(r)??0)+i)}return t.size?Array.from(t.entries()).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).map(([n,r])=>`${r.toLocaleString()} by ${n}`).join(", "):"sync filters"}function w_(e){const t=me(e.localName);if(t)return t;const n=me(e.coordinatorName);return n||jM(me(e.deviceId))}function KM(e){const t=me(e.localName),n=me(e.coordinatorName);return t||n?!1:!!me(e.deviceId)}function VM(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Ua(e){const t=me(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=h_(e);return g_(n)?"needs-repair":v_(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function _i(e){const t=e?.status||{},n=me(t.peer_state),r=h_(e),i=me(t.sync_status)==="ok"||me(t.ping_status)==="ok";return n==="offline"||n==="stale"?{state:"offline",badgeLabel:"Offline",description:"This device was paired before, but it is offline right now.",isWarning:!0}:g_(r)?{state:"needs-repairing",badgeLabel:"Needs re-pairing",description:"This device no longer accepts this one. Pair again from the other device, or remove this local record if it no longer belongs here.",isWarning:!0}:v_(r)?{state:"offline",badgeLabel:"Offline",description:"This device is saved here, but none of its last known addresses are responding right now.",isWarning:!0}:i||n==="online"?{state:"mutual-trust",badgeLabel:"Two-way trust",description:"Both devices trust each other and sync can run in both directions.",isWarning:!1}:e?.has_error||n==="degraded"?{state:"needs-review",badgeLabel:"Needs review",description:"This device has a sync problem that needs review before you trust the current state again.",isWarning:!0}:{state:"trusted-by-you",badgeLabel:"Waiting on other device",description:"This device is already trusted here. Finish setup on the other device before sync can run both ways.",isWarning:!1}}var WM={missing_scope:"Missing scope id",sender_not_member:"Sender not a scope member",receiver_not_member:"Receiver not a scope member",stale_epoch:"Stale or revoked membership",scope_mismatch:"Scope mismatch",visibility_filter:"Visibility filter",project_filter:"Project filter"};function zM(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,a]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(a??0));if(s===0)continue;const c=i;r.push({reason:c,label:WM[c]??i,count:s})}return r.sort((i,a)=>a.count-i.count||i.label.localeCompare(a.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function S_(e){return Array.isArray(e)?e.map(t=>me(t)).filter(t=>!!t):[]}function C_(e,t){if(e.length===0)return t;const n=e.slice(0,3).join(", "),r=e.length-3;return r>0?`${n} +${r.toLocaleString()} more`:n}function tc(e,t){return e?e.replaceAll("_"," "):t}function JM(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=me(r.scope_id),a=me(r.label);if(!i&&!a)return null;const s=a||"Untitled Space",c=[tc(me(r.kind),"user"),tc(me(r.authority_type),"local"),`${tc(me(r.role),"member")} role`].filter(Boolean).join(" · ");return{scopeId:i||s,label:s,detail:c}}).filter(r=>r!=null),n=t.length;return{total:n,badgeLabel:n===1?"1 Space":n>1?`${n} Spaces`:"No Space access",isWarning:n===0,domains:t,emptyMessage:"No Space access grants exist for this device yet. Advanced project filters cannot send data by themselves."}}function N_(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=me(n.scope_id),i=me(n.label);if(!r&&!i)return null;const a=i||"Untitled Space",s=me(n.last_applied_cursor),c=me(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=tc(me(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(m=>!!m).join(" · ");return{scopeId:r||a,label:a,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var YM=["personal","private","home","mine","me"],XM=["oss","open source","opensource","community","public"],QM=["work","client"],ZM=["local","legacy","review"];function eO(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>me(t)??"").join(" ").toLowerCase()}function tO(e){return[e.scope_id,e.label,e.kind].map(t=>me(t)??"").join(" ").toLowerCase()}function T_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Eu(e,t){const n=eO(e);return t.some(r=>{const i=T_(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function I_(e){return Eu(e,YM)||Eu(e,XM)}function nO(e){const t=tO(e);return ZM.some(n=>{const r=T_(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function rO(e){return!I_(e)&&(!nO(e)||Eu(e,QM))}function iO(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(me(e.discovered_via_group_id)||me(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(I_),r=t.some(rO);return!n||r?{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""}:{badgeLabel:"Review Space fit",detail:"Team discovery helps find the device, and advanced project filters only narrow already-authorized Spaces. Neither one grants missing work/client Space access.",isVisible:!0,message:"This Team-discovered device has personal or OSS Space access, but no separate work/client-like Space access. If this device is meant for work/client sync, grant that Space explicitly before treating sync as validated.",title:"Check this device's Space access"}}function aO(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function oO(e){const t=S_(e?.effective_include),n=S_(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${C_(t,"all projects")}`,a=`Exclude filter: ${C_(n,"no exclusions")}`,s=aO(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:a,summary:`${r}. ${i}; ${a}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function sO(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=me(n?.display_name),i=me(n?.actor_id),a=OM(r);if(!r||!i||!a)return;const s=t.get(a)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(a,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function k_(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=me(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const a=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>me(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||a.add(c)})}),{visibleActors:t.filter(s=>!a.has(me(s?.actor_id))),hiddenLocalDuplicateCount:a.size}}var cO=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),lO=new Set(["pending","verifying","waiting"]);function dO(e){return(Array.isArray(e?.groups)?e.groups.map(t=>me(t)).filter(Boolean):[]).join(", ")||"none"}function E_(e){return me(e?.projects?.[0]?.display_name)||"the shared Project"}function uO(e){const t=e?.items?.find(n=>n.state!=="active");return me(t?.canonicalProjectIdentity)||"the shared Project"}function pO(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=_i(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function mO(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&_i(n).state==="mutual-trust"&&!N_(n).rows.some(r=>r.status==="pending"))}function fO(e){return e.some(t=>me(t.status?.peer_state)==="online"&&_i(t).state==="mutual-trust")}function hO(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=me(n.status?.peer_state),i=_i(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function gO(e){if(e?.daemon_running===!1)return!0;const t=e?.daemon_state;return t!==void 0&&t!=="ok"&&t!=="offline-peers"&&t!=="stale"&&t!=="degraded"}function P_(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],a=dO(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${a}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${a}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s){const p=E_(s);return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. Exact-Project setup has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:`Open Project sharing below and retry setup for ${p}.`}}if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. Recipient access has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:"Open Sharing and use Manage projects for the affected recipient, then run Sync now again."};const l=r.find(p=>{const m=p.lifecycle?.state;return m!==void 0&&cO.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&lO.has(m)});if(l||d){const p=l?E_(l):uO(e.reconciliation??void 0),m=l?.lifecycle?.primary_action?.kind,f=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:f?"Removal pending":"Setup pending",meta:f?`Team: ${a}. Future access removal for ${p} is still pending.`:`Team: ${a}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:f?`Keep both devices online, then sync again to finish removing future access for ${p}.`:m==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:m==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(gO(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${a}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(pO(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${a}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=me(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${a}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${a}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or configure a coordinator in Advanced settings."}:hO(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${a}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&mO(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${a}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:fO(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function vO(e){return e.discovered?.stale?e.peer?Ua(e.peer)!=="connected":!0:!1}function A_(e){return{id:`repair:${e.id}`,kind:"device-needs-repair",priority:10,title:e.title||`${e.name} needs attention`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function Pu(e){return{id:`review:${e.id}:${e.key||"default"}`,kind:"review-team-device",priority:20,title:`${e.name} is available to review`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function yO(e){return{id:`name:${e.id}`,kind:"name-device",priority:30,title:`Name ${e.name}`,summary:e.summary,actionLabel:"Go to name field",deviceId:e.id}}function bO(e){const t=me(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>me(r))?e?.sync_enabled===!1?{reason:"sync_disabled",message:"Enable sync before pairing team devices."}:null:{reason:"coordinator_groups_empty",message:"Join or configure a team before pairing team devices."}:{reason:"coordinator_url_missing",message:"Configure a coordinator URL before pairing team devices."}}function _O(e,t){const n=new Map,r=i=>{const a=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,a),a};return e.forEach(i=>{const a=me(i?.peer_device_id);if(!a)return;const s=r(a);s.peer=i,s.localName=me(i?.name)}),t.forEach(i=>{const a=me(i?.device_id);if(!a)return;const s=r(a);s.discovered=i,s.coordinatorName=me(i?.display_name)}),[...n.values()]}function wO(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.coordinator?.discovered_devices)?e.coordinator.discovered_devices:[],i=_O(n,r),a=e.duplicatePersonDecisions??{},s=sO(t).filter(l=>!a[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=w_({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Ua(l.peer):"waiting",p=l.peer?_i(l.peer):null,m=me(l.discovered?.fingerprint),f=me(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(A_({id:l.deviceId,name:d,title:`${d} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."}));return}if(l.peer&&u==="needs-repair"){const g=p?.description||me(l.peer?.last_error)||"Sync needs review.";c.push(A_({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:g}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Pu({id:l.deviceId,key:"other-device-trust",name:d,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),!l.peer&&l.discovered?.stale&&c.push(Pu({id:l.deviceId,key:"stale-discovery",name:d,summary:"This device is no longer advertising fresh coordinator presence. Wait for it to check in again before connecting it here."})),!l.peer&&Array.isArray(l.discovered?.groups)&&l.discovered.groups.length>1&&c.push(Pu({id:l.deviceId,key:"ambiguous-groups",name:d,summary:"This device appears in multiple coordinator groups. Review the team setup before approving it here."})),l.peer&&KM({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(yO({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:P_({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Ua(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>vO(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var x_={actor:"person",actors:"people",actorAssignment:"person assignment",localActor:"you",peer:"device",peers:"devices",pairedLocally:"Connected on this device",discovered:"Seen on team",conflicts:"Needs review"};function Gn(e){const t=document.getElementById(e);t&&t.remove()}var R_=!1;function SO(e){R_=e}var Au=!1;function CO(e){Au=e}var xu=!1;function NO(e){xu=e}var TO=new Set,Ru=new Set,Du=new Set,D_="codemem-sync-duplicate-person-decisions";function IO(e){const t=String(e||"").trim();t&&(Ru.add(t),Du.add(t),TO.add(t))}function Lu(e){const t=String(e||"").trim();return!!t&&Ru.has(t)}function kO(e){const t=String(e||"").trim();t&&Ru.delete(t)}function EO(e){const t=String(e||"").trim();return!t||!Du.has(t)?!1:(Du.delete(t),!0)}function $u(){try{const e=localStorage.getItem(D_);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function L_(e){try{localStorage.setItem(D_,JSON.stringify(e))}catch{}}function $_(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function PO(){return $u()}function AO(e,t){const n=$_(e);if(!n)return;const r=$u();r[n]=t,L_(r)}function xO(e){const t=$_(e);if(!t)return;const n=$u();delete n[t],L_(n)}function M_(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function O_(e){const t=String(e||"");return t?M_(t):""}function RO(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function DO(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function nc(e){if(!e||typeof e!="object")return"Unknown person";const t=String(e.display_name||"").trim();return t||String(e.actor_id||"Unknown person")}function Mu(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":nc(e)}function LO(e){return(Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function $O(){return k_({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}).visibleActors}function j_(e){return $O().filter(t=>String(t?.actor_id||"")!==e)}function MO(e,t){const n=j_(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Mu(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Ou(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Ko("div","sync-action"),i=Ko("div","sync-action-text");i.textContent=n.label,i.appendChild(Ko("span","sync-action-command",n.command));const a=Ko("button","settings-button sync-action-copy","Copy");a.addEventListener("click",()=>Xi(n.command,a)),r.append(i,a),e.appendChild(r)})}}function F_(e,t){return t&&e.error_redacted===!0}function B_(){const e=document.getElementById("syncAttempts");if(!e)return;const t=_.lastSyncAttempts,n=String(_.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Nr(e,TM());return}const r=kM(n,t.slice(0,5).some(i=>i.status==="error"));RM(e,t.slice(0,5).map(i=>{const a=i.started_at||i.started_at_utc||"",s=String(i.peer_device_id||"").trim(),c=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===s):null,l=String(c?.name||"").trim()||(s?s.slice(0,8):"unknown"),d=i.status==="error",u=[],p=Zi();if(d&&i.error){const m=String(i.error);u.push(p?M_(m):m),F_(i,p)&&u.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!d&&(i.ops_in||i.ops_out)&&u.push(`${i.ops_in??0} in · ${i.ops_out??0} out`),!p&&i.address&&u.push(i.address),{status:i.status||"unknown",peerLabel:l,detail:u.join(" · "),startedAt:a?pr(a):"",...F_(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function OO(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&Nr(e,NM()),t&&Nr(t,IM()),n&&(n.textContent="Advanced diagnostics are unavailable right now. Refresh the page first. If that still fails, verify the local sync service and retry once it responds again."),Ou(r,[])}function wi(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function jO(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=wi(n.would_remove),a=wi(n.ambiguous),s=wi(r.applied),c=wi(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||a>0?`${a} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function U_(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Gn("syncDiagSkeleton");const r=_.lastSyncStatus;if(!r){Nr(e,CM()),Ou(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},a=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=a.last_ping_at||r.last_ping_at||bM(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),m=String(r.daemon_detail||""),f=String(r.daemon_state||"unknown"),g=r.retention||{},h=r.cleanup_diagnostics,v=h?.stale_peer_rows??{},w=wi(v.would_remove),b=wi(v.ambiguous),S=g.enabled===!0,C=Number(g.last_deleted_ops||0),T=g.last_run_at||null,P=String(g.last_error||""),k=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":zv(f),M=f==="disabled"||r.enabled===!1,U=Object.keys(i).length,E=!M&&U===0;if(t){const q=M?["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:E?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${k}`,`Peers: ${U}`,c?`Last sync: ${$n(ai(c))} ago`:"Last sync: never"];f==="offline-peers"&&q.push("All peers are currently offline; sync will resume automatically"),m&&f==="stopped"&&q.push(`Detail: ${m}`),m&&(f==="needs_attention"||f==="rebootstrapping")&&q.push(`Detail: ${m}`),S&&q.push(T?`Retention last ran ${$n(ai(T))} ago (approx oldest-first)`:"Retention enabled"),w>0?q.push(`${w.toLocaleString()} stale peer rows pending cleanup`):b>0&&q.push(`${b.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=q.join(" · ")}const j=M?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:E?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:k},{label:"Pending events",value:p},{label:"Last sync",value:c?`${$n(ai(c))} ago`:"never"},{label:"Last peer ping",value:l?`${$n(ai(l))} ago`:"never"},{label:"Retention",value:S?T?`${C.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!M&&!E&&(d||u)&&j.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!M&&!E&&s.seconds_since_last&&j.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!M&&!E&&a.seconds_since_last&&j.push({label:"Since last peer ping",value:`${a.seconds_since_last}s`}),!M&&S&&P&&j.push({label:P,value:"Retention"}),!M&&!E&&h&&j.push({label:"Cleanup",value:jO(h)}),xM(e,j);const O=[];E||f==="offline-peers"||(f==="stopped"?(O.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),O.push({label:"Run one sync pass now.",command:"codemem sync once"})):f==="needs_attention"?O.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?O.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="error"?(O.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),O.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!M&&!E&&p>0&&O.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!M&&b>0?O.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!M&&w>0&&O.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Ou(n,O)}var FO="syncRedactMount",BO="syncRedactLabel",G_=()=>{};function UO(e){G_=e}var ju=()=>{};function Fu(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;MM(e,{contentHost:t,open:_.syncPairingOpen,onOpenChange:r=>{if(VI(r),Fu(),r){const i=document.getElementById("pairingPayload"),a=document.getElementById("pairingHint");i&&m_(i,a,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}ju()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=_.pairingCommandRaw;r&&await Xi(r,n)})}function Bu(){Fu();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;m_(e,t,SM(_.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!_.pairingCommandRaw)}function H_(){const e=document.getElementById(FO);e&&et(e,y(ei,{"aria-labelledby":BO,checked:Zi(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{WI(t),H_(),ju(),U_(),G_(),B_(),Bu()},thumbClassName:"sync-redact-switch-thumb"}))}function GO(e){ju=e,Fu(),H_()}function HO(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function Si(e,t){e.classList.add("sync-field-error");const n=e.parentElement?.querySelector(".sync-field-hint");n&&n.remove();const r=document.createElement("div");return r.className="sync-field-hint",r.textContent=t,e.insertAdjacentElement("afterend",r),HO(e),e.addEventListener("input",()=>Ga(e),{once:!0}),!1}function Ga(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function ot(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var Tr=new Map,Uu=null,qO={operation_device_binding_missing:"The accepted device has not been linked yet.",operation_not_found:"This sharing operation is no longer available.",operation_scope_mismatch:"The invitation no longer matches the reviewed project access.",operation_state_invalid:"The invitation is no longer in a recoverable state.",reassign_capability_required:"A participating device must be updated before setup can continue."};function KO(e){return qO[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function VO(e){const t=new Map;for(const n of e){const r=n.person.actor_id;t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function WO(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Gu(e){switch(e){case"waiting_for_acceptance":return"Invitation pending";case"active":return"Sharing";case"revoking":return"Removing sharing";case"revoked":return"Previously shared";case"cancelled":return"Invitation cancelled";default:return"Sharing setup"}}function zO({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[a,s]=x(!1),[c,l]=x(()=>Tr.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;J(()=>{Uu!==e.operation_id||!d.current||(Uu=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let v=h;if(!v&&n){const b=(await n(e.operation_id)).lifecycle.primary_action;b?.kind==="copy_invite"&&(v=b.invite_link)}if(!v)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(b=>navigator.clipboard.writeText(b)))(v);const w={message:"Invite copied.",tone:"success"};Tr.set(e.operation_id,w),l(w)}catch(v){const w={message:v instanceof Error?v.message:"Invite could not be copied.",tone:"warning"};Tr.set(e.operation_id,w),l(w)}finally{s(!1)}}async function m(){s(!0);try{const h=await t(e.operation_id),v=h.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:h.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${h.lifecycle.label}.`,tone:"success"};Tr.set(e.operation_id,v),Uu=e.operation_id,l(v),await r()}catch(h){const v={message:KO(h),tone:"warning"};Tr.set(e.operation_id,v),l(v),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){const h=e.projects.map(v=>v.project_id?.trim()).filter(v=>!!v);if(h.length!==e.projects.length){const v={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};Tr.set(e.operation_id,v),l(v);return}if(!Do(h,e.person.display_name)){const v={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};Tr.set(e.operation_id,v),l(v)}}function g(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){m();return}f()}}return o("section",{"aria-label":`${Gu(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[o("div",{className:"peer-scope-summary",children:Gu(e.lifecycle.state)}),o("ul",{"aria-label":`${Gu(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,v)=>o("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${v}`))}),o("div",{className:"peer-scope-summary",children:e.lifecycle.label}),o("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?o("div",{className:"peer-actions",children:o("button",{"aria-busy":a,className:"settings-button",disabled:a,type:"button",onClick:g,children:a?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?o("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function JO({operations:e,...t}){const n=e[0].person,r=WO(e);return o("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[o("h3",{className:"device-row-name",children:n.display_name}),r.length>0?o("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>o("li",{children:i.display_name},i.device_id))}):null,e.map(i=>o(zO,{operation:i,...t},i.operation_id))]})}function YO(e){return e.operations.length===0?null:o("div",{className:"project-share-person-groups",children:VO(e.operations).map(t=>o(JO,{...e,operations:t},t[0].person.actor_id))})}function XO(e,t){et(e,o(YO,{...t}))}function q_({title:e,detail:t}){return o("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[o("strong",{children:e}),o("span",{children:t})]})}function QO(e){return e<=0?"Represents you across your own devices.":`Represents you across your own devices. ${e} unresolved duplicate ${e===1?"entry is":"entries are"} hidden until reviewed in Needs attention.`}function ZO({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const a=String(e.actor_id||""),s=nc(e),c=LO(a),l=j_(a),d=l.map(O=>String(O.actor_id||"")).join("|"),[u,p]=x(s),[m,f]=x(!1),[g,h]=x("Rename"),[v,w]=x(!1),[b,S]=x("Merge into selected person"),[C,T]=x(""),[P,k]=x(!1);J(()=>{p(s),f(!1),h("Rename"),w(!1),S("Merge into selected person"),T(""),k(!1)},[a,c,t,s,d]);const M=l.length?MO(C,a):"No other people are available yet. Create another person first if you need to merge duplicates.",U=[{label:"Merge into person",value:""},...l.map(O=>{const q=String(O.actor_id||"");return{label:O.is_local?Mu(O):nc(O),value:q}})];async function E(){const O=u.trim();if(!O)return;f(!0),h("Saving…");let q=!1;try{await n(a,O),q=!0}catch{h("Retry rename")}finally{f(!1),q&&h("Rename")}}async function j(){if(!C)return;const O=l.find(L=>String(L.actor_id||"")===C);if(!O||!await Jt({title:`Merge ${s} into ${nc(O)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;w(!0),S("Merging…");let q=!1;try{await r(C,a),q=!0}catch{S("Retry merge")}finally{w(!1),q&&S("Merge into selected person")}}return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:Mu(e)}),o("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?QO(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:o("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),o("div",{className:"actor-actions",children:e.is_local?o("div",{className:"peer-meta",children:"Rename yourself in config"}):o(Z,{children:[o(Ne,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||v,type:"text",value:u,onInput:O=>p(O.currentTarget.value),onKeyDown:O=>Wr(O,{onSubmit:()=>{E()},disabled:m||v||!u.trim()})}),o("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||v,onClick:()=>{E()},children:g}),o("button",{type:"button",className:"settings-button danger",disabled:m||v,onClick:async()=>{await Jt({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(a)},children:"Remove"}),o("button",{type:"button",className:"settings-button",disabled:m||v,onClick:()=>k(O=>!O),children:P?"Hide duplicate cleanup":"Show duplicate cleanup"}),P?o(Z,{children:[o("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),o("div",{className:"actor-merge-controls",children:[o(Ln,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:v||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:T,options:U,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:C,viewportClassName:"sync-radix-select-viewport"}),o("button",{type:"button",className:"settings-button",disabled:v||l.length===0||!C,onClick:()=>{j()},children:b})]}),o("div",{className:"peer-meta actor-merge-note",children:M})]}):null]})})]})}function ej({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?o(Z,{children:e.map(a=>{const s=String(a.actor_id||a.display_name||a.is_local||"");return o(ZO,{actor:a,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):o(q_,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function tj(e,t){et(e,o(ej,{...t}))}function nj(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function rj(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${pr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function ij({devices:e}){return o(Z,{children:rj(e)})}function aj(e){const t=String(e.origin_device_id||"").trim(),n=Number(e.memory_count||0);return{label:n>0?`${t} (${n} memories)`:t,value:t}}function oj(e){const t=nj(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),bi(e.mount),bi(e.meta);return}const n=t.map(aj),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,et(e.mount,o(Ln,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),et(e.meta,o(ij,{devices:t}))}var sj={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function cj({state:e,size:t=8,"aria-label":n}){return o("span",{"aria-label":n??sj[e],className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function Ir({feedback:e}){return e?.message?o("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function lj(){return o("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[o("title",{children:"Chevron"}),o("path",{d:"m9 18 6-6-6-6"})]})}function dj(e){switch(Ua(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var rc=null,K_=0,Hu=new Set;function V_(e){if(rc!==e){rc=e,K_+=1;for(const t of Hu)t(K_)}}function uj(){const[,e]=x(0);return J(()=>(Hu.add(e),()=>{Hu.delete(e)}),[]),rc}var pj={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function W_(e,t){if(!e)return"the selected Identity";const n=t.find(r=>r.actor_id===e);return String(n?.display_name||n?.actor_display_name||"the selected Identity")}function mj(e,t,n,r=!1,i=!1,a=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||a&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${W_(e.identityId,n)}.`,detail:"This result comes from an active identity_devices binding. Advanced actor_id values are not authoritative ownership.",actionLabel:"Review or rebind in Devices"};if(e?.state==="pairing_required")return{status:"pairing_required",summary:"Identity setup is blocked until pairing is complete.",detail:"Pairing establishes sync trust; it does not establish device ownership.",actionLabel:"Review setup in Devices"};if(e?.state==="conflicted")return{status:"conflicted",summary:"Identity ownership needs review.",detail:"Conflicting device evidence failed closed. Advanced actor_id values cannot resolve ownership.",actionLabel:"Review conflict in Devices"};const s=e?.suggestedIdentityId??t;return{status:e?.state??"unavailable",summary:s?`Suggested Identity: ${W_(s,n)}.`:"No authoritative Identity binding is configured.",detail:"sync_peers.actor_id is only a suggestion or hint until you confirm an identity_devices binding in Devices.",actionLabel:"Set up Identity in Devices"}}function fj(e){_.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function hj(e){return e?e.authorized?"Private same-person sync is limited to your personal Space. Team and org Spaces do not carry your private memories.":"Private same-person sync is blocked until this device is granted an allowed personal Space.":"Private same-person sync is limited to an allowed personal Space; team or org Spaces do not carry your private memories."}function gj(){window.location.hash="coordinator-admin"}function qu(e=_.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function vj({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),a=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||a,c=_i(e),l=pj[VM(e)],d=e.status||{},u=JM(e),p=Lu(i),m=p&&u.total===0,f=iO(e),g=zM(e),h=N_(e),v=oO(e.project_scope||{}),w=RO(e.addresses),b=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(W=>String(W)))):[],S=Number(e.address_count??0),C=Number.isFinite(S)&&S>0?S:0,T=b.length?b.map(W=>Zi()?O_(W):W).join(" · "):C>0?`${C} ${C===1?"address":"addresses"} hidden`:"No addresses",P=_.lastDeviceIdentityInventory?.items.find(W=>W.deviceId===i||W.evidenceDeviceIds.includes(i)),k=mj(P,String(e.actor_id||"")||null,_.lastSyncActors,_.deviceIdentityInventoryLoadError,_.lastDeviceIdentityInventory?.truncated===!0,_.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),M=String(d.last_sync_at||d.last_sync_at_utc||""),U=String(d.last_ping_at||d.last_ping_at_utc||""),E=e.discovered_via_group_id?`Discovery: seen through Team ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,j=EO(i),O=B(null),[q,L]=x(a),[R,A]=x(()=>_.syncPeerFeedbackById.get(i)??null),[I,D]=x(!1),[F,K]=x("Save name"),[ce,ie]=x(!1),[re,ye]=x(!1),[Y,he]=x("Remove device");J(()=>{p&&u.total>0&&kO(i)},[u.total,i,p]),J(()=>{L(a),A(_.syncPeerFeedbackById.get(i)??null),D(!1),K("Save name"),ie(!1),ye(!1),he("Remove device")},[a,e.actor_id,i]),J(()=>{!j||!O.current||queueMicrotask(()=>O.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[j]);async function ne(){if(!i)return;const W=q.trim();if(!W){const be={message:"Enter a friendly name for this device.",tone:"warning"};A(be),_.syncPeerFeedbackById.set(i,be),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}D(!0),K("Saving…");try{const be=await n(i,W);A(be),_.syncPeerFeedbackById.set(i,be),K("Save name")}catch{K("Retry")}finally{D(!1)}}async function ke(){if(m){const W=qu();if(!await Jt({title:`Sync ${a} before advanced rule review?`,description:W?"This manual sync will use the current Space access and advanced filters until you review them in Teams.":"This manual sync will use the current Space access and advanced filters until a coordinator or manager reviews them in Teams.",confirmLabel:"Sync anyway",cancelLabel:W?"Review in Teams first":"Cancel"}))return}ie(!0);try{const W=await r(e,w);A(W),W&&_.syncPeerFeedbackById.set(i,W)}finally{ie(!1)}}async function ge(){if(!i||!await Jt({title:`Remove device ${s}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;ye(!0),he("Removing…");let W=!1;try{await t(i,s),W=!0}catch{he("Retry remove")}finally{ye(!1),W&&he("Remove device")}}const ae=uj()===i&&i!=="",xe=`device-drawer-${i||"unknown"}`,de=dj(e),Te=M?`Sync: ${pr(M)}`:"Sync: never",ue=qu(),z=`${ae?"Collapse":"Expand"} device ${a}`;return o(zo,{asChild:!0,open:ae,onOpenChange:W=>{W?V_(i):rc===i&&V_(null)},children:o("div",{ref:O,className:"peer-card","data-peer-device-id":i||void 0,children:[o(eg,{asChild:!0,children:o("button",{"aria-label":z,className:"device-row-head device-row-head--trigger",type:"button",children:[o(cj,{state:de}),o("span",{className:"device-row-name",title:i||void 0,children:a}),l?o("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,o("span",{className:"device-row-chips",children:[o("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),m?o("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,o("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),g.badgeLabel?o("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:g.badgeLabel}):null,f.badgeLabel?o("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:f.badgeLabel}):null,e.discovered_via_group_id?o("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),o("span",{className:"device-row-meta",children:Te}),o("span",{"aria-hidden":"true",className:"device-row-chevron",children:o(lj,{})})]})}),o(Jo,{"aria-label":`Device actions for ${a}`,className:"device-row-drawer",id:xe,children:[o("div",{className:"peer-actions",children:[o("button",{type:"button",className:"settings-button",disabled:ce,onClick:()=>{ke()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:ce?"Syncing…":"Sync now"}),o("div",{className:"sync-labeled-field",children:[o("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),o(Ne,{"aria-label":`Friendly name for ${a}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:I,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:q,onInput:W=>L(W.currentTarget.value)})]}),o("button",{type:"button",className:"settings-button",disabled:I,onClick:()=>{ne()},children:F}),o("button",{type:"button",className:"settings-button danger",disabled:re,onClick:()=>{ge()},children:Y})]}),o("div",{className:"peer-scope",children:[j?o("div",{className:"peer-meta",children:ue?"Review this device's Space access and advanced rules in Teams if the defaults are too broad.":"A coordinator or manager can review this device's Space access and advanced rules in Teams if the defaults are too broad."}):m?o("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,o("div",{className:"peer-scope-summary",children:"Device details"}),o("div",{className:"peer-addresses",children:T}),E?o("div",{className:"peer-meta",children:E}):null,o("div",{className:"peer-meta",children:[M?`Sync: ${pr(M)}`:"Sync: never",U?`Ping: ${pr(U)}`:"Ping: never"].join(" · ")}),o("div",{className:"peer-scope-summary",children:"Space access"}),o("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?o("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(W=>o("li",{className:"peer-scope-chip",title:W.detail,children:W.label},W.scopeId))}):null,f.isVisible?o("div",{className:"settings-note",role:"status",children:[o("strong",{children:f.title}),o("div",{children:f.message}),o("div",{children:f.detail})]}):null,o("div",{className:"peer-meta",children:v.note}),o("div",{className:"peer-scope-summary",children:"Space sync progress"}),o("div",{className:"peer-meta",children:h.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":h.emptyMessage}),h.rows.length>0?o("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:h.rows.map(W=>o("li",{title:W.detail,children:[o("span",{className:"peer-scope-rejection-label",children:W.label}),o("span",{className:`badge ${W.status==="received"?"badge-online":"actor-badge"}`,children:W.badgeLabel})]},W.scopeId))}):null,g.total>0?o("div",{className:"peer-scope-rejections","data-peer-rejection-count":g.total,children:[o("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),o("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),o("ul",{className:"peer-scope-rejections-list",children:g.reasons.map(W=>o("li",{children:[o("span",{className:"peer-scope-rejection-label",children:W.label}),o("span",{className:"peer-scope-rejection-count",children:W.count.toLocaleString()})]},W.reason))}),g.lastAt?o("div",{className:"peer-meta",children:["Last rejected ",pr(g.lastAt)]}):null]}):null,o("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),o("div",{className:"peer-meta",children:k.summary}),o("div",{className:"peer-meta",children:k.detail}),e.claimed_local_actor?o("div",{className:"peer-meta",children:hj(e.claimed_local_actor_scope)}):null,o("div",{className:"peer-actor-row",children:o("button",{type:"button",className:"settings-button",onClick:()=>fj(P?.deviceId??i),children:k.actionLabel})}),o("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),o("div",{className:"peer-meta",children:[v.statusLabel,". ",v.summary," ",v.note]}),ue?o("div",{className:"peer-actions",children:o("button",{type:"button",className:"settings-button",onClick:gj,children:"Manage Spaces in Teams"})}):o("div",{className:"peer-meta",children:"Space access is managed in Teams by a coordinator or manager."}),o(Ir,{feedback:R})]})]})]})})}function yj(e){const t=_.syncPeersSectionFeedback,n=_.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?o(Z,{children:[o(Ir,{feedback:t}),e.peers.map(i=>{const a=String(i.peer_device_id||i.name||"unknown-peer");return o(vj,{peer:i,...e},a)})]}):o(Z,{children:[o(Ir,{feedback:t}),o(q_,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function bj(e,t){et(e,o(yj,{...t}))}var Hn=async()=>{},ic="";function Ku(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function _j(e){Hn=e}function wj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Gn("syncActorsSkeleton"),Ku(!1);const n=k_({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),tj(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,a)=>{await WS(i,a),await Hn()},onMerge:async(i,a)=>{try{await qp(i,a),oe("People combined. Assigned devices moved to the selected person."),await Hn()}catch(s){throw oe(ot(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await zS(i),oe("Person removed. Assigned devices have been unassigned."),await Hn()}catch(a){throw oe(ot(a,"Failed to remove person."),"warning"),a}}})}function Sj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Ku(!0),t&&(t.textContent="People controls are temporarily unavailable. Refresh this page to retry. Device status and sync health are still available below while this recovers."),e&&Nr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function Cj(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;XO(e,{operations:_.lastShareOperations,onAdvance:n=>OS(n),onLoadOperation:n=>MS(n),onReload:Hn});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=_.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":_.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function Vu(){const e=document.getElementById("syncPeers");if(!e)return;Gn("syncPeersSkeleton");const t=_.lastSyncPeers,n=Array.isArray(t)?t:[];DO(_.syncPeersSectionFeedback,n)&&(_.syncPeersSectionFeedback=null),bj(e,{peers:n,onRename:async(r,i)=>{try{return await Ap(r,i),await Hn(),{message:"Device name saved.",tone:"success"}}catch(a){return{message:ot(a,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const a=String(r?.peer_device_id||""),s=b_(await Cc({address:i,peerDeviceId:a||void 0}));let c;s.ok?a&&Lu(a)?c={message:`Triggered sync for ${r?.name||(a?a.slice(0,8):"unknown")}. ${qu()?"Review Space access and advanced rules in Teams if this device needs tighter sharing.":"A coordinator or manager can review Space access and advanced rules in Teams if this device needs tighter sharing."}`,tone:"warning"}:c={message:s.message,tone:"success"}:c={message:s.message,tone:"warning"};try{await Hn()}catch{c={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return c}catch(a){return{message:ot(a,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Pp(r);const a={message:`Removed peer ${i}.`,tone:"success"};return _.syncPeerFeedbackById.delete(r),_.syncPeersSectionFeedback={...a,relatedPeerDeviceId:r},await Hn(),a}catch(a){return{message:ot(a,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function Nj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Ku(!0),t&&(t.textContent="People and device details are unavailable right now. Refresh this page to retry once local sync status is reachable again."),e&&Nr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. Named people will reload here once the local sync status endpoint responds again."}),n&&Nr(n,{title:"Devices unavailable right now.",detail:"Refresh this page to retry. When sync is reachable again, paired devices will reload here so you can rename, inspect, or re-pair them."})}function z_(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||oj({devices:Array.isArray(_.lastSyncLegacyDevices)?_.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==ic&&(ic=r,z_())},panel:e,value:ic})}function Tj(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Wr(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){Si(n,"Enter a name for the person.");return}Ga(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await VS(i),oe("Person created."),n.value="",await e()}catch(a){oe(ot(a,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(ic||"").trim();if(!i||!r||!await Jt({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const a=r.textContent||"Attach device history";r.textContent="Attaching…";try{await JS(i),oe("Old device history attached to you."),await e()}catch(s){oe(ot(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=a,r.disabled=!1})}function Ij(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function Wu(e=Ij()){const t=document.getElementById("syncMainView"),n=document.getElementById("syncDiagnosticsView");!t||!n||(e==="diagnostics"?(t.hidden=!0,n.hidden=!1):(t.hidden=!1,n.hidden=!0))}var J_=!1;function kj(){J_||(J_=!0,window.addEventListener("hashchange",()=>{Wu()}))}var Zt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function Ej(e){Zt.loadSyncData=e}var Pj=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function Aj(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=_.lastCoordinatorAdminStatus?.readiness,r=String(_.lastCoordinatorAdminStatus?.active_group||"").trim();if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent=r?`Teams is ready for ${r}. Advanced admin tools now live in Teams.`:"Teams is ready. Advanced admin tools now live in Teams.";return}const i=n==="partial"?"Finish Teams setup before creating remote invites. Use Teams to check what is missing.":"Configure a coordinator URL, Team, and admin secret before creating remote invites. Use Teams to finish setup.";e.disabled=!0,t.hidden=!1,t.textContent=i}function zu(){const e=document.getElementById("syncAdminDisclosureMount");e&&$M(e,{open:R_,onOpenChange:t=>{SO(t),zu(),oc(),Ju()}})}function xj(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function Ju(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(_.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function ac(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=_.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function oc(){const e=document.getElementById("syncInvitePolicyMount");e&&et(e,y(Ln,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==Zt.invitePolicy&&(Zt.invitePolicy=n,oc())},options:Pj,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:Zt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function Rj(e,t){zu(),oc();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),a=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),m=document.getElementById("syncProjectInviteReviewHeading"),f=document.getElementById("syncRecipientName"),g=document.getElementById("syncRecipientDeviceName");let h="",v=0;r?.addEventListener("click",()=>{Do()||oe("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(b,S)=>{if(!u||!f||!g)return"other";const C=await Ep(b);if(S!==v||d?.value.trim()!==b)return"stale";if(C.kind!=="project_share_invite")return"other";const T=(C.projects??[]).map(P=>`${P.display_name} (${P.existing_memory_count} existing ${P.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${C.inviter_name||"A teammate"} invited you${C.team_name?` through ${C.team_name}`:""} to share ${T||"selected projects"}.`),f.value=Ur(C.recipient_name),g.value=Ur(C.device_name),u.hidden=!1,h=b,l&&(l.textContent="Accept and start syncing"),m?.focus(),"project"};d?.addEventListener("input",()=>{v+=1,d.value.trim()!==h&&(h="",u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!a||!s||!c||i.disabled)return;const b=a.value.trim(),S=Number(s.value);let C=!0;if(b?Ga(a):C=Si(a,"Team name is required."),!S||S<1?C=Si(s,"Must be at least 1 hour."):Ga(s),!!C){i.disabled=!0,i.textContent="Creating…";try{const T=await Tp({group_id:b,policy:Zt.invitePolicy,ttl_hours:S||24});_.lastTeamInvite=T,Ju(),c.value=String(T.encoded||""),c.hidden=!1,c.focus(),c.select();const P=Array.isArray(T.warnings)?T.warnings:[];oe(P.length?`Invite created. Copy it above and review ${P.length===1?"1 warning":`${P.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",P.length?"warning":"success")}catch(T){oe(ot(T,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",b=>{Wr(b,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const b=d.value.trim();if(!b){Si(d,"Paste a team invite or pairing payload.");return}if(Ga(d),h!==b){const C=v;try{const T=await w(b,C);if(T==="project"||T==="stale")return}catch{}if(C!==v||d.value.trim()!==b)return;h=b,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(S){const C=T=>Ur(T)==="";if(C(S.recipient_name)){f&&Si(f,"Enter a human-readable name using 120 characters or fewer.");return}if(C(S.device_name)){g&&Si(g,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const C=await yc(b,S);_.lastTeamJoin=C;const T=C,P=typeof T.type=="string"?T.type:"team_join";let k;if(P==="pair"){const M=String(C.peer_device_id??"").trim();k={message:M?`Paired with device ${M.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(P==="project_share"){const M=T.restart_required===!0||T.setup_state==="pending_inviter"||C.status==="pending_setup",U=typeof T.detail=="string"?T.detail.trim():"";k=M?{message:U||(T.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":T.setup_state==="pending_inviter"?"Project invitation accepted. Waiting for the inviter to finish setup.":"Project invitation accepted. Setup is still pending."),tone:"warning"}:{message:"Project invitation accepted.",tone:"success"}}else k={message:C.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};_.syncJoinFlowFeedback=k,ac(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(M){k={message:ot(M,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=k,ac()}}catch(C){_.syncJoinFlowFeedback={message:ot(C,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},ac(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const b=b_(await Cc());oe(b.message,b.warning?"warning":void 0)}catch(b){oe(ot(b,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function Yu({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(null);return bt(()=>{e&&(e.hidden=t)},[e,t]),bt(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),o("div",{ref:r})}function Dj({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return o(Z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Invite a teammate.",o("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?o(Yu,{element:e,hidden:!t,restoreParent:n}):null]})}function Lj(){return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Pair another device.",o("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),o("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>Xi("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function $j({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return o(Z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Accept an invite or pairing.",o("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?o(Yu,{element:e,hidden:!t,restoreParent:n}):null]})}function Mj({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return o(Z,{children:[u?o(Z,{children:[o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["Join this device.",o("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?o(Yu,{element:r,hidden:!1,restoreParent:a}):null,o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["This device is not on the team yet.",o("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):o(Z,{children:[o($j,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggle:c}),o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:o(Dj,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?o(Lj,{}):null]})}function sc({count:e,label:t}){return o("div",{className:"sync-section-heading",children:[o("div",{className:"sync-action-text sync-section-label",children:t}),e?o("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function cc({children:e}){return o("div",{className:"section-meta sync-section-note",children:e})}function Oj({item:e,onAction:t}){const[n,r]=x(!1);return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:[e.title,o("span",{className:"sync-action-command",children:e.summary})]}),o("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function jj({request:e,onApprove:t,onDeny:n}){const[r,i]=x(null),[a,s]=x(null),[c,l]=x("Approve"),[d,u]=x("Deny");return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:o("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),o("div",{className:"actor-actions",children:[o("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),o("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),o(Ir,{feedback:a})]})}function Fj({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,a]=x(null),[s,c]=x(null),l=e.actionLabel||"Pair with this device",[d,u]=x(l),[p,m]=x("Remove broken device record");return o("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[o("div",{className:"peer-title",children:[o("strong",{title:e.displayTitle||void 0,children:e.displayName}),o("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),o("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?o("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),o("div",{className:"peer-meta",children:e.note}),o("div",{className:"peer-actions",children:[e.mode==="accept"?o("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const f=await r(e)||null;c(f),u(f?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{a(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?o("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?o("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?o(Z,{children:[o("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),o("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("remove"),m("Removing…");try{c(await n(e)||null),m("Remove broken device record")}catch{m("Retry")}finally{a(null)}},children:p})]}):null]}),o(Ir,{feedback:s})]})}function Bj(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return o(Z,{children:[r?o(sc,{label:"Needs attention"}):null,r?o(cc,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?o("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:o("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,o("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>o(Oj,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function Uj({children:e}){return e?o(Z,{children:[o(sc,{label:"Add devices & teammates"}),o(cc,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function Gj({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!_.syncDiscoveredFeedback?null:cn(o(Z,{children:[o(sc,{count:t.length||void 0,label:"Devices waiting for review"}),o(cc,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),o(Ir,{feedback:_.syncDiscoveredFeedback}),t.map(a=>o(Fj,{row:a,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${a.deviceId}:${a.incomingRequestId}:${a.fingerprint}`))]}),e)}function Hj({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:cn(o(Z,{children:[o(sc,{count:t.length||void 0,label:"Join requests to review"}),o(cc,{children:"Approve or deny requests here before those devices become part of the team."}),o(Ir,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>o(jj,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function Y_(e){return o(Z,{children:[o(Bj,{...e}),o(Uj,{children:e.children}),o(Hj,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),o(Gj,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function X_(e){e&&(e.textContent="")}function lc(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function qj(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ha(){return qj()?"auto":"smooth"}var Xu="syncTeamActionsMount",Kj="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function Vj(e,t,n=!1){return e.length>1&&(!t||n)}function Wj(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function zj(e,t){const n=document.createElement("div");n.id=Xu,e.appendChild(n),et(n,y(Y_,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function Q_(e,t){const n=document.getElementById(Xu);n&&(bi(n),n.remove()),X_(e),t.forEach(r=>{X_(r)})}function qa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;zu(),oc(),Ju(),ac(),Aj();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),a=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Gn("syncTeamSkeleton"),xj();const p=_.lastSyncCoordinator,m=_.lastSyncViewModel||{primaryStatus:P_({status:_.lastSyncStatus,coordinator:p,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=A=>{if(A.kind==="possible-duplicate-person"){const K=document.getElementById("syncActorsList");K instanceof HTMLElement&&(K.scrollIntoView({block:"center",behavior:Ha()}),lc(K));return}const I=String(A.deviceId||"").trim();if(!I)return;if(A.kind==="name-device"){const K=document.querySelector(`[data-device-name-input="${CSS.escape(I)}"]`);if(K instanceof HTMLInputElement){K.scrollIntoView({block:"center",behavior:Ha()}),K.focus(),K.select(),lc(K);return}}const D=document.querySelector(`[data-peer-device-id="${CSS.escape(I)}"]`);if(D instanceof HTMLElement){D.scrollIntoView({block:"center",behavior:Ha()}),lc(D);return}const F=document.querySelector(`[data-discovered-device-id="${CSS.escape(I)}"]`);F instanceof HTMLElement&&(F.scrollIntoView({block:"center",behavior:Ha()}),lc(F))},g=async A=>{const I=Array.isArray(A.actorIds)?A.actorIds.map(ie=>String(ie||"").trim()).filter(Boolean):[],D=(Array.isArray(_.lastSyncActors)?_.lastSyncActors:[]).filter(ie=>I.includes(String(ie?.actor_id||"").trim()));if(D.length<2){oe("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const F=await cA({title:"Review possible duplicate people",summary:A.title.replace(/^Possible duplicate person:\s*/,""),actors:D.map(ie=>({actorId:String(ie?.actor_id||""),label:String(ie?.display_name||ie?.actor_id||"Unknown person"),isLocal:!!ie?.is_local}))});if(F.action==="different-people"){AO(I,"different-people"),oe("Okay. I will keep these people separate on this device."),await Zt.loadSyncData();return}if(F.action!=="merge")return;const K=D.find(ie=>String(ie?.actor_id||"")===F.primaryActorId),ce=D.find(ie=>String(ie?.actor_id||"")===F.secondaryActorId);if(!K?.actor_id||!ce?.actor_id){oe("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await qp(String(K.actor_id),String(ce.actor_id)),xO(I),oe(`Combined duplicate people into ${String(K.display_name||K.actor_id)}.`),await Zt.loadSyncData()}catch(ie){try{await Zt.loadSyncData()}catch{}oe(ot(ie,"Failed to combine these people."),"warning")}},h=async A=>await pd({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:A,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:I=>I.trim()?null:"Enter a device name to pair this device."}),v=!!p?.configured,w=bO(p);e.title=v?String(p.coordinator_url||"").trim():"";const b=document.getElementById("syncOnlineBadge");if(b?Wj(b,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!v){Q_(n,[c,u]),t.hidden=!1,n.hidden=!1,zj(n,m.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const S=String(p.presence_status||""),C=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],T=Array.isArray(m.attentionItems)?m.attentionItems:[],P=Array.isArray(p.discovered_devices)?p.discovered_devices:[],k=String(p.coordinator_url||"").trim(),M=P.map(A=>{const I=String(A.device_id||"").trim(),D=w_({coordinatorName:String(A.display_name||"").trim(),deviceId:I})||"Discovered device",F=I&&D!==I?I:null,K=String(A.fingerprint||"").trim(),ce=String(A.incoming_reciprocal_request_id||"").trim(),ie=Array.isArray(A.groups)?A.groups.map(Ce=>String(Ce||"").trim()).filter(Boolean):[],re=C.find(Ce=>String(Ce?.peer_device_id||"")===I),ye=Vj(ie,!!re,A.needs_local_approval===!0),Y=y_({device:A,pairedLocally:!!re}),he=String(re?.fingerprint||"").trim(),ne=!!re&&!!K&&!!he&&he!==K,ke=_.pendingCoordinatorApprovalsByDeviceId.get(I),ge=A.needs_local_approval===!0&&ke?.coordinatorUrl===k&&ke?.incomingRequestId===ce,ae=ge?"approval-pending":A.needs_local_approval===!0?"needs-local-approval":"not-required",xe=!ge&&!w&&BM({device:A,hasAmbiguousCoordinatorGroup:ye,pairedLocally:!!re}),de=Array.isArray(A.addresses)?A.addresses:[],Te=Number(A.address_count??0),ue=Number.isFinite(Te)&&Te>0?Te:0,z=[de.length?de.map(Ce=>Zi()?O_(String(Ce||"")):String(Ce||"")).filter(Boolean).join(" · "):ue>0?`${ue} ${A.stale?"last-known":"fresh"} ${ue===1?"address":"addresses"} hidden`:"No fresh addresses"];!de.length&&F&&z.push(`device id: ${I}`);let G=null,W=xe?"accept":"none",be=null;return ne?W="conflict":ge?(G="Waiting for refreshed coordinator status. You do not need to approve again.",W="approval-pending"):w&&(!re||Y.state==="needs-your-approval")?(G=w.message,W="setup-blocked"):ye?(G="This device appears in multiple coordinator groups. Review the Team setup before approving it here.",W="ambiguous"):re&&Lu(I)?(G="Review this device's Space access and advanced rules in Teams before you sync it.",W="scope-pending"):re?.last_error?(z.push(`error: ${String(re.last_error)}`),xe||(W="paired")):re?.status?.peer_state?(z.push(`status: ${String(re.status.peer_state)}`),xe||(W="paired")):!re&&A.stale?(G="Wait for a fresh coordinator presence update, then review this device again here.",W="stale"):re&&!xe&&(W="paired"),W==="paired"&&(be=Y.state==="waiting-for-other-device"?Y.description||"Waiting on the other device.":String(re?.last_error||"").toLowerCase().includes("401")&&String(re?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:G,actionLabel:Y.actionLabel||(re?"Review device":"Pair with this device"),approvalBadgeLabel:ge?"Approval sent":Y.badgeLabel,approvalState:ae,availabilityLabel:A.stale?"Offline":"Available",connectionLabel:ne?x_.conflicts:re?x_.pairedLocally:"Not connected on this device",coordinatorUrl:k,deviceId:I,displayName:D,displayTitle:F,fingerprint:K,groupId:ie[0]??"",incomingRequestId:ce,mode:W,note:z.join(" · "),pairedMessage:be}}),U=new Set(M.filter(A=>A.approvalState==="approval-pending").map(A=>A.deviceId)),E=T.filter(A=>!A.deviceId||!U.has(A.deviceId)),j=[],O=M.filter(A=>A.mode!=="paired"&&A.mode!=="none"&&A.mode!=="scope-pending"),q=M.filter(A=>A.mode==="accept"||A.mode==="scope-pending").length,L=E.length+j.length+q;l&&(l.hidden=O.length===0&&!_.syncDiscoveredFeedback),d&&(d.textContent=O.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=j.length===0&&!_.syncJoinRequestsFeedback),Q_(n,[c,u]);const R=document.createElement("div");R.id=Xu,n.appendChild(R),et(R,y(Y_,{actionItems:E,actionableCount:L,children:y(Mj,{invitePanel:r,invitePanelOpen:Au,inviteRestoreParent:i,joinPanel:a,joinPanelOpen:xu,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(CO(!Au),qa())},onToggleJoinPanel:()=>{a&&(NO(!xu),qa())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:O,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async A=>{if(A.kind==="possible-duplicate-person"){await g(A);return}f(A)},onDenyJoinRequest:async()=>null,onInspectConflict:A=>{const I=document.querySelector(`[data-peer-device-id="${CSS.escape(A.deviceId)}"]`);if(I instanceof HTMLElement){I.scrollIntoView({block:"center",behavior:Ha()}),oe(`Opened the conflicting local device record for ${A.displayName}.`,"warning");return}oe("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async A=>{if(!await Jt({title:`Remove ${A.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Pp(A.deviceId);const I={message:`Removed the broken local device record for ${A.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return _.syncDiscoveredFeedback=I,await Zt.loadSyncData(),I}catch(I){return{message:ot(I,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async A=>{try{const I=await h(A.displayName);return I?await Jj(A,I):null}catch(I){return{message:ot(I,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:j,presenceStatus:S,primaryStatus:m.primaryStatus}))}async function Jj(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),a=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!a||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await uS(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:a||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&_.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s}),_.pendingAcceptedSyncPeers=[...Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(u=>String(u?.peer_device_id||"").trim()!==e.deviceId):[],{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],IO(e.deviceId);let d=n?{message:Kj,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};_.syncDiscoveredFeedback=d,n&&qa();try{t.trim()!==l.trim()&&(await Ap(e.deviceId,t.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(u=>String(u?.peer_device_id||"").trim()===e.deviceId?{...u,name:t.trim()}:u),n||(d={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(u){d={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ot(u,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=d;try{await Zt.loadSyncData()}catch(u){d={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ot(u,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=d}return d}function Yj(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function Ci(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function Z_(e){return Ci(e)?"Unclear project identity":e.displayProject}function At(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function Xj(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function Qj(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zj(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function e1(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function t1(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function n1(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function r1({group:e}){const t=e.memorySamples??[],n=t.length;return o("details",{className:"legacy-review-samples",children:[o("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),o("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?o("ul",{className:"legacy-review-sample-list",children:t.map(r=>o("li",{className:"legacy-review-sample",children:[o("div",{className:"legacy-review-sample-title",children:r.title}),o("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",t1(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?o("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,o("div",{className:"legacy-review-group-meta mono",children:n1(r)})]},r.id))}):o("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function ew(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${Qj(t)}\\b`,"g"),Zj(t,n))),r}function i1(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function a1({item:e,onReview:t}){return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:e.peerName}),o("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),o("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function o1({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],a=Object.fromEntries(r.map(I=>[I.workspaceIdentity,I.suggestedScopeId??""])),[s,c]=x({}),[l,d]=x({}),[u,p]=x(a),[m,f]=x({}),[g,h]=x("all"),[v,w]=x(""),[b,S]=x(null),C=r.length,T=e.totalGroupCount??C,P=r.filter(Ci).length,k=r.filter(I=>I.suggestedScopeId&&!Ci(I)&&At(I)).length,M=r.filter(I=>m[I.workspaceIdentity]&&At(I)).length,U=r.filter(I=>m[I.workspaceIdentity]&&At(I)&&!!u[I.workspaceIdentity]).length,E=r.filter(I=>{const D=Ci(I);return g==="suggested"&&(!I.suggestedScopeId||D)||g==="cleanup"&&!D||g==="no-suggestion"&&(I.suggestedScopeId||D)||g==="selected"&&!m[I.workspaceIdentity]?!1:!v.trim()||i1(I,i).includes(v.trim().toLowerCase())});async function j(I){const D=u[I.workspaceIdentity]||I.suggestedScopeId||"";if(!(!D||!t||b)){S(I.workspaceIdentity),d(F=>{const K={...F};return delete K[I.workspaceIdentity],K});try{const F=await t(I,D,!!s[I.workspaceIdentity],s[I.workspaceIdentity]?.confirmation_token);c(F?K=>({...K,[I.workspaceIdentity]:F}):K=>{const ce={...K};return delete ce[I.workspaceIdentity],ce})}catch(F){d(K=>({...K,[I.workspaceIdentity]:ew(F,D,i)}))}finally{S(null)}}}function O(I,D){p(F=>({...F,[I.workspaceIdentity]:D})),c(F=>{const K={...F};return delete K[I.workspaceIdentity],K}),d(F=>{const K={...F};return delete K[I.workspaceIdentity],K})}function q(I,D){f(F=>({...F,[I.workspaceIdentity]:D}))}function L(I){f(D=>({...D,...Object.fromEntries(E.filter(At).map(F=>[F.workspaceIdentity,I]))}))}function R(){f(I=>({...I,...Object.fromEntries(r.filter(D=>D.suggestedScopeId&&!Ci(D)&&At(D)).map(D=>[D.workspaceIdentity,!0]))}))}async function A(){if(!t||b||U===0)return;const I=r.filter(D=>m[D.workspaceIdentity]&&At(D)&&!!u[D.workspaceIdentity]);if(!I.every(D=>s[D.workspaceIdentity])){S("bulk");try{for(const D of I){if(s[D.workspaceIdentity])continue;const F=u[D.workspaceIdentity]||D.suggestedScopeId||"";if(F)try{const K=await t(D,F,!1);d(ce=>{const ie={...ce};return delete ie[D.workspaceIdentity],ie}),K&&c(ce=>({...ce,[D.workspaceIdentity]:K}))}catch(K){d(ce=>({...ce,[D.workspaceIdentity]:ew(K,F,i)}))}}}finally{S(null)}}}return o("div",{className:"legacy-review-card",children:[o("div",{className:"legacy-review-header",children:[o("div",{children:[o("div",{className:"actor-title",children:[o("strong",{children:"Legacy shared review"}),o("span",{className:"badge badge-offline",children:"Needs project review"})]}),o("div",{className:"peer-meta legacy-review-summary",children:[T.toLocaleString()," older"," ",T===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",C<T?` Showing ${C.toLocaleString()} projects; open Projects to review the rest.`:""]}),o("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),o("div",{className:"legacy-review-toolbar",children:[o("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${C.toLocaleString()}`],["suggested",`Suggested ${k.toLocaleString()}`],["cleanup",`Needs cleanup ${P.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${U.toLocaleString()}`]].map(([I,D])=>o("button",{className:g===I?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(I),type:"button",children:D},I))}),o("div",{className:"legacy-review-bulk-row",children:[o("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:I=>w(I.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),o("button",{className:"settings-button",onClick:()=>L(!0),type:"button",children:"Select visible"}),o("button",{className:"settings-button",onClick:R,type:"button",children:"Select suggested"}),o("button",{className:"settings-button",onClick:()=>L(!1),type:"button",children:"Clear visible"}),t&&i.length>0?o("button",{className:"settings-save",disabled:b!=null||U===0||r.filter(I=>m[I.workspaceIdentity]&&At(I)&&!!u[I.workspaceIdentity]).every(I=>s[I.workspaceIdentity]),onClick:()=>{A()},type:"button",children:b==="bulk"?"Previewing…":`Preview ${U.toLocaleString()} selected`}):t&&M>0?o("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,U>0&&r.filter(I=>m[I.workspaceIdentity]&&At(I)&&!!u[I.workspaceIdentity]).every(I=>s[I.workspaceIdentity])?o("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?o("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:E.map(I=>o("li",{className:"legacy-review-group",children:[o("div",{className:"legacy-review-group-main",children:[o("div",{className:"legacy-review-title-wrap",children:[o("input",{"aria-label":`Select ${Z_(I)}`,checked:!!m[I.workspaceIdentity],className:"cm-checkbox",disabled:!At(I),onChange:D=>q(I,D.currentTarget.checked),type:"checkbox"}),o("div",{children:[o("div",{className:"legacy-review-group-title",children:Z_(I)}),o("div",{className:"legacy-review-group-meta",children:[Yj(I.identitySource),Xj(I,i)]}),At(I)?I.peerOwnedMemoryCount?o("div",{className:"legacy-review-cleanup-note",children:[(I.reassignableMemoryCount??I.memoryCount).toLocaleString()," ","local memor",(I.reassignableMemoryCount??I.memoryCount)===1?"y":"ies"," ","can be reassigned; ",I.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",I.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:o("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),Ci(I)?o("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),o("span",{className:"legacy-review-count",children:[I.memoryCount.toLocaleString()," memor",I.memoryCount===1?"y":"ies"]})]}),I.suggestionReason?o("div",{className:"legacy-review-reason",children:I.suggestionReason}):null,l[I.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:l[I.workspaceIdentity]}):null,s[I.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:[s[I.workspaceIdentity].warning," This will reassign"," ",s[I.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[I.workspaceIdentity].memory_count.toLocaleString()," memories",s[I.workspaceIdentity].skipped_memory_count?`; ${s[I.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,o(r1,{group:I}),i.length>0&&t&&At(I)?o("label",{className:"legacy-review-target",children:[o("span",{children:"Destination Space"}),o("select",{className:"peer-scope-input",disabled:b!=null,onChange:D=>O(I,D.currentTarget.value),value:u[I.workspaceIdentity]||"",children:[o("option",{value:"",children:"Choose Space…"}),i.map(D=>o("option",{value:D.scopeId,children:[D.label," · ",e1(D.authorityType),D.scopeId===I.suggestedScopeId?" · suggested":""]},D.scopeId))]})]}):null,i.length>0&&t&&At(I)?o("div",{className:"legacy-review-actions",children:o("button",{type:"button",className:"settings-button",disabled:b!=null||!u[I.workspaceIdentity],onClick:()=>{j(I)},children:b===I.workspaceIdentity?s[I.workspaceIdentity]?"Reassigning…":"Previewing…":s[I.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},I.workspaceIdentity))}):null]})}function s1({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return o(Z,{children:[t?o(o1,{item:t,onReassign:n,onReview:r??i}):null,e.map(a=>o(a1,{item:a,onReview:i},`${a.peerName}:${a.actorId}:${a.scopeLabel}`))]})}function c1(){Ah("mine"),_.feedQuery="",window.location.hash="feed"}function l1(){window.location.hash="projects"}async function d1(e,t,n,r){try{const i=await HS({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.lastSyncLegacySharedReview=i.legacy_shared_review??null,oe(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),tw(),null}catch(i){if(i instanceof Rp)return i.preview;const a=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw oe(a,"warning"),new Error(a)}}function tw(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],a=_.lastSyncLegacySharedReview,s=Math.max(0,Number(a?.memory_count??0)),c=a?.has_data?{groups:Array.isArray(a.groups)?a.groups.map(d=>{const u=d;return{displayProject:String(u.display_project||u.project||"Unknown project"),identitySource:String(u.identity_source||"unknown"),lastUpdatedAt:typeof u.last_updated_at=="string"?u.last_updated_at:null,memoryCount:Number(u.memory_count||0),memorySamples:Array.isArray(u.memory_samples)?u.memory_samples.map(p=>{const m=p,f=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:f,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(u.peer_owned_memory_count||0),reassignableMemoryCount:Number(u.reassignable_memory_count||0),suggestedScopeId:typeof u.suggested_scope_id=="string"?u.suggested_scope_id:null,suggestionReason:typeof u.suggestion_reason=="string"?u.suggestion_reason:null,workspaceIdentity:String(u.workspace_identity||u.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(a.scope_id||"legacy-shared-review"),totalGroupCount:Number(a.total_group_count||a.groups?.length||0),targetScopes:Array.isArray(a.target_scopes)?a.target_scopes.map(d=>{const u=d;return{authorityType:String(u.authority_type||"unknown"),label:String(u.label||u.scope_id||"Unknown domain"),scopeId:String(u.scope_id||"")}}).filter(d=>d.scopeId):[]}:null;if(!i.length&&!c){bi(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`,et(n,y(s1,{items:i.map(d=>({actorDisplayName:String(d.actor_display_name||d.actor_id||"unknown"),actorId:String(d.actor_id||"unknown"),peerName:String(d.peer_name||d.peer_device_id||"Device"),privateCount:Number(d.private_count||0),scopeLabel:String(d.scope_label||"All allowed projects"),shareableCount:Number(d.shareable_count||0)})),legacyReview:c,onLegacyReassign:d1,onLegacyReview:l1,onReview:c1}))}var dc="";function u1(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const a of r){const s=String(a.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],a])}for(const[a,s]of _.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){_.pendingCoordinatorApprovalsByDeviceId.delete(a);continue}if(n)continue;const c=i.get(a);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||_.pendingCoordinatorApprovalsByDeviceId.delete(a))}}function p1(){return[..._.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var Ka=null,Qu=0,m1=15e3;function nw(e){return`project:${e||""}|includeJoinRequests:false`}function f1(e){const t=nw(e);return!Ka||Ka.key!==t||Date.now()>=Ka.expiresAtMs?null:Ka.payload}function h1(e,t){Ka={key:nw(e),expiresAtMs:Date.now()+m1,payload:t}}function g1(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function v1(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function Ni(){const e=++Qu;try{const t=_.currentProject||"",n=!1,r=_.activeTab==="health";let i=!1;const a=!Zi();let s;r?(s=f1(t),s||(s=await to(a,t,{includeJoinRequests:!1}),i=!0)):(s=await to(a,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=_.lastDeviceIdentityInventory,u=_.lastShareOperations,p=!1,m=!1,f=_.deviceIdentityInventoryLoadError,g=!1;const h=PO();try{c=await lS()}catch{p=!0}try{l=await Za()}catch{m=!0}if(_.activeTab==="advanced"){f=!1;try{d=await Sc()}catch{f=!0}}try{const T=await Hp();u=Array.isArray(T.items)?T.items:[]}catch{g=!0}if(e!==Qu)return;i&&h1(t,g1(s)),u1(s.coordinator);const v=JSON.stringify([s,c,l,d,f,u,g,h,p1()]);if(v===dc)return;dc=v;const w=s.status&&typeof s.status=="object"?s.status:null;w&&(_.lastSyncStatus=w),Array.isArray(c?.items)?_.lastSyncActors=c.items:_.lastSyncActors=[];const b=Array.isArray(s.peers)?s.peers:[],S=new Set(b.map(T=>String(T?.peer_device_id||"").trim()).filter(Boolean)),C=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(T=>{const P=String(T?.peer_device_id||"").trim();return P&&!S.has(P)}):[];_.pendingAcceptedSyncPeers=C,_.lastSyncPeers=[...b,...C],f||(_.lastDeviceIdentityInventory=d),_.deviceIdentityInventoryLoadError=f,_.lastShareOperations=u,_.shareOperationsLoadError=g,_.lastSyncSharingReview=s.sharing_review||[],_.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,_.lastSyncCoordinator=s.coordinator||null,_.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,_.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],_.lastSyncAttempts=s.attempts||[],_.lastSyncLegacyDevices=s.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=h,_.lastSyncViewModel=wO({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:w,shareOperations:_.lastShareOperations,shareOperationsLoadError:g,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),U_(),qa(),wj(),Cj(),tw(),Vu(),z_(),B_(),$b(),p&&Sj(),m&&(_.lastCoordinatorAdminStatus=null,qa())}catch{if(e!==Qu)return;dc="",_.deviceIdentityInventoryLoadError=!0,Gn("syncTeamSkeleton"),Gn("syncActorsSkeleton"),Gn("syncPeersSkeleton"),Gn("syncDiagSkeleton"),v1(),Nj(),OO()}}function y1(){dc="",_.lastSyncPeers?.length&&Vu()}async function b1(){try{_.pairingPayloadRaw=await dS()||null,Bu()}catch{_.pairingPayloadRaw=null,Bu()}}function _1(e){yM(),vs(),Ej(Ni),_j(Ni),UO(Vu),Rj(e,Ni),Tj(Ni),GO(e),Wu(),kj()}function w1(e,t){const n=Oe("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function S1(){try{const e=await iS();if(!e?.version)return;w1(e.version,"b60075d")}catch{}}var Zu=null,rw=1500,iw="codemem-legacy-upgrade-notice-dismissed",qn=null,en=!1,ep=!1,Va=null;function aw(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function ow(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=aw(n.total_group_count,r.length),a=aw(n.memory_count);return i<=0||a<=0?null:{groupCount:i,memoryCount:a}}function sw(){try{return localStorage.getItem(iw)==="1"}catch{return!1}}function uc(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(iw,"1")}catch{}}function cw(){const e=Oe("legacyUpgradeModal");return!e||e.hidden?[]:Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(t=>!t.hidden&&t.offsetParent!==null)}function C1(){const e=cw(),t=Oe("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function lw(e){const t=Oe("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),uc(),Wa(!1);return}if(e.key==="Enter"){const a=Oe("legacyUpgradeReviewGroups");Wr(e,{onSubmit:()=>a?.click(),disabled:!a||a.disabled});return}if(e.key!=="Tab")return;const n=cw();if(n.length===0)return;const r=n[0],i=n[n.length-1];if(e.shiftKey&&document.activeElement===r){e.preventDefault(),i.focus();return}!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus())}function dw(e){for(const t of document.querySelectorAll("header, .tab-bar, .tab-panel, #toastRoot, #viewerReconnectOverlay, #settingsDialogMount"))t.id==="viewerReconnectOverlay"&&t.hidden||(t.inert=e,e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}function Wa(e,t){const n=Oe("legacyUpgradeModalBackdrop"),r=Oe("legacyUpgradeModal"),i=Oe("legacyUpgradeSummary");if(!(!n||!r||!i)){if(t&&(i.textContent=`${t.groupCount.toLocaleString()} older ${t.groupCount===1?"project needs":"projects need"} a Sharing domain. They contain ${t.memoryCount.toLocaleString()} older shared memories total; you will review the projects, not individual memories.`),n.hidden=!e,r.hidden=!e,e){Va=document.activeElement,document.addEventListener("keydown",lw),C1(),dw(!0);return}dw(!1),document.removeEventListener("keydown",lw),Va&&document.contains(Va)&&Va.focus(),Va=null}}function uw(e){!e||ep||sw()||(ep=!0,Wa(!0,e))}async function N1(){if(!(ep||sw()))try{uw(ow(await to(!1,"",{includeJoinRequests:!1})))}catch{}}function kr(e,t){const n=Oe("viewerReconnectOverlay"),r=Oe("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function tp(){try{return await rS(),!0}catch{return!1}}function T1(){return document.visibilityState!=="hidden"&&!c_()}function pw(){if(en)return;en=!0,np(),Er("error","(reconnecting)"),kr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await tp()){if(qn&&(clearTimeout(qn),qn=null),en=!1,kr(!0,"Viewer responded. Restoring your session…"),T1()){Er("refreshing"),za();try{await pc()}catch{}}else Er("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");en||kr(!1);return}kr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),qn=setTimeout(e,rw)};qn=setTimeout(e,rw)}function Er(e,t){_.refreshState=e;const n=Oe("refreshStatus");if(!n)return;const r=a=>{const s=Oe("refreshAnnouncer");!s||Zu===e||(s.textContent=a,Zu=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,Zu=null}function np(){_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function za(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Kn(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(np(),Er("paused","(tab hidden)")):!c_()&&!en&&(za(),Kn())});function I1(){const e=_.advancedSection==="sync",t=Oe("advancedSyncContent"),n=Oe("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Oe("advancedSyncButton"),i=Oe("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const a=window.location.hash.replace(/^#/,"");Wu(a==="sync/diagnostics"||a==="advanced/sync/diagnostics"?"diagnostics":"main")})}function mw(e){const t=new Set(FI(_.lastCoordinatorAdminStatus));rr.forEach(n=>{const r=Oe(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),rr.forEach(n=>{const r=Oe(`tabBtn-${n}`);if(!r)return;r.hidden=!t.has(n);const i=n===e&&t.has(n);r.classList.toggle("active",i),i?r.setAttribute("aria-current","page"):r.removeAttribute("aria-current")}),I1()}function Ti(e,t={}){const n=Qi(e,_.lastCoordinatorAdminStatus);n==="advanced"&&Nl(t.advancedSection??Cl()??_.advancedSection),Ph(n,t.canonicalHash?{canonicalHash:!0}:{}),mw(n),Kn()}function k1(){rr.forEach(e=>{Oe(`tabBtn-${e}`)?.addEventListener("click",()=>Ti(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Oe("advancedSyncButton")?.addEventListener("click",()=>Nl("sync",!0)),Oe("advancedTeamsButton")?.addEventListener("click",()=>Nl("teams",!0)),window.addEventListener("hashchange",()=>{const e=Sl();if(e){const t=Cl();Ti(e,t?{advancedSection:t}:{})}}),Ti(_.activeTab)}async function E1(){try{const e=await eo();_.knownProjects=e,y1();const t=bl("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function P1(e){_.pendingDeviceIdentityFocus=e?.trim()||null,Ti("devices",{canonicalHash:!0})}var Ja=HT({},{onOpenTeamSetup:jb,onReviewDevices:P1}),fw={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},rp=0,ip=null,xt=null;async function A1(){const e=[];let t=0;for(;;){const n=await io({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return xo(e)}function x1(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of _.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),a=Ua(r);n(i,a==="connected"||a==="available"?"available":a==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function R1(){return _.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function hw(e){if(e==="advanced_sync"){Ti("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}Ti(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function ap(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=D1(e,++rp);return ip=t,t}async function D1(e,t){xt||ws(e,fw,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,a]=await Promise.all([A1(),wc(),kS(),Sc().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:xt?.inventory,unavailable:!0})),Ni()]);if(t!==rp)return ip??!1;const s=x1(),c=R1(),l=Kp(_.lastSyncStatus);return!a.unavailable&&a.inventory&&(_.lastDeviceIdentityInventory=a.inventory),_.deviceIdentityInventoryLoadError=a.unavailable,ws(e,r,i,n,s,{inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l,onCommitted:async()=>{const[d,u]=await Promise.all([ap(),Ja()]);return d&&u},onNavigate:hw,peerRuntimeMetadata:c}),xt={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==rp?ip??!1:(xt?ws(e,xt.intent,xt.reconciliation,xt.projects,xt.availability,{coordinatorEnrollmentIssueCount:xt.coordinatorEnrollmentIssueCount,inventory:xt.inventory,inventoryUnavailable:xt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([ap(),Ja()]);return n&&r},onNavigate:hw,peerRuntimeMetadata:xt.peerRuntimeMetadata,refreshError:!0}):ws(e,fw,{version:1,items:[]},[],[],{loadError:!0}),!1)}}bl("projectFilter")?.addEventListener("change",()=>{_.currentProject=bl("projectFilter")?.value||"",yr(!0),Kn()});var op=null;async function Kn(){en||(op&&clearTimeout(op),op=setTimeout(()=>pc(),80))}async function pc(){if(!en){if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;try{Er("refreshing");const e=_.activeTab,t=[cL(),F$()];let n=!0;e==="feed"&&t.push(Za().then(i=>{_.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{_.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(au()),e==="projects"&&t.push(Cu()),e==="sharing"&&t.push(Ja()),e==="devices"&&t.push(ap().then(i=>{n=i})),(e==="advanced"&&_.advancedSection==="sync"||e==="health")&&t.push(Ni()),e==="advanced"&&_.advancedSection==="teams"&&t.push(gd()),_.syncPairingOpen&&t.push(b1()),await Promise.all(t),uw(ow(_.lastSyncLegacySharedReview));const r=Qi(_.activeTab,_.lastCoordinatorAdminStatus);r!==_.activeTab&&Ph(r),mw(_.activeTab),Er(n?"idle":"error")}catch{await tp()?Er("error"):pw()}finally{_.refreshInFlight=!1,_.refreshQueued&&!en&&(_.refreshQueued=!1,pc())}}}zI();var gw=document.getElementById("toastRoot");gw&&PI(gw);var vw=document.getElementById("legacyTeamSetupMount");vw&&EL(vw,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(_.activeTab==="sharing"?(t=await Cu(n),e=await Ja(n)):(e=await Ja(n),t=await Cu(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),JI(_l("themeToggle")),Dh(Il()),k1(),zD(),l$(()=>Kn(),{onOpenTeamSetup:jb}),_1(()=>Kn()),OA(),gM(np,za,()=>Kn()),E1(),Oe("viewerReconnectRetry")?.addEventListener("click",async()=>{if(kr(!0,"Checking whether the viewer server is back…"),!await tp()){pw();return}qn&&(clearTimeout(qn),qn=null),en=!1,kr(!0,"Viewer responded. Restoring your session…"),za();try{await pc()}catch{}en||kr(!1)}),Oe("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{uc(),Wa(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Oe("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{uc(),Wa(!1),window.location.hash="projects"}),Oe("legacyUpgradeNotNow")?.addEventListener("click",()=>{uc(),Wa(!1)}),S1(),N1(),Kn(),za()})();
|
|
107
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${fn(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=$b(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+fn(t)+'"'),o+=">"+r+"</a>",o}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=$b(e);if(i===null)return fn(n);e=i;let o=`<img src="${e}" alt="${fn(n)}"`;return t&&(o+=` title="${fn(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:fn(e.text)}},dp=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Qt=class Mf{options;renderer;textRenderer;constructor(t){this.options=t||Kr,this.options.renderer=this.options.renderer||new Cc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new dp}static parse(t,n){return new Mf(n).parse(t)}static parseInline(t,n){return new Mf(n).parseInline(t)}parse(t){this.renderer.parser=this;let n="";for(let r=0;r<t.length;r++){let i=t[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,c=this.options.extensions.renderers[s.type].call({parser:this},s);if(c!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=c||"";continue}}let o=i;switch(o.type){case"space":n+=this.renderer.space(o);break;case"hr":n+=this.renderer.hr(o);break;case"heading":n+=this.renderer.heading(o);break;case"code":n+=this.renderer.code(o);break;case"table":n+=this.renderer.table(o);break;case"blockquote":n+=this.renderer.blockquote(o);break;case"list":n+=this.renderer.list(o);break;case"checkbox":n+=this.renderer.checkbox(o);break;case"html":n+=this.renderer.html(o);break;case"def":n+=this.renderer.def(o);break;case"paragraph":n+=this.renderer.paragraph(o);break;case"text":n+=this.renderer.text(o);break;default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(t,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let o=t[i];if(this.options.extensions?.renderers?.[o.type]){let c=this.options.extensions.renderers[o.type].call({parser:this},o);if(c!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(o.type)){r+=c||"";continue}}let s=o;switch(s.type){case"escape":r+=n.text(s);break;case"html":r+=n.html(s);break;case"link":r+=n.link(s);break;case"image":r+=n.image(s);break;case"checkbox":r+=n.checkbox(s);break;case"strong":r+=n.strong(s);break;case"em":r+=n.em(s);break;case"codespan":r+=n.codespan(s);break;case"br":r+=n.br(s);break;case"del":r+=n.del(s);break;case"text":r+=n.text(s);break;default:{let c='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},la=class{options;block;constructor(e){this.options=e||Kr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Xt.lex:Xt.lexInline}provideParser(e=this.block){return e?Qt.parse:Qt.parseInline}},E$=class{defaults=np();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Qt;Renderer=Cc;TextRenderer=dp;Lexer=Xt;Tokenizer=Sc;Hooks=la;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,t));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,t));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,t));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=t.renderers[i.name];o?t.renderers[i.name]=function(...s){let c=i.renderer.apply(this,s);return c===!1&&(c=o.apply(this,s)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[i.level];o?o.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new Cc(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,c=n.renderer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Sc(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,c=n.tokenizer[s],l=i[s];i[s]=(...d)=>{let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new la;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,c=n.hooks[s],l=i[s];la.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&la.passThroughHooksRespectAsync.has(o))return(async()=>{let p=await c.call(i,d);return l.call(i,p)})();let u=c.call(i,d);return l.call(i,u)}:i[s]=(...d)=>{if(this.defaults.async)return(async()=>{let p=await c.apply(i,d);return p===!1&&(p=await l.apply(i,d)),p})();let u=c.apply(i,d);return u===!1&&(u=l.apply(i,d)),u}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let c=[];return c.push(o.call(this,s)),i&&(c=c.concat(i.call(this,s))),c}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Xt.lex(e,t??this.defaults)}parser(e,t){return Qt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer(e):e?Xt.lex:Xt.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(e):e?Qt.parse:Qt.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(o);try{i.hooks&&(t=i.hooks.preprocess(t));let s=(i.hooks?i.hooks.provideLexer(e):e?Xt.lex:Xt.lexInline)(t,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(e):e?Qt.parse:Qt.parseInline)(s,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(s){return o(s)}}}onError(e,t){return n=>{if(n.message+=`
|
|
108
|
+
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+fn(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},zr=new E$;function Fe(e,t){return zr.parse(e,t)}Fe.options=Fe.setOptions=function(e){return zr.setOptions(e),Fe.defaults=zr.defaults,wb(Fe.defaults),Fe},Fe.getDefaults=np,Fe.defaults=Kr;function A$(...e){return zr.use(...e),Fe.defaults=zr.defaults,wb(Fe.defaults),Fe}Fe.use=A$,Fe.walkTokens=function(e,t){return zr.walkTokens(e,t)},Fe.parseInline=zr.parseInline,Fe.Parser=Qt,Fe.parser=Qt.parse,Fe.Renderer=Cc,Fe.TextRenderer=dp,Fe.Lexer=Xt,Fe.lexer=Xt.lex,Fe.Tokenizer=Sc,Fe.Hooks=la,Fe.parse=Fe;var DU=Fe.options,$U=Fe.setOptions,LU=Fe.walkTokens,jU=Fe.parseInline,OU=Qt.parse,MU=Xt.lex,x$={ALLOWED_TAGS:["p","br","strong","em","code","pre","ul","ol","li","blockquote","a","h1","h2","h3","h4","h5","h6","hr"],ALLOWED_ATTR:["href","title"],ALLOW_DATA_ATTR:!1};function D$(e){const t=String(e||"").trim();if(!t)return!1;if(t.startsWith("#")||t.startsWith("/"))return!0;const n=t.toLowerCase();return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("mailto:")}_b.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(D$(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function up(e){const t=Fe.parse(String(e||""),{async:!1});return _b.sanitize(t,x$)}function $$(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=Object.keys(e);return t.filter(r=>n.includes(r)).map(r=>{const i=String(e[r]||"").trim();return i?b("div",{className:"summary-section",key:r},b("div",{className:"summary-section-label"},p0(r)),b("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:up(i)}})):null}).filter(Boolean)}function L$(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const o=r.indexOf(":"),s=r.slice(0,o).trim(),c=r.slice(o+1).trim();return!s||!c?null:b("div",{className:"summary-section",key:`${s}-${i}`},b("div",{className:"summary-section-label"},s),b("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:up(c)}}))}).filter(Boolean);if(n.length)return b("div",{className:"feed-body facts"},n)}return b("div",{className:"feed-body"},b("ul",null,t.map((n,r)=>b("li",{key:`${n}-${r}`},n))))}function Mb(e,t="feed-body"){const n=String(e||"").trim();return n?b("div",{className:t,dangerouslySetInnerHTML:{__html:up(n)}}):null}function j$(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const o=String(e?.body_text||"").trim();if(o.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(o);d;d=l.exec(o)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function Ic(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function O$(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Ic(e,t)?"session_summary":n||"change"}var M$=Object.defineProperty,Ge=(e,t)=>M$(e,"name",{value:t,configurable:!0}),pp=["Enter"," "],F$=["ArrowDown","PageUp","Home"],Fb=["ArrowUp","PageDown","End"],B$=[...F$,...Fb],FU={ltr:[...pp,"ArrowRight"],rtl:[...pp,"ArrowLeft"]},Pc="Menu",[fp,U$,q$]=$o(Pc),[Wr,Bb]=lt(Pc,[q$,Xn,Ai]),mp=Xn(),Ub=Ai(),[G$,da]=Wr(Pc),[H$,hp]=Wr(Pc),K$=Ge(e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:o,modal:s=!0}=e,c=mp(t),[l,d]=x(null),u=q(!1),p=mt(o),f=Ei(i);return K(()=>{const m=Ge(()=>{u.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},"handleKeyDown"),v=Ge(()=>u.current=!1,"handlePointer");return document.addEventListener("keydown",m,{capture:!0}),()=>{document.removeEventListener("keydown",m,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),K(()=>{if(!n)return;const m=Ge(()=>p(!1),"handleBlur");return window.addEventListener("blur",m),()=>window.removeEventListener("blur",m)},[n,p]),a(zs,{...c,children:a(G$,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(H$,{scope:t,onClose:se(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})},"Menu"),V$=J(Ge(function(t,n){const{__scopeMenu:r,...i}=t,o=mp(r);return a(Vo,{...o,...i,ref:n})},"MenuAnchor")),qb="MenuPortal",[z$,W$]=Wr(qb,{forceMount:void 0}),J$=Ge(e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=da(qb,t);return a(z$,{scope:t,forceMount:n,children:a(Pt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"MenuPortal"),ar="MenuContent",[Y$,Gb]=Wr(ar),X$=J(Ge(function(t,n){const r=W$(ar,t.__scopeMenu),{forceMount:i=r.forceMount,...o}=t,s=da(ar,t.__scopeMenu),c=hp(ar,t.__scopeMenu);return a(fp.Provider,{scope:t.__scopeMenu,children:a(Pt,{present:i||s.open,children:a(fp.Slot,{scope:t.__scopeMenu,children:c.modal?a(Q$,{...o,ref:n}):a(Z$,{...o,ref:n})})})})},"MenuContent")),Q$=J(Ge(function(t,n){const r=da(ar,t.__scopeMenu),i=q(null),o=Se(n,i);return K(()=>{const s=i.current;if(s)return ds(s)},[]),a(Hb,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:ne(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),Z$=J(Ge(function(t,n){const r=da(ar,t.__scopeMenu);return a(Hb,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),eL=on("MenuContent.ScrollLock"),Hb=J(Ge(function(t,n){const{__scopeMenu:r,loop:i=!1,trapFocus:o,onOpenAutoFocus:s,onCloseAutoFocus:c,disableOutsidePointerEvents:l,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,disableOutsideScroll:g,...h}=t,y=da(ar,r),w=hp(ar,r),_=mp(r),I=Ub(r),P=U$(r),[k,A]=x(null),L=q(null),F=Se(n,L,y.onContentChange),T=q(0),M=q(""),j=q(0),B=q(null),U=q("right"),$=q(0),E=g?Co:z,S=g?{as:eL,allowPinchZoom:!0}:void 0,D=Ge(G=>{const oe=M.current+G,ae=P().filter(Ne=>!Ne.disabled),ee=document.activeElement,ie=ae.find(Ne=>Ne.ref.current===ee)?.textValue,Ce=Yb(ae.map(Ne=>Ne.textValue),oe,ie),Ie=ae.find(Ne=>Ne.textValue===Ce)?.ref.current;Ge((function Ne(le){M.current=le,window.clearTimeout(T.current),le!==""&&(T.current=window.setTimeout(()=>Ne(""),1e3))}),"updateSearch")(oe),Ie&&setTimeout(()=>Ie.focus())},"handleTypeaheadSearch");K(()=>()=>window.clearTimeout(T.current),[]),bi();const H=se(G=>U.current===B.current?.side&&Qb(G,B.current?.area),[]);return a(Y$,{scope:r,searchRef:M,onItemEnter:se(G=>{H(G)&&G.preventDefault()},[H]),onItemLeave:se(G=>{H(G)||(L.current?.focus(),A(null))},[H]),onTriggerLeave:se(G=>{H(G)&&G.preventDefault()},[H]),pointerGraceTimerRef:j,onPointerGraceIntentChange:se(G=>{B.current=G},[]),children:a(E,{...S,children:a(ts,{asChild:!0,trapped:o,onMountAutoFocus:ne(s,G=>{G.preventDefault(),L.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:a(hi,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,children:a(qd,{asChild:!0,...I,dir:w.dir,orientation:"vertical",loop:i,currentTabStopId:k,onCurrentTabStopIdChange:A,onEntryFocus:ne(d,G=>{w.isUsingKeyboardRef.current||G.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(Ws,{role:"menu","aria-orientation":"vertical","data-state":Vb(y.open),"data-radix-menu-content":"",dir:w.dir,..._,...h,ref:F,style:{outline:"none",...h.style},onKeyDown:ne(h.onKeyDown,G=>{const oe=G.target.closest("[data-radix-menu-content]")===G.currentTarget,ae=G.ctrlKey||G.altKey||G.metaKey,ee=G.key.length===1;oe&&(G.key==="Tab"&&G.preventDefault(),!ae&&ee&&D(G.key));const ie=L.current;if(G.target!==ie||!B$.includes(G.key))return;G.preventDefault();const Ce=P().filter(Ie=>!Ie.disabled).map(Ie=>Ie.ref.current);Fb.includes(G.key)&&Ce.reverse(),Wb(Ce)}),onBlur:ne(t.onBlur,G=>{G.currentTarget.contains(G.target)||(window.clearTimeout(T.current),M.current="")}),onPointerMove:ne(t.onPointerMove,Rc(G=>{const oe=G.target,ae=$.current!==G.clientX;if(G.currentTarget.contains(oe)&&ae){const ee=G.clientX>$.current?"right":"left";U.current=ee,$.current=G.clientX}}))})})})})})})},"MenuContentImpl")),gp="MenuItem",Kb="menu.itemSelect",tL=J(Ge(function(t,n){const{disabled:r=!1,onSelect:i,...o}=t,s=q(null),c=hp(gp,t.__scopeMenu),l=Gb(gp,t.__scopeMenu),d=Se(n,s),u=q(!1),p=Ge(()=>{const f=s.current;if(!r&&f){const m=new CustomEvent(Kb,{bubbles:!0,cancelable:!0});f.addEventListener(Kb,v=>i?.(v),{once:!0}),es(f,m),m.defaultPrevented?u.current=!1:c.onClose()}},"handleSelect");return a(nL,{...o,ref:d,disabled:r,onClick:ne(t.onClick,p),onPointerDown:f=>{t.onPointerDown?.(f),u.current=!0},onPointerUp:ne(t.onPointerUp,f=>{u.current||f.currentTarget?.click()}),onKeyDown:ne(t.onKeyDown,f=>{r||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||pp.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})},"MenuItem")),nL=J(Ge(function(t,n){const{__scopeMenu:r,disabled:i=!1,textValue:o,...s}=t,c=Gb(gp,r),l=Ub(r),d=q(null),u=Se(n,d),[p,f]=x(!1),[m,v]=x("");return K(()=>{const g=d.current;g&&v((g.textContent??"").trim())},[s.children]),a(fp.ItemSlot,{scope:r,disabled:i,textValue:o??m,children:a(Gd,{asChild:!0,...l,focusable:!i,children:a(ve.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...s,ref:u,onPointerMove:ne(t.onPointerMove,Rc(g=>{i?c.onItemLeave(g):(c.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ne(t.onPointerLeave,Rc(g=>c.onItemLeave(g))),onFocus:ne(t.onFocus,()=>f(!0)),onBlur:ne(t.onBlur,()=>f(!1))})})})},"MenuItemImpl")),[BU,UU]=Wr("MenuRadioGroup",{value:void 0,onValueChange:Ge(()=>{},"onValueChange")}),rL="MenuItemIndicator",[qU,GU]=Wr(rL,{checked:!1}),iL="MenuSub",[HU,KU]=Wr(iL);function Vb(e){return e?"open":"closed"}Ge(Vb,"getOpenState");function zb(e){return e==="indeterminate"}Ge(zb,"isIndeterminate");function oL(e){return zb(e)?"indeterminate":e?"checked":"unchecked"}Ge(oL,"getCheckedState");function Wb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}Ge(Wb,"focusFirst");function Jb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Ge(Jb,"wrapArray");function Yb(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let o=Jb(e,Math.max(i,0));r.length===1&&(o=o.filter(c=>c!==n));const s=o.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}Ge(Yb,"getNextMatch");function Xb(e,t){const{x:n,y:r}=e;let i=!1;for(let o=0,s=t.length-1;o<t.length;s=o++){const c=t[o],l=t[s],d=c.x,u=c.y,p=l.x,f=l.y;u>r!=f>r&&n<(p-d)*(r-u)/(f-u)+d&&(i=!i)}return i}Ge(Xb,"isPointInPolygon");function Qb(e,t){return t?Xb({x:e.clientX,y:e.clientY},t):!1}Ge(Qb,"isPointerInGraceArea");function Rc(e){return t=>t.pointerType==="mouse"?e(t):void 0}Ge(Rc,"whenMouse");var aL=K$,sL=V$,cL=J$,lL=X$,dL=tL,uL=Object.defineProperty,ua=(e,t)=>uL(e,"name",{value:t,configurable:!0}),vp="DropdownMenu",[pL,VU]=lt(vp,[Bb]),pa=Bb(),[fL,Zb]=pL(vp),mL=ua(e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=pa(t),d=q(null),[u,p]=Et({prop:i,defaultProp:o??!1,onChange:s,caller:vp});return a(fL,{scope:t,triggerId:Nt(),triggerRef:d,contentId:Nt(),open:u,onOpenChange:p,onOpenToggle:se(()=>p(f=>!f),[p]),modal:c,children:a(aL,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})},"DropdownMenu"),hL="DropdownMenuTrigger",gL=J(ua(function(t,n){const{__scopeDropdownMenu:r,disabled:i=!1,...o}=t,s=Zb(hL,r),c=pa(r),l=Se(n,s.triggerRef);return a(sL,{asChild:!0,...c,children:a(ve.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":i?"":void 0,disabled:i,...o,ref:l,onPointerDown:ne(t.onPointerDown,d=>{!i&&d.button===0&&d.ctrlKey===!1&&(s.onOpenToggle(),s.open||d.preventDefault())}),onKeyDown:ne(t.onKeyDown,d=>{i||(["Enter"," "].includes(d.key)&&s.onOpenToggle(),d.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),vL=ua(e=>{const{__scopeDropdownMenu:t,...n}=e,r=pa(t);return a(cL,{...r,...n})},"DropdownMenuPortal"),yL="DropdownMenuContent",bL=J(ua(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=Zb(yL,r),s=pa(r),c=q(!1);return a(lL,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...i,ref:n,onCloseAutoFocus:ne(t.onCloseAutoFocus,l=>{c.current||o.triggerRef.current?.focus(),c.current=!1,l.preventDefault()}),onInteractOutside:ne(t.onInteractOutside,l=>{const d=l.detail.originalEvent,u=d.button===0&&d.ctrlKey===!0,p=d.button===2||u;(!o.modal||p)&&(c.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),_L=J(ua(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=pa(r);return a(dL,{...o,...i,ref:n})},"DropdownMenuItem")),wL=mL,SL=gL,CL=vL,IL=bL,e_=_L;function PL({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return b(wL,null,b(SL,{asChild:!0},b("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),b(CL,null,b(IL,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},b(e_,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),b(e_,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function RL({modes:e,active:t,onSelect:n}){return e.length<=1?null:b("div",{className:"feed-toggle"},e.map(r=>b("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function yp({label:e,variant:t=""}){return b(zu,{variant:"provenance",tone:t||void 0},e)}function kL({tag:e}){const t=Uy(e);return t?b(zu,{variant:"tag",title:String(e)},t):null}function TL({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=pc(e?.metadata_json),s=Ic(e,o),c=O$(e,o),l=Rt(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,f=l0(p),m=y0(e),v=uc(e.files||[]),g=e.project||"",h=w0(e),y=S0(e,o),w=String(e.visibility||o?.visibility||"private").trim(),_=String(e.workspace_kind||o?.workspace_kind||"").trim(),I=String(e.origin_source||o?.origin_source||"").trim(),P=String(e.trust_state||o?.trust_state||"").trim(),k=m.length?` · ${m.map(me=>Uy(me)).join(", ")}`:"",A=v.length?` · ${f0(v)}`:"",L=Number(e.id||0),F=L>0?`ID ${L}`:"",[T,M]=x(C.newItemKeys.has(l)),j=s?j$({...e,metadata_json:o}):null,B=s?null:Q0({...e,metadata_json:o}),U=B?Z0(B):[],$=B?eD(B):"summary",E=C.itemViewState.get(l),S=B&&E&&U.some(me=>me.id===E)?E:$,[D,H]=x(S),G=`${l}:${D}`,[oe,ae]=x(C.itemExpandState.get(G)===!0),[ee,ie]=x(w==="shared"?"shared":"private"),[Ce,Ie]=x(!1),[Ne,le]=x(!1),[ye,Y]=x(!1),ce=j?$$(j):[];K(()=>{B&&(U.some(me=>me.id===D)||H($))},[D,$,U,B]),K(()=>{C.itemViewState.set(l,D)},[D,l]),K(()=>{const me=`${l}:${D}`;ae(C.itemExpandState.get(me)===!0)},[D,l]),K(()=>{ie(w==="shared"?"shared":"private")},[w]),K(()=>{if(!T)return;const me=window.setTimeout(()=>{C.newItemKeys.delete(l),M(!1)},700);return()=>window.clearTimeout(me)},[T,l]);const ge=ee,pe=ge==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",He=[g?`Project ${g}`:"No project",f].filter(Boolean).join(" · "),de=[_&&_!==w?`Workspace ${_}`:"",I?`From ${I}`:"",y,P&&P!=="trusted"?_0(P):""].filter(Boolean).join(" · "),W=[`${k}${A}`.trim(),de].filter(Boolean).join(" · "),Pe=!!B&&tD(D,B),re=[D==="facts"?"feed-body facts":"feed-body",Pe&&!oe?nD(D).join(" "):""].filter(Boolean).join(" "),je=s?ce.length?b("div",{className:"feed-body facts"},ce):Mb(String(e.body_text||""))||b("div",{className:"feed-body"}):B?D==="facts"?L$(B.facts)||b("div",{className:re}):Mb(D==="narrative"?B.narrative:B.summary,re)||b("div",{className:re}):b("div",{className:"feed-body"});async function it(me){const ot=ge;ie(me),Ie(!0);try{const Ze=await zS(L,me);Ze?.item&&(t(Ze.item),r()),Q(me==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Ze){ie(ot),Q(Ze instanceof Error?Ze.message:"Failed to save visibility.","warning")}finally{Ie(!1)}}async function hr(){const me=String(e.project||"").trim(),ot=me,Ze=String(u||"this memory").trim(),ao=Ze.length>80?`${Ze.slice(0,79).trimEnd()}…`:Ze,so=me?`Move "${ao}" from "${me}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${ao}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let ai=[];try{ai=(await Fa()).filter(_t=>_t&&_t!==me)}catch{}const co=await Du({title:"Assign to project",description:so,initialValue:ot,placeholder:"Pick one or type a new project name",suggestions:ai,confirmLabel:"Move",cancelLabel:"Cancel",validate:_t=>{const yn=_t.trim();return yn?yn===me?"Already assigned to this project.":null:"Enter a project name."}});if(co==null)return;const vn=co.trim();if(!(!vn||vn===me)){Y(!0);try{const _t=await WS(L,vn),yn=Number(_t.moved_memory_count||1),nl=yn>1?`Moved ${yn} memories from this session to "${_t.project}".`:`Moved to "${_t.project}".`;Q(nl),await i(),r()}catch(_t){Q(_t instanceof Error?_t.message:"Failed to move memory.","warning")}finally{Y(!1)}}}async function Zt(){const me=String(u||"this memory").trim(),ot=me.length>80?`${me.slice(0,79).trimEnd()}…`:me;if(await pn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${ot}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){le(!0);try{await JS(L),n(L),r(),await i(),Q("Memory forgotten and removed from the active feed.")}catch(Ze){Q(Ze instanceof Error?Ze.message:"Failed to forget memory.","warning")}finally{le(!1)}}}const Un=c.replace(/_/g," "),gr=v.length?b("div",{className:"feed-files"},v.map((me,ot)=>b("span",{className:"feed-file",key:`${String(me)}-${ot}`},String(me)))):null;return b("article",{className:`feed-item ${c}${T?" new-item":""}`.trim(),"data-key":l},b("div",{className:"feed-kind-banner"},b(zu,{variant:"kind",tone:c},Un)),b("div",{className:"feed-card-body"},b("div",{className:"feed-card-header"},b("div",{className:"feed-header"},b("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:Hk(u,C.feedQuery)}}),b("div",{className:"feed-card-subtitle small"},He)),b("div",{className:"feed-actions"},B?b(RL,{active:D,modes:U,onSelect:me=>H(me)}):null,b(gc,{label:c0(p),side:"left"},b("div",{className:"small feed-age"},f)),e.owned_by_self&&L>0?b(PL,{assignProjectDisabled:ye,disabled:Ne,onAssignProject:()=>{hr()},onForget:()=>{Zt()},title:String(u||"memory")}):null)),b("div",{className:"feed-provenance"},b(yp,{label:h,variant:h==="You"?"mine":"author"}),b(yp,{label:w||"private",variant:w||"private"}),F?b(gc,{label:`Memory database id ${L}`,side:"top"},b(yp,{label:F,variant:"memory-id"})):null),b("div",{className:"feed-meta"},W||"No tags, files, or provenance details attached."),je,b("div",{className:"feed-footer"},b("div",{className:"feed-footer-left"},m.length?b("div",{className:"feed-tags"},m.map((me,ot)=>b(kL,{key:`${String(me)}-${ot}`,tag:me}))):null,e.owned_by_self&&L>0?b("div",{className:"feed-visibility-controls"},b("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:Ce,onChange:me=>{it(String(me.currentTarget.value)==="shared"?"shared":"private")},value:ge},b("option",{value:"private"},"Only me"),b("option",{value:"shared"},"Share with peers")),b("div",{className:"feed-visibility-note"},pe)):null),b("div",{className:"feed-footer-right"},Pe?b("button",{className:"feed-expand",onClick:()=>{const me=!oe;C.itemExpandState.set(G,me),ae(me)},type:"button"},oe?"Collapse":"Expand"):null)),gr))}function NL({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return b("div",{className:"feed-skeleton-item","aria-hidden":"true"},b("div",{className:"feed-skeleton-banner"}),b("div",{className:"feed-skeleton-body"},b("div",{className:`feed-skeleton-line ${n}`}),b("div",{className:`feed-skeleton-line ${r}`}),b("div",{className:"feed-skeleton-footer"},b("div",{className:"feed-skeleton-chip w-36"}),b("div",{className:"feed-skeleton-chip w-56"}),b("div",{className:"feed-skeleton-chip"}))))}function EL({items:e,loadingText:t,ops:n}){if(t)return b("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>b(NL,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!C.feedQuery.trim()||C.feedTypeFilter!=="all"||C.feedScopeFilter!=="all";return b("div",{className:"small feed-empty-state"},b("strong",null,r?"No memories match the current filters.":"No memories yet."),b("div",null,r?"Try clearing filters, changing the scope, or using a broader search.":"Memories and session summaries will appear here once codemem has something worth keeping."))}return b(z,null,e.map(r=>b(TL,{item:r,key:Rt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function t_({id:e,active:t,options:n,onSelect:r}){return b("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{const s=i===t;return b("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},o)}))}function AL({text:e}){return b("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function xL({query:e,onQuery:t}){return b("input",{"aria-label":"Search memories",className:"feed-search",id:"feedSearch",onInput:n=>{t(String(n.currentTarget.value||""))},placeholder:"Search title, body, tags…",type:"search",value:e})}function DL({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=x(!1);return b(z,null,b("div",{className:"feed-controls"},b(AL,{text:n||rD(t.length,r.hasMorePages())}),b("div",{className:"feed-controls-right"},b(xL,{query:C.feedQuery,onQuery:r.updateFeedQuery}),b(t_,{active:C.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==C.feedScopeFilter&&(dv(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),b(t_,{active:C.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==C.feedTypeFilter&&(rT(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),b("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>o(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),b(iD,{open:i}),b("div",{className:"feed-list",id:"feedList"},b(z,null,e?b("div",{className:"small feed-empty-state",role:"alert"},b("strong",null,e),b("div",null,"Check the viewer connection, then retry the Feed."),b("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null,!e||t.length>0?b(EL,{items:t,loadingText:n,ops:r}):null)))}function $L(e){return C.feedTypeFilter==="observations"?e.filter(t=>!Ic(t,pc(t?.metadata_json))):C.feedTypeFilter==="summaries"?e.filter(t=>Ic(t,pc(t?.metadata_json))):e}function LL(e){const t=e.map(n=>`${Hy(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${C.feedTypeFilter}|${C.feedScopeFilter}|${C.currentProject}|${Zo(C.feedQuery)}|${t.join("|")}`}var n_="",fa=0,ma=0,zi=!0,Wi=!0,kc=null,jL=0,Mt=null,r_=!1,Ji=0,bp="all",i_="",ha=null,Yi="",zU=250;function o_(e){n_=e,bp=C.feedScopeFilter,i_=C.feedQuery.trim(),Yi="",Ji+=1,fa=0,ma=0,zi=!0,Wi=!0,C.lastFeedItems=[],C.pendingFeedItems=null,C.lastFeedFilteredCount=0,C.lastFeedSignature="",C.newItemKeys.clear(),C.itemViewState.clear(),C.itemExpandState.clear()}function _p(){return zi||Wi}function OL(e){const t=Rt(e);C.lastFeedItems=C.lastFeedItems.map(n=>Rt(n)===t?e:n)}function ML(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Rt(r)),i};C.lastFeedItems=C.lastFeedItems.filter(n),Array.isArray(C.pendingFeedItems)&&(C.pendingFeedItems=C.pendingFeedItems.filter(n));for(const r of t){C.newItemKeys.delete(r),C.itemViewState.delete(r);for(const i of Array.from(C.itemExpandState.keys()))i.startsWith(`${r}:`)&&C.itemExpandState.delete(i)}}async function FL(){if(!_p())return;const e=Ji;if(kc===e)return;const t=C.currentProject||"",n=C.feedQuery.trim(),r=fa,i=ma;kc=e;try{const[o,s]=await Promise.all([zi?Kf(t,{limit:20,offset:r,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),Wi?Vf(t,{limit:50,offset:i,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==Ji||t!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(f=>!Gy(f));C.lastFeedFilteredCount+=l.length-d.length,Wi=fc(s,c.length,50),zi=fc(o,l.length,20),ma=mc(s,i+c.length),fa=mc(o,r+l.length);const u=[...c,...d],p=Ky(C.lastFeedItems,u);C.lastFeedItems=p,Jr()}finally{kc===e&&(kc=null)}}function a_(){C.activeTab==="feed"&&(ha||Mt||_p()&&I0()&&FL())}var BL={replaceFeedItem:OL,removeFeedItem:ML,updateFeedView:e=>Jr(e),loadFeedData:()=>Cp(),updateFeedQuery:e=>qL(e),hasMorePages:_p};function wp(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;J0(n,b(DL,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:BL}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Sp(e="Loading selected project..."){wp([],{loadingText:e})}function UL(){W0(),wp(C.lastFeedItems,C.lastFeedItems.length||C.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),r_||(window.addEventListener("scroll",()=>{a_()},{passive:!0}),r_=!0)}function qL(e){if(e===C.feedQuery)return;const t=C.feedQuery.trim();C.feedQuery=e,e.trim()!==t&&(o_(C.currentProject||""),Sp("Searching memories…"),ha&&clearTimeout(ha),ha=setTimeout(()=>{ha=null,Cp().catch(()=>{})},250))}function Jr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=$L(C.lastFeedItems),r=LL(n),i=e||r!==C.lastFeedSignature;C.lastFeedSignature=r,i&&wp(n,{errorText:Yi||void 0}),window.scrollTo({top:t}),a_()}async function Cp(){const e=C.currentProject||"",t=C.feedScopeFilter!==bp,n=C.feedQuery.trim(),r=n!==i_;(e!==n_||t||r)&&(o_(e),Sp(r?"Searching memories…":void 0));const i=Ji,o=++jL;Mt={generation:i,requestId:o};const s=!!Yi;s&&(Yi="",C.lastFeedItems.length>0?Jr(!0):Sp(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([Kf(e,{limit:20,offset:0,scope:C.feedScopeFilter,q:n||void 0}),Vf(e,{limit:50,offset:0,scope:C.feedScopeFilter,q:n||void 0})]);if(Mt?.generation!==i||Mt.requestId!==o||i!==Ji||e!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const p=u.items||[],f=d.items||[],m=n?f:f.filter(w=>!Gy(w)),v=f.length-m.length,g=[...p,...m].sort((w,_)=>new Date(_.created_at||0).getTime()-new Date(w.created_at||0).getTime()),h=C0(C.lastFeedItems,g),y=C.lastFeedItems;if(P0(h,y)&&y.length>0){const w=new Set(y.map(Rt));h.forEach(_=>{w.has(Rt(_))||C.newItemKeys.add(Rt(_))})}C.pendingFeedItems=null,C.lastFeedItems=h,Yi="",C.lastFeedFilteredCount=Math.max(C.lastFeedFilteredCount,v),Wi=fc(u,p.length,50),zi=fc(d,f.length,20),ma=Math.max(ma,mc(u,p.length)),fa=Math.max(fa,mc(d,f.length)),bp=C.feedScopeFilter,Mt?.generation===i&&Mt.requestId===o&&(Mt=null),Jr(s)}catch(c){throw Mt?.generation===i&&Mt.requestId===o&&i===Ji&&e===(C.currentProject||"")&&n===C.feedQuery.trim()&&(zi=!1,Wi=!1,Yi="Feed unavailable. Refresh and try again.",Jr(!0)),c}finally{Mt?.generation===i&&Mt.requestId===o&&(Mt=null)}}var GL=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function s_(e){return!!GL.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function WU(e){return e}function HL(e){return e.latest_version?e.stale?{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:s_(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function KL({status:e}){const t=HL(e),n=e.update_available||e.stale||!e.latest_version||!s_(e.current_version);return b("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},b("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),b("div",{class:"health-update-copy"},b("h2",null,t.title),b("p",null,t.detail),n&&e.recommended_action?b("p",{class:"health-update-guidance"},b("span",{class:"health-update-guidance-label"},"Recommended action"),b("code",null,e.recommended_action)):null))}function VL(e,t){e&&(e.hidden=!t,We(t?b(KL,{status:t}):null,e))}function zL({label:e,value:t,detail:n,icon:r,className:i,title:o}){const s=b("div",{class:`stat${i?` ${i}`:""}`,style:o?"cursor: help;":void 0},r?b("i",{"data-lucide":r,class:"stat-icon"}):null,b("div",{class:"stat-content"},b("div",{class:"value"},t),b("div",{class:"label"},e),n?b("div",{class:"small"},n):null));return o?b(gc,{label:o},s):s}function WL({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action()}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Oo(e.command,n)}return b("div",{class:"health-action"},b("div",{class:"health-action-text"},e.label,e.command?b("span",{class:"health-action-command"},e.command):null),b("div",{class:"health-action-buttons"},e.action?b("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?b("button",{class:"settings-button health-action-copy",onClick:o,ref:s=>{n=s}},"Copy"):null))}function JL(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function YL({label:e,value:t,icon:n,tooltip:r}){const i=b("div",{class:"stat",style:r?"cursor: help;":void 0},b("i",{"data-lucide":n,class:"stat-icon"}),b("div",{class:"stat-content"},b("div",{class:"value"},JL(t)),b("div",{class:"label"},e)));return r?b(gc,{label:r},i):i}function c_(e,t){e&&We(b(Ku,null,t.map(n=>b(YL,{...n,key:`${n.label}-${n.icon}`}))),e)}function l_(e,t){e&&We(b(z,null,t),e)}function Ip(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function XL(e,t){e&&We(b(Ku,null,t.map(n=>b(zL,{...n,key:n.key??n.label}))),e)}function QL(e,t){if(e){if(!t.length){e.hidden=!0,We(null,e);return}e.hidden=!1,We(b(z,null,t.slice(0,3).map((n,r)=>b(WL,{item:n,key:`${n.label}-${r}`}))),e)}}var d_="scope_id_backfill";function u_(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;VL(document.getElementById("healthUpdateBanner"),C.lastUpdateStatus);const i=C.lastStatsPayload||{},o=C.lastUsagePayload||{},s=C.lastRawEventsPayload&&typeof C.lastRawEventsPayload=="object"?C.lastRawEventsPayload:{},c=C.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(W=>W.kind===d_),u=i.reliability||{},p=u.counts||{},f=u.rates||{},m=i.database||{},v=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},g=Array.isArray(o.recent_packs)?o.recent_packs:[],h=g.length?g[0]?.created_at:null,y=g.length?g[0]?.metadata_json||{}:{},w=Number(y?.exact_duplicates_collapsed||0),_=Number(s.pending||0),I=Number(p.errored_batches||0),P=Number(f.flush_success_rate??1),k=Number(f.dropped_event_rate||0),A=Bu(v.tokens_saved,v.tokens_read),L=u0(A),F=Number(m.tags_coverage||0),T=String(c.daemon_state||"unknown"),M=T==="offline-peers"?"Offline peers":T==="needs_attention"?"Needs attention":T==="rebootstrapping"?"Rebootstrapping":By(T),j=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers.length:0,B=T==="disabled"||c.enabled===!1,U=T==="offline-peers",$=!B&&j===0;let E=B?"Disabled":$?"No peers":M;const S=c.last_sync_at||c.last_sync_at_utc||null,D=qi(S),H=qi(h),G=D!==null&&D>7200,oe=D!==null&&D<=300,ae=_>=200;let ee=0;const ie=[];_>=1e3?(ee+=40,ie.push("high raw-event backlog")):_>=200&&(ee+=24,ie.push("growing raw-event backlog")),I>0&&_>=200&&(ee+=I>=5?10:6,ie.push("batch errors during backlog pressure")),P<.95&&(ee+=20,ie.push("lower flush success")),k>.02?(ee+=24,ie.push("high dropped-event rate")):k>.005&&(ee+=10,ie.push("non-trivial dropped-event rate")),!B&&!$&&(T==="error"?(ee+=36,ie.push("sync daemon reports errors")):T==="needs_attention"?(ee+=40,ie.push("sync needs manual attention")):T==="stopped"?(ee+=22,ie.push("sync daemon stopped")):T==="degraded"&&!oe&&(ee+=20,ie.push("sync daemon degraded")),U?(ee+=4,ie.push("all peers currently offline"),G&&(ee+=4,ie.push("offline peers and sync not recent"))):G?(ee+=26,ie.push("sync looks stale")):D!==null&&D>1800&&(ee+=12,ie.push("sync not recent"))),L!==null&&L<10&&(ee+=8,ie.push("low retrieval reduction")),H!==null&&H>86400&&(ee+=12,ie.push("memory pack activity is old"));let Ce="Healthy",Ie="status-healthy";ee>=60?(Ce="Attention",Ie="status-attention"):ee>=25&&(Ce="Degraded",Ie="status-degraded");const Ne=Ie==="status-healthy";r&&(r.className=`health-dot ${Ie}`,r.title=Ce);const le=`${Number(v.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,ye=_>0?"Queue is actively draining":"Queue is clear",Y=B?"Sync disabled":$?"No peers configured":U?`${j} peers offline · last sync ${rr(D)} ago`:`${j} peers · last sync ${rr(D)} ago`;Ne&&!B&&!$&&(U?E="Peers offline":T==="degraded"&&oe&&(E="Syncing"));const ce=`last pack ${rr(H)} ago`,ge=l.map(W=>{const Pe=Number(W.progress?.current||0),re=typeof W.progress?.total=="number"?W.progress.total:null,je=String(W.progress?.unit||"items"),it=re&&re>0?` (${Math.round(100*Pe/re)}%)`:"",hr=re&&re>0?`${Pe.toLocaleString()}/${re.toLocaleString()} ${je}${it}`:`${Pe.toLocaleString()} ${je}`,Zt=W.status==="failed",Un=W.status==="completed",gr=W.kind===d_,me=Zt?"Failed":Un?"Complete":hr,ot=Zt?String(W.error||"unknown error").trim():Un?gr?`${hr} · one-time Sharing-domain upgrade finished`:hr:gr?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(W.kind||W.title||"background-maintenance"),label:String(W.title||W.kind||"Background maintenance"),value:me,detail:ot,icon:Zt?"alert-triangle":Un?"check-circle":"loader",className:Zt?"status-attention":void 0,title:Zt?`Error: ${W.error||"unknown"}`:Un?`${String(W.title||"Maintenance")} finished`:gr?`${String(W.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(W.title||"Maintenance")} in progress`}}),pe=[{key:"overall-health",label:"Overall health",value:Ce,detail:`Weighted score ${ee}`,icon:"heart-pulse",className:`health-primary ${Ie}`,title:ie.length?`Main signals: ${ie.join(", ")}`:"No major risk signals detected"},...ge,{key:"pipeline-health",label:"Pipeline health",value:`${_.toLocaleString()} pending`,detail:ye,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:A,detail:le,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:E,detail:Y,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:rr(H),detail:ce,icon:"clock-3",title:"Recency of last memory pack activity"}];XL(e,pe);const He=async()=>{await yl()},de=[];ae?(de.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),de.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):T==="stopped"?de.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!B&&!$&&!Ne&&(T==="error"||T==="degraded")?(de.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:He,actionLabel:"Sync now"}),de.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!B&&!$&&G&&de.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:He,actionLabel:"Sync now"}),F>0&&F<.7&&de.length<2&&de.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&de.length<3&&de.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),QL(n,de),t.textContent=ie.length?`Why this status: ${ie.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Ip()}function ZL(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=C.lastUsagePayload||{},r=C.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,o=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(P=>P.event==="pack")||null,c=Array.isArray(n?.recent_packs)?n.recent_packs:[],l=c.length?c[0]:null,d=l?.metadata_json||{},u=l?.created_at||"",p=Number(s?.count||0),f=Number(l?.tokens_read||0),m=Number(l?.tokens_saved||0),v=Number(d?.exact_duplicates_collapsed||0),g=!!d?.exact_dedupe_enabled,h=Bu(m,f),y=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${qr(u)}`:"",_=o?"Project":"All projects",I=[{label:"Last pack savings",value:l?`${Qo(m)} (${h})`:"n/a",tooltip:l?`Exact: ${m.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Qo(f):"n/a",tooltip:l?`Exact: ${f.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?v.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:l?g?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];l_(t,[_,y,w].filter(Boolean).join(" · ")),c_(e,I),Ip()}function ej(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=C.lastStatsPayload||{},r=C.lastUsagePayload||{},i=C.lastRawEventsPayload&&typeof C.lastRawEventsPayload=="object"?C.lastRawEventsPayload:{},o=n.database||{},s=C.currentProject,c=r?.totals_global||r?.totals||n.usage?.totals||{},l=r?.totals_filtered||null,d=!!(s&&l),u=d?l:c,p=Number(i.sessions||0),f=Number(i.pending||0),m=d?`
|
|
109
|
+
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",v=d?`
|
|
110
|
+
Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",g=d?`
|
|
111
|
+
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",h=[{label:d?"Savings (project)":"Savings",value:Qo(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${g}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:Qo(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${v}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:Bu(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${d0(u.tokens_saved,u.tokens_read)}.`+v+g,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Qo(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${m}`,icon:"pencil"},{label:"Active memories",value:o.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:Fy(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Fy(o.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(f>0?h.push({label:"Raw events pending",value:f,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&h.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),c_(e,h),t){const y=s?` · project: ${s}`:"",w=m0(o.path||"unknown");l_(t,`DB: ${w} · ${h0(o.size_bytes||0)}${y}`)}Ip()}async function tj(){const e=C.lastStatsPayload?.identity?.actor_id||null,t=C.activeTab==="health"&&!C.lastUpdateStatus?YC().catch(XC):Promise.resolve(C.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([ZS(),eC(C.currentProject),tC(C.currentProject),nC(C.currentProject),t]);C.lastStatsPayload=n||{},C.lastUsagePayload=r||{},C.lastRawEventsPayload=o||{},C.lastUpdateStatus=s;const c=C.lastStatsPayload?.identity?.actor_id||null;ej(),ZL(),u_(),C.activeTab==="feed"&&e!==c&&Jr(!0)}function Pp(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function p_(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function f_(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var nj={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function m_(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function rj(e){return e.targetIdentityRef??e.existingIdentityRef??""}function ij({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Cr(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,v=rj(o),g=o.targetIdentityRef??"",[h,y]=x(v);K(()=>y(v),[v]);const w=i.identityChoices.some(D=>D.identityRef===h),_=m_(i,o.existingIdentityRef),I=m_(i,o.suggestedIdentityRef),P=n?.has(o.deviceRef)??!1,k=e||P||r,A=k||!o.actions.assignIdentity.enabled,L=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!h&&!w,T=!o.actions.include.enabled||L||F||!g||h!==g,M=k||T,j=A||!h||L||F||h===g,B=!o.enabled||T,U=e?t:P?Pp("device",o.deviceRef):void 0,$=[f,B?m:void 0,U].filter(Boolean).join(" "),E=[f,U].filter(Boolean).join(" "),S=o.decision==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-device-row${S?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-device-row-${s}`,tabIndex:S?-1:void 0,children:[a("legend",{children:o.displayName}),S?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,a("div",{className:"small legacy-team-device-evidence",id:f,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),_?a("span",{children:["Current assignment: ",_,o.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!_&&I?a("span",{children:["Suggested person: ",I]}):null,a("span",{children:["Decision: ",nj[o.decision]]})]}),a("label",{htmlFor:p,children:"Person using this device"}),a("select",{"aria-describedby":$,className:"feed-search legacy-team-device-select",disabled:A,id:p,onChange:D=>y(D.currentTarget.value),value:h,children:[a("option",{value:"",children:"Choose a person"}),h&&!w?a("option",{value:h,children:"Current server assignment"}):null,i.identityChoices.map(D=>a("option",{value:D.identityRef,children:D.displayName},D.identityRef))]}),o.enabled?F?a("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):L?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!h||!g||h!==g?a("p",{className:"small",id:m,children:h?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:a("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),a("div",{className:"legacy-team-device-actions",children:[a("button",{"aria-describedby":$,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{j||c(o,h)},type:"button",children:"Save assignment"}),o.enabled?a(z,{children:[a("button",{"aria-describedby":$,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{M||d(o,"included",g)},type:"button",children:"Include"}),a("button",{"aria-describedby":E,"aria-disabled":k||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!k&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":E,"aria-disabled":k||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!k&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":E,"aria-disabled":k||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!k&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function oj(e){const t=p_(e.detail.devices);return a("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[a("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),a("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),a("div",{className:"legacy-team-device-list",children:t.map((n,r)=>b(ij,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function aj(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function sj({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=Cr(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=kr(c.mappingChoices.map($=>({canonicalId:$.resolvedProjectRef,displayName:$.displayName}))),m=[...new Set(c.mappingChoices.map($=>$.resolvedProjectRef))],v=[...m].sort(($,E)=>$<E?-1:$>E?1:0),g=new Map(v.map(($,E)=>[$,`project-choice-${E+1}`])),h=new Map(c.mappingChoices.map($=>[$.resolvedProjectRef,$])),y=m.flatMap($=>{const E=h.get($);return E?[{...E,label:f.get($)??E.displayName,token:g.get($)??""}]:[]}),w=y.find($=>$.resolvedProjectRef===p)?.token??"",_=JSON.stringify(v),[I,P]=x(w);K(()=>P(w),[w,_]);const k=y.find($=>$.token===I)?.resolvedProjectRef,A=n?.has(c.projectRef)??!1,L=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!I,T=e||A||r||!c.actions.map.enabled,M=T||!k||k===p,j=aj(c,f),B=[L||F?u:void 0,e?t:A?Pp("project",c.projectRef):void 0].filter(Boolean).join(" "),U=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${U?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:U?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[U?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?a("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):a(z,{children:[a("p",{className:"small",children:j?`Saved mapping: ${j}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a("select",{"aria-describedby":B||void 0,className:"feed-search legacy-team-project-select",disabled:T,id:d,onChange:$=>P($.currentTarget.value),value:I,children:[a("option",{value:"",children:"Choose a Project"}),y.map($=>a("option",{value:$.token,children:$.label},$.resolvedProjectRef))]}),L?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":B||void 0,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!M&&k&&o(c,k)},type:"button",children:"Save mapping"})]})]})]})}function cj(e){const t=f_(e.detail.projects),n=kr(t.map(o=>({canonicalId:o.projectRef,displayName:o.displayName}))),r=e.detail.projects.filter(o=>o.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return a("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[a("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),a("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?a("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,a("div",{className:"legacy-team-project-list",children:t.map((o,s)=>a(sj,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(o.projectRef),index:s,onMap:e.onMap,presentationName:n.get(o.projectRef)??o.displayName,project:o},o.projectRef))}),e.detail.unresolvedProjectCount===0?a("div",{className:"legacy-team-setup-next-action",children:[a("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),a("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var ga={add:"Add",update:"Update",remove:"Remove"},lj=10;function pt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Rp(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${Po(s)}`,d=n(o),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function kp(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${pt(e.projectRefs.size,t)}`:e.displayName}function va({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>lj;return a("section",{children:[a("h4",{children:i}),n.length>0?a(z,{children:[o&&r?a("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>a("li",{children:c},`${i}-summary-${l}`))}):null,s?a("details",{children:[a("summary",{children:["Show all ",pt(n.length,`exact ${t}`)]}),a(h_,{items:n,title:i})]}):a(h_,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function h_({items:e,title:t}){return a("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>a("li",{children:n},`${t}-${r}`))})}function dj({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const o=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=x(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),f=o.teamChanges.map(S=>{const D=S.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":S.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${ga[S.change]} ${S.teamDisplayName}: change device access from ${D} to the reviewed device list.`}),m=o.membershipChanges.map(S=>`${ga[S.change]} ${S.identityDisplayName} ${S.change==="remove"?"from":"to"} ${S.teamDisplayName}.`),v=kr([...n.projects.map(S=>({canonicalId:S.projectRef,displayName:S.displayName})),...o.projectChanges.map(S=>({canonicalId:S.projectRef,displayName:S.projectDisplayName}))]),g=o.projectChanges.flatMap(S=>[...S.fromResolvedProjectRef&&S.fromResolvedProjectDisplayName?[{canonicalProjectRef:S.fromCanonicalProjectRef,resolvedProjectRef:S.fromResolvedProjectRef,displayName:S.fromResolvedProjectDisplayName}]:[],...S.toResolvedProjectRef&&S.toResolvedProjectDisplayName?[{canonicalProjectRef:S.toCanonicalProjectRef,resolvedProjectRef:S.toResolvedProjectRef,displayName:S.toResolvedProjectDisplayName}]:[]]),h=kr(g.map(S=>({canonicalId:S.canonicalProjectRef??S.resolvedProjectRef,displayName:S.displayName}))),y=new Map(g.map(S=>[S.resolvedProjectRef,h.get(S.canonicalProjectRef??S.resolvedProjectRef)??S.displayName])),w=kr([...n.projects.flatMap(S=>S.canonicalProjectRef?[{canonicalId:S.canonicalProjectRef,displayName:S.displayName}]:[]),...[...o.recipientChanges,...o.deviceAccessChanges].filter(S=>S.canonicalProjectKind==="project").map(S=>({canonicalId:S.canonicalProjectRef,displayName:S.canonicalProjectDisplayName}))]),_=o.projectChanges.map(S=>`${ga[S.change]} ${v.get(S.projectRef)??S.projectDisplayName}: ${S.fromResolvedProjectRef?y.get(S.fromResolvedProjectRef)??S.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${S.toResolvedProjectRef?y.get(S.toResolvedProjectRef)??S.toResolvedProjectDisplayName??"no Project":"no Project"}.`),I=o.recipientChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.change==="remove"?"Stop":"Start"} using legacy default sharing for ${S.recipientDisplayName}.`:`${ga[S.change]} ${S.recipientDisplayName} ${S.change==="remove"?"from":"as"} a recipient for ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),P=o.deviceAccessChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.deviceDisplayName} ${S.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${ga[S.change]} ${S.deviceDisplayName} access ${S.change==="remove"?"from":"to"} ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),k=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,A=Rp(o.projectChanges,S=>S.projectDisplayName,S=>S.projectRef,()=>"project"),L=Rp(o.recipientChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),F=Rp(o.deviceAccessChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),T=n.devices.filter(S=>S.decision==="included").length,M=[pt(o.teamChanges.length,"Team policy change"),pt(o.membershipChanges.length,"membership change"),pt(o.projectChanges.length,"Project change"),pt(o.recipientChanges.length,"recipient change"),pt(o.deviceAccessChanges.length,"device-access change")],j=`${pt(n.projects.length,"Project")} included; ${pt(T,"included device")}.`,B=Math.max(n.candidate.projectCount,n.projects.length),U=new Set(o.deviceAccessChanges.map(S=>S.deviceRef)).size,$=[...o.teamChanges,...o.membershipChanges,...o.projectChanges,...o.recipientChanges,...o.deviceAccessChanges].filter(S=>S.change==="remove").length,E=o.teamChanges.length===0&&o.membershipChanges.length===0&&o.projectChanges.length===0&&o.recipientChanges.length>0&&o.recipientChanges.every(S=>S.change==="remove"&&S.canonicalProjectKind==="legacy_default_sharing")&&o.deviceAccessChanges.every(S=>S.change==="remove"&&S.canonicalProjectKind==="legacy_default_sharing")?`No new access will be added. This removes legacy default sharing for ${n.candidate.displayName}.${U>0?` ${pt(U,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${pt(B,"reviewed Project")}.`:`${pt(k,"server-confirmed access change")} will be applied atomically; ${pt($,"removal")} ${$===1?"is":"are"} included.`;return a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:"Review every server-confirmed access change before activating this Team."}),a("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[a("p",{className:"legacy-team-setup-net-effect",children:[a("strong",{children:"Net effect:"})," ",E]}),a("p",{children:[a("strong",{children:pt(k,"exact access change")})," to review."]}),a("ul",{children:M.map(S=>a("li",{children:S},S))}),a("p",{className:"small",children:["Scope: ",j]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(va,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),a(va,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(va,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:_,summaryItems:A.map(S=>`${kp(S,"reviewed Project")}, ${pt(S.changeCount,"Project change")}`),title:"Projects"}),a(va,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:I,summaryItems:L.map(S=>`${kp(S,"canonical Project")}, ${pt(S.changeCount,"recipient change")}`),title:"Recipients"}),a(va,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:P,summaryItems:F.map(S=>`${kp(S,"canonical Project")}, ${pt(S.changeCount,"device-access change")}`),title:"Device access"})]}),a("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[a("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:S=>{e&&S.preventDefault()},onChange:S=>{if(e){S.currentTarget.checked=d;return}l(S.currentTarget.checked?s:null)},type:"checkbox"}),a("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?a("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[a("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,a("button",{"aria-describedby":p||void 0,"aria-disabled":u?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{u||i(n)},type:"button",children:r?"Finishing Team setup…":"Finish Team setup"})]})}function uj(e){let t=null;return async n=>{try{const r=await pj(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){let i,o;try{i=await fj(n,e,r)}catch(s){o=s}return{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}}}async function pj(e,t,n,r){switch(e.kind){case"load":return e.refresh?t.refreshCandidate(e.candidateRef):t.loadDetail(e.candidateRef);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function fj(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Ht)||!Tp(n.errorCode))&&!(e.kind==="load"&&(e.refresh||n.errorCode!=="team_setup_confirmation_stale")))return t.loadDetail(e.candidateRef)}function Tp(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function g_(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function mj(e,t,n){return y_(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function v_(e,t){return y_(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function y_(e,t){return{id:e,targetId:t}}var b_="Team setup changed since it was last reviewed. Reload the latest details to continue.",__="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",hj="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",gj="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",vj="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",yj="Another device completed this Team with different reviewed details. Retry to load the completed setup.",bj="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function _j(){return{status:"closed",generation:0}}function Np(e,t){switch(t.type){case"open":return e.status==="open"&&Mn(e)?e:wj(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Mn(e)?e:{status:"closed",generation:e.generation+1};case"close_blocked":case"open_blocked":return e.status==="open"?{...e,message:t.message}:e;case"navigate":return Sj(e,t.step);case"blocked_navigation":return Tc(e,t.step,t.message);case"retry":return Cj(e);case"refresh":return Pj(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Ep(e,t,"assign_device");case"decide_device":return Ep(e,t,"decide_device");case"clear_device":return Ep(e,t,"clear_device");case"map_project":return Ij(e,t);case"finish":return Rj(e);case"command_started":return Fj(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return kj(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function wj(e,t){return sr({status:"open",generation:e,candidateRef:t,view:null,step:"devices",projectsVisitedAttemptId:null,commands:[],nextCommandId:1,errors:[],message:"",focus:null,nextFocusId:1},{kind:"load",candidateRef:t,refresh:!1,focusOnOutcome:!1})}function Sj(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return Tc(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return Tc(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return Tc(e,"projects","Finish the Project mappings before reviewing access.");const n=t==="projects"&&e.view?e.view.attemptId:e.projectsVisitedAttemptId;return{...e,step:t,projectsVisitedAttemptId:n,focus:g_(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function Tc(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?p_(e.view.devices).findIndex(i=>i.decision==="unresolved"):f_(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:mj(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function Cj(e){if(e.status!=="open"||e.step==="completed"||ya(e)||Mn(e))return e;const t=Nc(e)?.retry??e.errors.find(n=>n.retry)?.retry??"load";return sr(e,{kind:"load",candidateRef:e.candidateRef,refresh:t==="refresh",focusOnOutcome:!0})}function Ep(e,t,n){if(e.status!=="open"||e.step==="completed"||!Ap(e.view)||Nc(e)||ya(e)||Mn(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return sr(Yr(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function Ij(e,t){if(e.status!=="open"||e.step==="completed"||!Ap(e.view)||Nc(e)||ya(e)||Mn(e))return e;const n=e.view.projects.find(r=>r.projectRef===t.projectRef);return!n?.actions.map.enabled||!n.mappingChoices.some(r=>r.resolvedProjectRef===t.resolvedProjectRef)?e:sr(Yr(e,{kind:"project",itemRef:t.projectRef}),{kind:"map_project",candidateRef:e.candidateRef,projectRef:t.projectRef,input:{attemptId:e.view.attemptId,resolvedProjectRef:t.resolvedProjectRef}},`Saving the mapping for ${n.displayName}.`)}function Pj(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||ya(e)||Mn(e)?e:sr(Yr(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function Rj(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:sr(Yr(e,{kind:"global"}),{kind:"finish",candidateRef:e.candidateRef,attemptId:e.view.attemptId,input:{attemptId:e.view.attemptId,finishDigest:e.view.finishDigest,confirmedAccessDeltaDigest:e.view.accessDeltaDigest,confirmedViewerAccessDeltaDigest:e.view.viewerAccessDeltaDigest}},"Finishing Team setup.")}function sr(e,t,n=e.message){const r=`${e.generation}:${e.nextCommandId}`;return{...e,commands:[...e.commands,{...t,generation:e.generation,id:r,status:"pending"}],nextCommandId:e.nextCommandId+1,message:n}}function kj(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return t.status==="failure"?Nj(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?Ej(r,n.attemptId):t.view?w_({...Mj(r,n),message:Tj(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function Tj(e,t){if(e.kind==="refresh")return"Team setup refreshed.";if(e.kind==="load")return"";if("deviceRef"in e){const n=t?.devices.find(r=>r.deviceRef===e.deviceRef)?.displayName;return n?`${n} saved.`:"Device saved."}if("projectRef"in e){const n=t?.projects.find(r=>r.projectRef===e.projectRef)?.displayName;return n?`${n} saved.`:"Project mapping saved."}return""}function Nj(e,t,n){if(t.kind==="completion_refresh")return{...e,message:"Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control."};const r=n.recoveredView?w_(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=Aj(t,n.cause,n.recoveryCause),o={...r,errors:[...Yr(r,i.scope).errors,i],message:""};return t.kind!=="load"||!t.focusOnOutcome?o:{...o,focus:v_(o.nextFocusId,{hasError:!0,recovery:o.view?.state==="unavailable",step:o.step}),nextFocusId:o.nextFocusId+1}}function w_(e,t,n){const r=jj(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:Oj(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:o,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=o.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:v_(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!P_(s,t.attemptId)&&(s=sr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function Ej(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:g_(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return P_(n,t)||(n=sr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function Aj(e,t,n){const r=t instanceof Ht&&Tp(t.errorCode),i=t instanceof Ht&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=$j({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i});return{scope:xj(e,{globalError:r||i||o!==null}),message:s,retry:Dj(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null})}}function xj(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function Dj(e,t,n,r){return t instanceof Ht&&t.errorCode==="team_setup_confirmation_stale"||n instanceof Ht&&n.errorCode==="team_setup_confirmation_stale"||r.terminalRecovery?"load":r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load"}function $j(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Ht?xp(n.errorCode):null,c=Lj(r instanceof Ht?xp(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?vj:C_(l);return c?{completionCode:l,message:d??S_(t.kind),terminalRecoveryCode:c}:i?{completionCode:l,message:b_,terminalRecoveryCode:c}:o?{completionCode:l,message:t.kind==="finish"?hj:__,terminalRecoveryCode:c}:{completionCode:l,message:d??S_(t.kind),terminalRecoveryCode:c}}function Lj(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function S_(e){switch(e){case"load":return"Team setup details are temporarily unavailable. Retry to load the latest details.";case"assign_device":case"decide_device":case"clear_device":return"This device change could not be saved. Reload the latest details before trying again.";case"map_project":return"This Project mapping could not be saved. Reload the latest details before trying again.";case"refresh":return"Team setup could not be refreshed. Retry to load the latest server details.";case"finish":return"Team setup could not be finished. Reload the latest details before trying again.";case"completion_refresh":return"Team setup completed, but dependent views could not be refreshed.";default:return e}}function jj(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function Ap(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Mn(e){return e.commands.some(t=>t.kind==="load"&&t.refresh||["refresh","assign_device","decide_device","clear_device","map_project","finish"].includes(t.kind))}function ya(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function Nc(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function Oj(e){if(Tp(e))return b_;if(e==="team_setup_roster_unavailable")return __;const t=C_(xp(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function xp(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function C_(e){return e==="team_setup_completion_unavailable"?gj:e==="team_setup_completion_conflict"?yj:e==="team_setup_completion_invalid"?bj:null}function I_(e){return e.kind==="global"||e.kind==="load"}function Yr(e,t){const n=I_(t);return{...e,errors:e.errors.filter(r=>n?!I_(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function Mj(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?Yr(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?Yr(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function Fj(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function P_(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var Bj={role:"list"},Uj={role:"listitem"};function qj(e){const t=e.session,n=t.view,r=Nc(t),i=t.commands.some(_=>_.kind==="load"),o=ya(t)||Mn(t),s=t.commands.some(_=>_.kind==="finish"),c=n?.state==="unavailable"||r?.retry==="refresh",l=r!=null&&(!n||c),d=!Ap(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,p=n?`Set up ${n.candidate.displayName}`:"Set up Team",f=t.errors.filter(_=>_.scope.kind==="device"||_.scope.kind==="project"),m=f.length>0,v=f.some(_=>_.retry==="refresh"),g=new Set(f.flatMap(_=>_.scope.kind==="device"?[_.scope.itemRef]:[])),h=new Set(f.flatMap(_=>_.scope.kind==="project"?[_.scope.itemRef]:[])),y=new Set(t.commands.flatMap(_=>"deviceRef"in _?[_.deviceRef]:[])),w=new Set(t.commands.flatMap(_=>"projectRef"in _?[_.projectRef]:[]));return a(Rr,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:e.onCloseAutoFocus,onOpenAutoFocus:e.onOpenAutoFocus,onOpenChange:_=>{_||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:a("div",{"aria-busy":o?"true":"false",className:"modal-card legacy-team-setup-card",children:[a("div",{className:"modal-header",children:[a("div",{id:"legacy-team-setup-title",tabIndex:-1,children:a(tR,{children:p})}),a(ui,{ariaDisabled:o,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[f.map(_=>a("p",{"aria-live":"assertive",id:"itemRef"in _.scope?Pp(_.scope.kind,_.scope.itemRef):void 0,role:"alert",children:_.message},"itemRef"in _.scope?`${_.scope.kind}:${_.scope.itemRef}`:_.scope.kind)),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?v?"Refreshing…":"Retrying…":v?"Refresh Team setup":"Retry"})]}):null,n?a(z,{children:[t.step!=="completed"&&!l?a(Gj,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?a(oj,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:g,busyDeviceRefs:y,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(cj,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:h,busyProjectRefs:w,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(dj,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(Hj,{busy:o,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),a("div",{className:"modal-footer legacy-team-setup-actions",children:a("button",{"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function Gj(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(z,{children:[a("ol",{...Bj,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,o)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return b("li",{...Uj,className:"legacy-team-setup-step",key:i.step},a("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:o+1}),a("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${o+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?a("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?a("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function Hj(e){return e.step==="completed"?a("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[a("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),a("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),a("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?a("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var Kj={clearDecision:CC,finish:RC,loadDetail:_C,onCompleted:()=>{},refreshCandidate:PC,saveAssignment:wC,saveDecision:SC,saveProjectMapping:IC},Dp="codemem:open-legacy-team-setup";function R_(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(Dp,{detail:t})),t.handled}function Vj(e){if(!e?.isConnected||e.tabIndex<0||e.matches(":disabled")||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;for(let t=e;t;t=t.parentElement){const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!1}return!0}function zj({dependencies:e}){const[t,n]=x(_j),r=q(null),i=Re(()=>uj(e),[e]),o=l=>{n(d=>Np(d,l))};return It(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Mn(p)?Np(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Np(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(Dp,l),()=>{window.removeEventListener(Dp,l)}},[]),K(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))o({type:"command_started",id:l.id}),i(l).then(d=>o({type:"effect_outcome",outcome:d}))},[i,t]),K(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),o({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:a(qj,{session:t,onAssign:(l,d)=>o({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>o({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(Mn(t)){o({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}o({type:"close"})},onCloseAutoFocus:l=>Jj(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){o({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}o({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>o({type:"finish"}),onMap:(l,d)=>o({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>o({type:"navigate",step:l}),onOpenAutoFocus:Wj,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var Wj=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function Jj(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(Vj(t.current)?t.current:n)?.focus(),t.current=null}function Yj(e,t={}){const n={...Kj,...t};We(a(zj,{dependencies:n}),e)}var ba=new WeakMap;function cr(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function Xj(e,t){const n=document.createElement("article");n.className="project-inventory-row recipient-policy-blocked-item";const r=document.createElement("div");r.className="project-inventory-row-header";const i=document.createElement("h3");i.className="project-inventory-title",i.textContent=e.finding;const o=document.createElement("span");o.className="project-status-badge needs_attention",o.textContent="Blocked",r.append(i,o);const s=cr(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,cr(e.reason,"project-inventory-meta"),s,cr(`Owner: ${e.ownerLabel}`,"settings-note")),t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0)){const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent=e.repair.label,c.setAttribute("aria-describedby",s.id),c.addEventListener("click",async()=>{c.disabled=!0;try{await t.onRepair?.(e.repair)}finally{c.disabled=!1}}),n.appendChild(c)}else n.appendChild(cr("Open Projects to repair this item.","settings-note"));return n}function Qj(e,t,n={}){const r=`review:${t.blockedItems.map(s=>n.onRepair&&(n.isRepairAvailable?.(s.repair)??!0)?"1":"0").join("")}:${JSON.stringify(t)}`;if(ba.get(e)===r)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,ba.set(e,r);return}e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review",i.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const o=document.createElement("h2");if(o.id="recipientPolicyReviewTitle",o.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",i.appendChild(o),t.continuity){const s=t.continuity.findingCount,c=cr(`${s.toLocaleString()} older sharing finding${s===1?" was":"s were"} not changed because Codemem could not safely translate ${s===1?"it":"them"} automatically.`,"settings-note");c.setAttribute("role","status"),c.setAttribute("aria-live","polite"),t.blockedItems.length===0&&i.appendChild(cr("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),i.appendChild(c)}if(t.blockedItems.length>0){const s=cr("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),c=document.createElement("h3");c.className="recipient-policy-blocked-heading",c.textContent="Needs repair";const l=document.createElement("div");l.className="project-inventory-list recipient-policy-review-list";for(const d of t.blockedItems)l.appendChild(Xj(d,n));i.append(s,c,l)}e.replaceChildren(i),ba.set(e,r)}function Zj(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(ba.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const o=document.createElement("h2");o.textContent="Recipient migration review";const s=cr(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),ba.set(e,r)}var k_=[["","All projects"],["needs_attention","Needs review"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","Received from peers"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],yt=null,Ft=0,Ec=250,eO=100,$p=[],Ac=new Set,xc=new Set,Dc=new Map,$c=new Map,Xr=new Map,_a=new Map,Lc=!1,wa=new Map,Sa=!1,lr=!1,Xi=0,Fn=0,Ca=0,Qi=null,Ia=null,Bt=new Set,T_=new WeakMap,jc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Zi=jc,dr=!1,Lp;function jp(e=!1){if(!e&&Ia)return Ia;const t=nm().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return Ia=t,t.then(()=>{Ia===t&&(Ia=null)}),t}function De(e){return document.getElementById(e)}function tO(e){return k_.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function nO(e){switch(e){case"exact_mapping":return"assigned to a Space";case"pattern_mapping":return"assigned by matching rule";case"explicit_override":return"manually assigned";default:return"stays on this device"}}function mn(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Oc(e){return e.identity_source!=="unmapped"&&!mn(e)}function rO(e){const t=wa.get(e.workspace_identity);(!t||mn(t)&&!mn(e))&&wa.set(e.workspace_identity,e)}function Op(e){return mn(e)?"Received from peers":Fc(e.resolved_scope_id)}function iO(e){return mn(e)?"source-owned project":nO(e.resolution_reason)}function oO(e){const t=e.person.display_name;switch(e.lifecycle.state){case"waiting_for_acceptance":return`Invitation sent to ${t}`;case"active":return`Shared with ${t}`;case"waiting_for_device":return`Sharing with ${t}`;case"needs_attention":return`Sharing with ${t} needs attention`;case"revoking":return`Removing sharing with ${t}`;case"revoked":return`Previously shared with ${t}`;case"cancelled":return`Invitation to ${t} cancelled`;default:return`Setting up sharing with ${t}`}}function N_(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function E_(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Qr(){const e=Bt.size,t=De("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!lr||!dr,t.classList.add("project-selection-target"));const n=De("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`);for(const r of document.querySelectorAll(".project-selection-checkbox")){const i=T_.get(r)??[],o=i.filter(s=>Bt.has(s)).length;r.checked=i.length>0&&o===i.length,r.indeterminate=o>0&&o<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!lr||!dr}function aO(e){const t=e.every(n=>Bt.has(n));for(const n of e)t?Bt.delete(n):Bt.add(n);Qr()}function A_(e,t){const n=E_(e),r=document.createElement("label");r.className="project-selection-control project-selection-target";const i=document.createElement("input");i.className="project-selection-checkbox",i.dataset.projectFocusKey=`select:${n.join("|")}`,i.type="checkbox",i.setAttribute("aria-label",t),T_.set(i,n),i.addEventListener("change",()=>aO(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function sO(e){if(!dr)return[];const t=new Set(e),n=new Map(Zi.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(Zi.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of Zi.projectRecipients)if(!(o.status!=="active"||!t.has(o.canonicalProjectIdentity)))if(o.recipientKind==="team"){const s=n.get(o.teamId);s&&i.set(`team:${o.teamId}`,{key:`team:${o.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(o.identityId);s&&i.set(`identity:${o.identityId}`,{key:`identity:${o.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((o,s)=>`${o.kind}:${o.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function x_(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=sO(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=dr?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const o of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${o.kind.toLowerCase()}`,s.textContent=`${o.kind}: ${o.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function D_(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!lr||!dr,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{To({mode:"project-manage",projectId:e[0]})})):(n.textContent="Share selected",n.setAttribute("aria-label",`Share selected identities for ${t}`),n.dataset.projectFocusKey=`share:${e.join("|")}`,n.addEventListener("click",()=>{for(const r of e)Bt.add(r);Qr(),To({mode:"project-add",projectIds:[...e].sort()})})),n}function cO(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Mp(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Fp(e){return e.project||e.display_project||"Unnamed Project"}function $_(e){const t=String(e||"").trim();return t?C.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function lO(){return new Set(C.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function dO(e){return!Sa||e.authority_type!=="coordinator"||!e.group_id?!1:!lO().has(String(e.group_id).trim())}function Mc(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function L_(){Lc&&(Lc=!1,yt?.())}async function uO(){let e;try{const t=await ul();e=t&&typeof t=="object"?t:null}catch{C.lastProjectCoordinatorAdminGroups=[],Sa=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){C.lastProjectCoordinatorAdminGroups=[],Sa=!1;return}try{const t=await Uf(!1);C.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],Sa=!0}catch{C.lastProjectCoordinatorAdminGroups=[],Sa=!1}}function pO(e){return e.kind==="team_default"}function Bp(e){const t=e.label||"Untitled Space";return pO(e)?`${t} (default)`:t}function fO(e,t){const n=Bp(e);return t.some(r=>r.scope_id!==e.scope_id&&Bp(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function mO(e){const t=$_(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Space":`${e.authority_type||"Other"} Space`}function hO(e){return e?$p.find(t=>t.scope_id===e)??null:null}function Fc(e){const t=hO(e);return e?t?`${Bp(t)} · ${mO(t)}`:"Unknown Space":"—"}function Up(){return $p.filter(e=>e.scope_id!=="legacy-shared-review"&&!dO(e))}function gO(e){return Up().some(t=>t.scope_id===e)}function j_(...e){for(const t of e)if(t&&gO(t))return t;return e.find(t=>!!t)??""}function vO(e){const t=$_(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function yO(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function bO(){const e=new Map;for(const t of Up()){const n=yO(t),r=vO(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function O_(e){for(const t of bO()){const n=document.createElement("optgroup");n.label=t.label;for(const r of t.scopes){const i=document.createElement("option");i.value=r.scope_id,i.textContent=fO(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function _O(e){switch(e.code){case"unknown_project_local_only":return"Current behavior";case"basename_collision_review":return"Name collision";case"scope_reassignment_old_copies":return"Previous copies";case"broad_org_domain_pattern":case"home_directory_org_domain_pattern":return"Broad mapping";default:return"Review item"}}async function qp(e,t,n=[]){try{await MC({...e.mapping_id&&e.resolution_reason==="exact_mapping"?{id:e.mapping_id}:{},...n.length>0?{confirmed_guardrail_tokens:n}:{},project_pattern:e.display_project,scope_id:t,workspace_identity:e.workspace_identity}),Xr.delete(e.workspace_identity),Dc.delete(e.workspace_identity),Q("Project Space assignment updated. Device access grants are unchanged."),yt?.()}catch(r){if(r instanceof qa){Xr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),yt?.();return}Q(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function wO(e,t){const n=e.filter(Oc);if(n.length!==0)try{await FC({mappings:n.map(r=>({...r.mapping_id&&r.resolution_reason==="exact_mapping"?{id:r.mapping_id}:{},project_pattern:r.display_project,scope_id:t,workspace_identity:r.workspace_identity}))}),Q(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),$c.delete(Mp(n[0])),yt?.()}catch(r){Q(r instanceof qa?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":r instanceof Error?r.message:"Unable to update project Spaces.","warning")}}async function SO(e){if(e.mapping_id!=null)try{await BC(e.mapping_id),Xr.delete(e.workspace_identity),Dc.delete(e.workspace_identity),Q("Project Space assignment removed. The next fallback now applies."),yt?.()}catch(t){Q(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function M_(e,t=!1){try{const n=_a.get(e.workspace_identity),r=await qC({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});_a.delete(e.workspace_identity),Q(`Forgot ${r.forgotten_memory_count.toLocaleString()} local memor${r.forgotten_memory_count===1?"y":"ies"}. ${r.peer_owned_memory_count.toLocaleString()} peer-owned memor${r.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),yt?.()}catch(n){if(n instanceof Xf){_a.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),yt?.();return}Q(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function F_(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Fa()).filter(i=>i&&i!==t)}catch{}const r=await Du({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const o=i.trim();return o?o===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await UC({project:r.trim(),workspace_identity:e.workspace_identity});Q(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),yt?.()}catch(i){Q(i instanceof Error?i.message:"Unable to change project.","warning")}}async function CO(e){const t=wa.get(e);if(t&&!mn(t))return{offset:Ft,project:t};try{let n=0,r=0;for(;;){const i=await ho({limit:Ec,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!mn(c));if(o)return{offset:i.offset,project:o};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=eO)return null;n=s}}catch{return null}}function B_(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(o=>o.dataset.projectWorkspaceIdentity===e&&o.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.closest(".project-inventory-cluster"),i=r?.querySelector(":scope > .project-inventory-details");if(i){i.open=!0;const o=r?.dataset.projectClusterKey;o&&xc.add(o)}return n.open=!0,Ac.add(`${t.dataset.projectRepairable}:${e}`),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}async function IO(e){if(Mc()){Q("Finish the open Space assignment, then try Repair again.","warning");return}const t=Fn,n=De("projectsSearch")?.value??"",r=De("projectsStatusFilter")?.value??"",i=Ft,o=await CO(e.projectIdentity);if(Fn!==t||(De("projectsSearch")?.value??"")!==n||(De("projectsStatusFilter")?.value??"")!==r||Ft!==i)return;if(Mc()){Q("Finish the open Space assignment, then try Repair again.","warning");return}if(!o){Q("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:s}=o;if(e.kind==="reassign_project"){if(s.identity_source==="unmapped"||s.session_count===0){Q("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await F_(s);return}if(!B_(s.workspace_identity)){const c=De("projectsSearch"),l=c?.value??"",d=s.workspace_identity;c&&(c.value=d);const u=De("projectsStatusFilter"),p=u?.value??"",f="";u&&(u.value=f);const m=Ft;Ft=o.offset;const v=Fn;if(await Pa(),!B_(s.workspace_identity)){if(Fn!==v||c&&c.value!==d||u&&u.value!==f||Ft!==o.offset)return;c&&(c.value=l),u&&(u.value=p),Ft=m,await Pa(),Q("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function PO(e){const t=Fn,n=(Qi?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Fn===t)try{await IO(e)}catch(r){Q(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Qi=n,n.then(()=>{Qi===n&&(Qi=null)},()=>{Qi===n&&(Qi=null)}),n}function RO(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Oc(e)&&e.memory_count!=null&&e.guardrail_warnings.every(m=>!m.requires_confirmation)){const m=document.createElement("button");m.className="settings-button",m.type="button",m.textContent="Share",m.disabled=!lr,lr||(m.title="The complete project list is unavailable."),m.addEventListener("click",()=>hs([e.workspace_identity])),t.appendChild(m)}if(mn(e)){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(m),t}if(e.identity_source==="unmapped"){const m=document.createElement("div");return m.className="settings-note",m.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(m),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const o=Up().some(m=>m.scope_id===e.resolved_scope_id);if(!o&&e.resolved_scope_id){const m=document.createElement("option");m.value=e.resolved_scope_id,m.textContent=`${Fc(e.resolved_scope_id)} — not assignable`,m.disabled=!0,i.appendChild(m)}O_(i),i.value=j_(Dc.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!o,s.addEventListener("click",()=>{qp(e,i.value)}),i.addEventListener("change",()=>{Dc.set(e.workspace_identity,i.value),Xr.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,yt?.()}),i.addEventListener("blur",L_);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{qp(e,"local-default")});const l=document.createElement("button");l.className="settings-button",l.type="button",l.textContent="Remove mapping",l.disabled=e.mapping_id==null||e.resolution_reason!=="exact_mapping",l.addEventListener("click",()=>{SO(e)});const d=document.createElement("button");d.className="settings-button",d.type="button",d.textContent="Change project…",d.disabled=e.session_count===0,d.disabled&&(d.title="No sessions are available to reassign for this saved mapping."),d.addEventListener("click",()=>{F_(e)});const u=document.createElement("button");u.className="settings-button danger",u.type="button",u.textContent="Forget local memories…",u.disabled=(e.memory_count??0)===0,u.addEventListener("click",()=>{M_(e)}),t.append(n,i,s,c,l,d,u);const p=Xr.get(e.workspace_identity);if(p){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirmation required before saving this Space.";const g=document.createElement("p");g.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const h=document.createElement("ul");for(const _ of p.warnings){const I=document.createElement("li"),P=document.createElement("strong");P.textContent=`${_O(_)}: `;const k=document.createElement("span");k.textContent=_.message,I.append(P,k),h.appendChild(I)}const y=document.createElement("button");y.className="settings-button",y.type="button",y.textContent="I understand, save Space",y.addEventListener("click",()=>{const _=Xr.get(e.workspace_identity);!_||_.scopeId!==i.value||qp(e,_.scopeId,_.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{Xr.delete(e.workspace_identity),yt?.()}),m.append(v,g,h,y,w),t.appendChild(m)}const f=_a.get(e.workspace_identity);if(f){const m=document.createElement("div");m.className="settings-note project-guardrail-confirmation",m.setAttribute("role","alert");const v=document.createElement("strong");v.textContent="Confirm project memory cleanup.";const g=document.createElement("p");g.textContent=`${f.localOwnedMemoryCount.toLocaleString()} locally owned memor${f.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${f.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${f.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const h=document.createElement("p");h.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const y=document.createElement("button");y.className="settings-button danger",y.type="button",y.textContent="I understand, forget local memories",y.addEventListener("click",()=>{M_(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{_a.delete(e.workspace_identity),yt?.()}),m.append(v,g,h,y,w),t.appendChild(m)}return t}function U_(e){const t=document.createElement("article");t.className="project-inventory-row",t.dataset.projectWorkspaceIdentity=e.workspace_identity,t.dataset.projectRepairable=String(Oc(e));const n=`project-title-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;t.setAttribute("aria-labelledby",n);const r=document.createElement("div");r.className="project-inventory-row-header",ps(e)&&r.appendChild(A_([e],`Select ${e.display_project} for recipient sharing`));const i=document.createElement("h3");i.className="project-inventory-title",i.id=n,i.textContent=e.display_project,r.appendChild(i),ps(e)&&r.appendChild(D_([e.workspace_identity],e.display_project)),t.appendChild(r);const o=document.createElement("div");o.className="project-inventory-meta",o.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${N_(e.latest_session_at)}`,t.appendChild(o),t.appendChild(x_([e.workspace_identity]));const s=document.createElement("div");s.className="project-advanced-administration";const c=document.createElement("div");c.className="project-inventory-domain",c.textContent=Op(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${iO(e)} · ${e.identity_source} · ${N_(e.latest_session_at)}`,s.appendChild(l),e.sharing&&e.sharing.length>0){const h=document.createElement("div");h.className="settings-note project-sharing-summary";const y=document.createElement("strong");y.textContent="Project sharing";const w=document.createElement("ul");w.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const _ of e.sharing){const I=document.createElement("li"),P=document.createElement("strong");P.textContent=oO(_);const k=document.createElement("span");k.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,I.append(P,k),w.appendChild(I)}h.append(y,w),s.appendChild(h)}if(mn(e)){const h=document.createElement("div");h.className="settings-note",h.textContent="Received memories keep the source device's project and Space assignment. Local reassignment controls are disabled here to avoid split-brain sync state.",s.appendChild(h)}const d=document.createElement("div");if(d.className="project-inventory-signal mono",d.textContent=cO(e),s.appendChild(d),e.suggested_scope_id&&e.suggested_scope_id!==e.resolved_scope_id){const h=document.createElement("div");h.className="settings-note project-suggestion-note",h.textContent=e.suggestion_reason?`Suggestion: ${e.suggestion_reason}`:`Suggestion: assign this project to ${Fc(e.suggested_scope_id)}.`,s.appendChild(h)}const u=(e.guardrail_warnings??[]).filter(h=>h.severity==="warning");if(u.length>0){const h=document.createElement("div");h.className="settings-note project-attention-note",h.textContent=`Needs attention: ${u.map(y=>y.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const y of e.statuses){const w=document.createElement("span");w.className=`project-status-badge ${y}`,w.textContent=tO(y),h.appendChild(w)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details";const f=`${t.dataset.projectRepairable}:${e.workspace_identity}`;p.open=Ac.has(f),p.addEventListener("toggle",()=>{p.open?Ac.add(f):Ac.delete(f)});const m=document.createElement("summary");m.dataset.projectFocusKey=`admin:${t.dataset.projectRepairable}:${e.workspace_identity}`,m.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(m),p.appendChild(s);const v=document.createElement("dl");v.className="project-detail-grid";const g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",Op(e)],["Suggested Space",e.suggested_scope_id?Fc(e.suggested_scope_id):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]];for(const[h,y]of g){const w=document.createElement("dt");w.textContent=h;const _=document.createElement("dd");_.textContent=y==null||y===""?"—":String(y),v.append(w,_)}return p.appendChild(v),p.appendChild(RO(e)),t.appendChild(p),t}function kO(e){const t=[...new Set(e.map(n=>Op(n)))];return t.length===1?t[0]:"Mixed Spaces"}function TO(e){if(e.length===1)return U_(e[0]);const t=Mp(e[0]),n=e.filter(ps),r=E_(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const o=Fp(e[0]),s=`project-cluster-title-${t.replace(/[^a-z0-9_-]/gi,"-")}`;i.setAttribute("aria-labelledby",s);const c=document.createElement("div");c.className="project-inventory-row-header",n.length>0&&c.appendChild(A_(n,`Select all identities for ${Fp(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=o,c.appendChild(l),r.length>0&&c.appendChild(D_(r,o)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=kO(e),d.appendChild(u);const p=e.reduce((_,I)=>_+(I.memory_count??0),0),f=e.reduce((_,I)=>_+I.session_count,0),m=document.createElement("div");m.className="project-inventory-meta",m.textContent=`${e.length} identities · ${f.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(m),i.appendChild(x_(r));const v=document.createElement("div");v.className="project-inventory-actions";const g=e.filter(Oc);if(g.length===0){const _=document.createElement("div");_.className="settings-note",_.textContent=e.every(mn)?"These project identities were received from peers. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.",v.appendChild(_),d.appendChild(v)}else{const _=g.map(T=>({project:T,warnings:(T.guardrail_warnings??[]).filter(M=>M.requires_confirmation)})),I=_.some(({warnings:T})=>T.length>0),P=new Set(g.map(T=>T.suggested_scope_id).filter(T=>!!T)),k=new Set(g.map(T=>T.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${Fp(e[0])} group`);const L=document.createElement("option");L.value="",L.textContent="Choose Space…",A.appendChild(L),O_(A),A.value=j_($c.get(t));const F=document.createElement("button");if(F.className="settings-button",F.type="button",F.textContent=`Save Space for ${g.length} identit${g.length===1?"y":"ies"}`,F.disabled=!A.value||I,F.addEventListener("click",()=>{wO(g,A.value)}),A.addEventListener("change",()=>{A.value?$c.set(t,A.value):$c.delete(t),F.disabled=!A.value||I}),A.addEventListener("blur",L_),v.append(A,F),P.size>1||k.size>1||I){const T=document.createElement("div");if(T.className="settings-note project-attention-note",T.textContent=I?"One or more identities in this group need individual review before bulk assignment.":"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment.",I){const M=document.createElement("ul");for(const{project:j,warnings:B}of _){if(B.length===0)continue;const U=document.createElement("li"),$=document.createElement("strong");$.textContent=`Blocked identity: ${j.workspace_identity}`;const E=document.createElement("span");E.textContent=` — ${B.map(S=>S.message).join(" ")}`,U.append($,E),M.appendChild(U)}T.appendChild(M)}v.appendChild(T)}d.appendChild(v)}const h=document.createElement("details");h.className="project-inventory-details",h.open=xc.has(t),h.addEventListener("toggle",()=>{h.open?xc.add(t):xc.delete(t)});const y=document.createElement("summary"),w=e.reduce((_,I)=>_+(I.guardrail_warnings??[]).filter(P=>P.severity==="warning").length,0);y.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",h.appendChild(y),h.appendChild(d);for(const _ of e)h.appendChild(U_(_));return i.appendChild(h),i}function NO(e){const t=new Map;for(const n of e){const r=Mp(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function q_(e){const t=De("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function G_(){document.getElementById("projectsInventorySkeleton")?.remove()}function H_(e){const t=De("projectsInventoryMeta"),n=De("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;G_(),wa.clear();for(const s of e.projects)rO(s);if(n.textContent="",e.projects.length===0)q_("No projects match those filters.");else for(const s of NO(e.projects))n.appendChild(TO(s));t.textContent=e.total===0?"0 project identities found":`${e.total} project identit${e.total===1?"y":"ies"} found · showing ${e.offset+1}-${Math.min(e.offset+e.projects.length,e.total)}`;const i=De("projectsPrevPage"),o=De("projectsNextPage");i&&(i.disabled=e.offset===0),o&&(o.disabled=!e.has_more),Qr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function EO(e,t){uO().then(()=>{t===Xi&&(Mc()||H_(e))})}async function AO(){const e=new Map;let t=0;for(;;){const n=await ho({limit:250,offset:t});for(const r of n.projects)e.set(r.workspace_identity,r);if(!n.has_more)break;t+=n.limit}return[...e.values()]}function K_(e,t,n){const r=De("recipientPolicyManagementMount");r&&hg(r,fs(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Bt.clear(),Qr(),yt?.()}})}function V_(e,t){const n=t?.candidates??[],r=e.querySelector(":scope > .project-team-setup-entry");r?.querySelector(".project-team-setup-status")?.remove();const i=r?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement?document.activeElement.dataset.teamSetupCandidateRef:void 0;if(n.length===0){r?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,i&&De("projectsSearch")?.focus();return}const o=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===o){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=o;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),Lp){const f=document.createElement("button");f.setAttribute("aria-label",`Finish setting up ${d.displayName}`),f.className="settings-button",f.type="button",f.textContent="Finish setting up this Team",f.dataset.teamSetupCandidateRef=d.candidateRef,f.addEventListener("click",()=>Lp?.(d.candidateRef)),u.appendChild(f)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||De("projectsSearch")?.focus()}}function z_(e){const t=e.querySelector(":scope > .project-team-setup-entry");if(!t)return;let n=t.querySelector(".project-team-setup-status");n||(n=document.createElement("p"),n.className="section-meta project-team-setup-status",n.setAttribute("role","status"),t.appendChild(n)),n.textContent="Team setup status is temporarily unavailable. The previous Team setup status is being shown.",e.hidden=!1}function xO(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}async function Pa(e={}){const t=De("projectsInventoryMeta"),n=De("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await jp(!0)).ok:!0;if(Mc()){if(Lc=!0,!e.requireTeamSetupSummary)return!0;const i=++Ca,o=await jp(!0);if(i!==Ca)return!1;const s=De("recipientPolicyReviewMount");return o.ok?(s&&V_(s,o.summary),!0):(s&&z_(s),!1)}Lc=!1;const r=++Xi;lr=!1,dr=!1,Qr(),t.textContent="Loading project inventory…";try{const i=++Ca,o=jp(e.requireTeamSetupSummary===!0),[s,c,l,d,u]=await Promise.all([ho({limit:Ec,offset:Ft,q:De("projectsSearch")?.value.trim()||void 0,status:De("projectsStatusFilter")?.value||void 0}),DC(),AO().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),xC().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),gl().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==Xi)return e.requireTeamSetupSummary&&await o,!1;if($p=c.scopes,lr=l.ok,dr=u.ok,Zi=u.ok?u.intent:jc,l.ok){const g=new Set(fs(l.projects).map(h=>h.canonicalProjectIdentity));for(const h of Bt)g.has(h)||Bt.delete(h)}const p=De("projectShareFlowMount");p&&_g(p,l.projects,{inventoryError:!l.ok});const f=De("recipientPolicyReviewMount");if(f){const g=xO(f);"review"in d?Qj(g,d.review,{isRepairAvailable:h=>!h.projectIdentity.startsWith("unmapped:"),onRepair:PO}):Zj(g,d.error),f.hidden=g.hidden&&!f.querySelector(".project-team-setup-entry")}K_(l.projects,Zi,!l.ok||!u.ok),H_(s),EO(s,r),o.then(g=>{if(r!==Xi||i!==Ca)return;const h=De("recipientPolicyReviewMount");if(h){if(!g.ok){z_(h);return}V_(h,g.summary)}});const m=l.ok&&"review"in d&&u.ok;if(!e.requireTeamSetupSummary)return m;const v=await o;return r!==Xi||i!==Ca?!1:m&&v.ok}catch(i){if(r!==Xi)return!1;wa.clear(),lr=!1,dr=!1,Zi=jc;const o=De("projectShareFlowMount");return o&&_g(o,[],{inventoryError:!0}),K_([],jc,!0),Qr(),G_(),t.textContent="Project inventory failed to load.",q_(i instanceof Error?i.message:"Unable to load project inventory."),!1}}function DO(e,t={}){yt=e,Lp=t.onOpenTeamSetup,Bt.clear();const n=De("projectsStatusFilter");if(n&&n.options.length===0)for(const[o,s]of k_){const c=document.createElement("option");c.value=o,c.textContent=s,n.appendChild(c)}const r=()=>{Fn+=1,Ft=0,yt?.()};De("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),De("projectsPrevPage")?.addEventListener("click",()=>{Fn+=1,Ft=Math.max(0,Ft-Ec),yt?.()}),De("projectsNextPage")?.addEventListener("click",()=>{Fn+=1,Ft+=Ec,yt?.()});const i=De("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Bt.size!==0&&To({mode:"project-add",projectIds:[...Bt].sort()})})),Qr()}function Gp(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(o=>o.trim()):r;if(t.requireNonEmpty&&i.some(o=>o.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function $O(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,o]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof o!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=o}return r}var W_="codemem-settings-advanced",J_="gpt-5.1-codex-mini",Y_="claude-4.5-haiku",LO=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],jO={claudeCommand:"claude_command",codexCommand:"codex_command",observerProvider:"observer_provider",observerModel:"observer_model",observerTierRoutingEnabled:"observer_tier_routing_enabled",observerSimpleModel:"observer_simple_model",observerSimpleTemperature:"observer_simple_temperature",observerReasoningEffort:"observer_reasoning_effort",observerReasoningSummary:"observer_reasoning_summary",observerRichModel:"observer_rich_model",observerRichTemperature:"observer_rich_temperature",observerRichReasoningEffort:"observer_rich_reasoning_effort",observerRichReasoningSummary:"observer_rich_reasoning_summary",observerRichMaxOutputTokens:"observer_rich_max_output_tokens",observerRuntime:"observer_runtime",observerAuthSource:"observer_auth_source",observerAuthFile:"observer_auth_file",observerAuthCommand:"observer_auth_command",observerAuthTimeoutMs:"observer_auth_timeout_ms",observerAuthCacheTtlS:"observer_auth_cache_ttl_s",observerHeaders:"observer_headers",observerMaxChars:"observer_max_chars",packObservationLimit:"pack_observation_limit",packSessionLimit:"pack_session_limit",rawEventsSweeperIntervalS:"raw_events_sweeper_interval_s",syncEnabled:"sync_enabled",syncHost:"sync_host",syncPort:"sync_port",syncInterval:"sync_interval_s",syncMdns:"sync_mdns",syncCoordinatorUrl:"sync_coordinator_url",syncCoordinatorGroup:"sync_coordinator_group",syncCoordinatorTimeout:"sync_coordinator_timeout_s",syncCoordinatorPresenceTtl:"sync_coordinator_presence_ttl_s"},OO=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),MO={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",observerReasoningEffort:"",observerReasoningSummary:"",observerRichModel:"",observerRichTemperature:"",observerRichReasoningEffort:"",observerRichReasoningSummary:"",observerRichMaxOutputTokens:"",observerRuntime:"api_http",observerAuthSource:"auto",observerAuthFile:"",observerAuthCommand:"",observerAuthTimeoutMs:"",observerAuthCacheTtlS:"",observerHeaders:"",observerMaxChars:"",packObservationLimit:"",packSessionLimit:"",rawEventsSweeperIntervalS:"",syncEnabled:!1,syncHost:"",syncPort:"",syncInterval:"",syncMdns:!1,syncCoordinatorUrl:"",syncCoordinatorGroup:"",syncCoordinatorTimeout:"",syncCoordinatorPresenceTtl:""};function FO(){try{return globalThis.localStorage?.getItem(W_)==="1"}catch{return!1}}function BO(e){try{globalThis.localStorage?.setItem(W_,e?"1":"0")}catch{}}function Bn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ee(e,t,n){if(Bn(t,n))return t[n];if(Bn(e,n))return e[n]}function $e(e){return e==null?"":String(e)}function Bc(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(!t||["0","false","no","off"].includes(t))return!1;if(["1","true","yes","on"].includes(t))return!0}return!!e}function UO(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function qO(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function GO(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Y_,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:J_,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Y_,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:"opencode/gpt-5.1-codex-mini",source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:J_,source:"Recommended (direct API)"}}function HO(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return ct($e(n[t]));case"observer_runtime":return ct($e(n.observer_runtime));case"observer_auth_source":return ct($e(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([o,s])=>{typeof o=="string"&&o.trim()&&typeof s=="string"&&(i[o.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Bn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r!==0?r:""}case"sync_coordinator_timeout_s":case"sync_coordinator_presence_ttl_s":{if(!Bn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Bn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)?r:""}case"sync_enabled":case"sync_mdns":case"observer_tier_routing_enabled":return Bc(n[t]);default:return Bn(n,t)?n[t]:""}}function KO(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Bn(r,i)&&(r[i]=HO(t,i))}),r}function VO(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Gp(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("claude_command"))throw I;const P=r.claude_command;o=Array.isArray(P)?P.filter(k=>typeof k=="string").map(k=>k.trim()).filter(k=>k.length>0):[]}let s=[];try{s=Gp(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("codex_command"))throw I;const P=r.codex_command;s=Array.isArray(P)?P.filter(k=>typeof k=="string").map(k=>k.trim()).filter(k=>k.length>0):[]}let c=[];try{c=Gp(t.observerAuthCommand,{label:"observer auth command"})}catch(I){if(!i||n.has("observer_auth_command"))throw I;const P=r.observer_auth_command;c=Array.isArray(P)?P.filter(k=>typeof k=="string"):[]}let l={};try{l=$O(t.observerHeaders)}catch(I){if(!i||n.has("observer_headers"))throw I;const P=r.observer_headers;P&&typeof P=="object"&&!Array.isArray(P)&&Object.entries(P).forEach(([k,A])=>{typeof k=="string"&&k.trim()&&typeof A=="string"&&(l[k]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),f=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),v=d===""?"":Number(d),g=u===""?"":Number(u),h=p===""?"":Number(p),y=f===""?"":Number(f),w=Number(m),_=m===""?"":w;if(d!==""&&!Number.isFinite(v))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof g!="number"||!Number.isFinite(g)||g<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof y!="number"||!Number.isFinite(y)||y<=0||!Number.isInteger(y)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(w)||w<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:ct(t.observerProvider),observer_model:ct(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ct(t.observerSimpleModel),observer_simple_temperature:g,observer_reasoning_effort:ct(t.observerReasoningEffort),observer_reasoning_summary:ct(t.observerReasoningSummary),observer_rich_model:ct(t.observerRichModel),observer_rich_temperature:h,observer_rich_reasoning_effort:ct(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ct(t.observerRichReasoningSummary),observer_rich_max_output_tokens:y,observer_runtime:ct(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ct(t.observerAuthSource||"auto")||"auto",observer_auth_file:ct(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:v,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:_,sync_enabled:t.syncEnabled,sync_host:ct(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ct(t.syncCoordinatorUrl),sync_coordinator_group:ct(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function zO(e){const t=e.config||{},n=e.effective||{},r=Ee(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,f])=>typeof p=="string"&&p.trim()&&typeof f=="string")):{},o=Ee(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=Ee(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ee(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:$e(Ee(t,n,"observer_provider")),observerModel:$e(Ee(t,n,"observer_model")),observerTierRoutingEnabled:Bc(Ee(t,n,"observer_tier_routing_enabled")),observerSimpleModel:$e(Ee(t,n,"observer_simple_model")),observerSimpleTemperature:$e(Ee(t,n,"observer_simple_temperature")),observerReasoningEffort:$e(Ee(t,n,"observer_reasoning_effort")),observerReasoningSummary:$e(Ee(t,n,"observer_reasoning_summary")),observerRichModel:$e(Ee(t,n,"observer_rich_model")),observerRichTemperature:$e(Ee(t,n,"observer_rich_temperature")),observerRichReasoningEffort:$e(Ee(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:$e(Ee(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:$e(Ee(t,n,"observer_rich_max_output_tokens")),observerRuntime:$e(Ee(t,n,"observer_runtime"))||"api_http",observerAuthSource:$e(Ee(t,n,"observer_auth_source"))||"auto",observerAuthFile:$e(Ee(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:$e(Ee(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:$e(Ee(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:$e(Ee(t,n,"observer_max_chars")),packObservationLimit:$e(Ee(t,n,"pack_observation_limit")),packSessionLimit:$e(Ee(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:$e(Ee(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Bc(Ee(t,n,"sync_enabled")),syncHost:$e(Ee(t,n,"sync_host")),syncPort:$e(Ee(t,n,"sync_port")),syncInterval:$e(Ee(t,n,"sync_interval_s")),syncMdns:Bc(Ee(t,n,"sync_mdns")),syncCoordinatorUrl:$e(Ee(t,n,"sync_coordinator_url")),syncCoordinatorGroup:$e(Ee(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:$e(Ee(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:$e(Ee(t,n,"sync_coordinator_presence_ttl_s"))}}function WO(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=GO(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Bn(t,r))?"Env override":n.source}: ${n.model}`}function JO(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to Luna and richer batches to Terra with medium reasoning by default. Official OpenAI and OAuth Codex consumer requests always use Responses. The observer_openai_use_responses=false compatibility setting selects chat completions only for an explicitly configured custom OpenAI-compatible base URL. Sidecar runtimes route both tiers through their local CLI.":"Off: codemem uses the base observer settings from the Connection tab for all batches. Explicit user settings always win over built-in routing defaults."}function YO(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function XO(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Processing controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function QO(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while the Processing tab owns simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-5.4-mini` for Direct API, `gpt-5.1-codex-mini` for Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function ZO(e){return!e}function eM(e,t,n){return t.has(e)||n.has(e)}function tM(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var Z={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:FO(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...MO}}};function nM(){Z.controller?.hideTooltip()}function Zr(e){if(Z.controller){Z.controller.setRenderState(e);return}Z.renderState={...Z.renderState,...e}}function rM(e){Zr({values:{...Z.renderState.values,...e}})}function iM(e){const t=["observer","queue","sync"].includes(e)?e:"observer";Z.activeTab=t,Z.controller?.setActiveTab(t)}function Uc(e,t=!0){C.settingsDirty=e,t&&Z.controller?.setDirty(e)}function oM(e){Z.showAdvanced=e,Z.controller?.setShowAdvanced(e)}function X_(){return Z.open}function aM(e){return eM(e,Z.protectedKeys,OO)}function Q_(e={}){return VO({values:Z.renderState.values,touchedKeys:Z.touchedKeys,baseline:Z.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function sM(e){Zr({observerStatus:e&&typeof e=="object"?e:null})}function cM(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},o=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=zO(t);Z.envOverrides=i,Z.protectedKeys=new Set(o),C.configDefaults=n,C.configPath=t.path||"",Zr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:C.configPath?`Config path: ${C.configPath}`:"Config path: n/a",providers:UO(t.providers),statusText:"No unsaved changes",values:s}),Z.touchedKeys=new Set;try{const c=Q_({allowUntouchedParseErrors:!0});Z.baseline=KO(c,r,i)}catch{Z.baseline={}}Uc(!1)}async function lM(){if(!Z.open)try{const[e,t]=await Promise.all([AS(),ES().catch(()=>null)]);cM(e),sM(t)}catch{}}function Hp(e){return String(e||"").replace(/_/g," ")}function Kp(e){const t=e.filter(n=>typeof n=="string"&&n.trim());return t.length===0?"":t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function dM(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function uM(e){const t=[];return e.oauth&&t.push("OAuth"),e.api_key&&t.push("API key"),e.env_var&&t.push("env var"),t.length?t.join(", "):"none"}function pM(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function fM({status:e}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,o])=>o&&typeof o=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?a(z,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",dM(t.auth?.method||"none")," ",a("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":t.auth?.token_present===!0?"check":"x"})})]})]}):a(z,{children:[a("div",{className:"status-label",children:"Observer status"}),a("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),i.length?a(z,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:i.map(([o,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return a("span",{className:"status-cred",children:[c>0?" · ":null,a("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(o),": ",uM(l)]},o)})})]}):null,r&&typeof r=="object"?a(z,{children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue",children:[a("div",{className:"status-issue-message",children:typeof r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${pM(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?a("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function Z_(e,t){const n=t.getBoundingClientRect(),r=8,i=8,o=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-o/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-o-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Ra(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function mM(e){if(!e)return[];const t=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[href]",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(t)).filter(n=>{const r=n;return!r.hidden&&r.offsetParent!==null})}function hM(){const e=Le("settingsModal");(mM(e)[0]||e)?.focus()}function gM(){const[e,t]=x({anchor:null,content:"",visible:!1}),n=q(null);return K(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},o=u=>{const p=Ra(u.target);p&&r(p)},s=u=>{const p=Ra(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=Ra(u.target);p&&r(p)},l=u=>{Ra(u.target)&&i()},d=u=>{const p=Ra(u.target);p&&(u.preventDefault(),t(f=>{if(f.anchor===p&&f.visible)return{anchor:null,content:"",visible:!1};const m=p.dataset.tooltip?.trim()||"";return m?{anchor:p,content:m,visible:!0}:f}))};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),It(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&Z_(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),K(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&Z_(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:Re(()=>typeof document>"u"?null:rn(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function vM({DialogContent:e,onClose:t}){const[n,r]=x(Z.open),[i,o]=x(["observer","queue","sync"].includes(Z.activeTab)?Z.activeTab:"observer"),[s,c]=x(C.settingsDirty),[l,d]=x(Z.renderState),[u,p]=x(Z.showAdvanced),{tooltipPortal:f,setTooltip:m}=gM();Z.open=n,Z.activeTab=i,C.settingsDirty=s,Z.renderState=l,Z.showAdvanced=u,K(()=>(Z.controller={hideTooltip:()=>{m({anchor:null,content:"",visible:!1})},setActiveTab:g=>{const h=["observer","queue","sync"].includes(g)?g:"observer";Z.activeTab=h,o(h)},setDirty:g=>{C.settingsDirty=g,c(g)},setOpen:g=>{Z.open=g,r(g)},setRenderState:g=>{const h={...Z.renderState,...g};Z.renderState=h,d(h)},setShowAdvanced:g=>{Z.showAdvanced=g,BO(g),p(g)}},()=>{Z.controller&&(Z.controller=null)}),[]),K(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const v=se(()=>{Z.startPolling&&Z.refresh&&t(Z.startPolling,Z.refresh)},[t]);return a(z,{children:[a(Rr,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:g=>{g.preventDefault()},onOpenAutoFocus:g=>{g.preventDefault(),hM()},onOpenChange:g=>{if(g){r(!0);return}v()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),f]})}function ze({children:e,className:t="field",hidden:n=!1,id:r}){return a("div",{className:t,hidden:n,id:r,children:e})}function ka({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function Vp({detail:e,title:t}){return a("div",{className:"settings-section-intro",children:[a("div",{className:"settings-section-intro-title",children:t}),a("div",{className:"small settings-section-intro-detail",children:e})]})}function yM({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:o,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:f,observerStatusBannerSlot:m}){return a(z,{children:[a(Vp,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),m,a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),a(nr,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:l()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),a(ke,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),a("div",{className:"small",children:u()}),a("div",{className:"small",id:"observerModelHint",children:p()})]}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),a(nr,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Ui,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:f("codex_command")})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Ui,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:f("claude_command")})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(ke,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Authentication"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(nr,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),a(ze,{hidden:!r,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(ke,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:f("observer_auth_file")})]}),a(ze,{hidden:!i,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(Ui,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:f("observer_auth_command")})]}),a("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(ka,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(ke,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(ke,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(ze,{className:"field settings-advanced",hidden:o(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(Ui,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:f("observer_headers")})]})]})]})}function qc({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`;return a("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[a("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:o}),a(Mi,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function bM({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(z,{children:[a(Vp,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),a("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),a(ke,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),a("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Tiered observer routing"}),a(qc,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(ka,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),a("div",{hidden:!t,children:[a("h4",{children:"Simple tier"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerSimpleModel",children:"Model"}),a("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(ke,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),a("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(ke,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),a("div",{className:"settings-advanced",hidden:!t||n(),children:[a("h4",{children:"Shared reasoning defaults"}),a("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),a(ze,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(ke,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(ze,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(ke,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),a("div",{hidden:!t,children:[a("h4",{children:"Rich tier"}),a(ze,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRichModel",children:"Model"}),a("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(ke,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),a("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(ke,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(ke,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(ke,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(ke,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),a("div",{className:"settings-group settings-advanced",hidden:n(),children:[a("h3",{className:"settings-group-title",children:"Pack limits"}),a(ka,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(ke,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),a("div",{className:"small",children:"Default number of observations to include in a pack."})]}),a(ze,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(ke,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),a("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function _M({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(z,{children:[a(Vp,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Device Sync"}),a(qc,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),a(ke,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),a("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncHost",children:"Sync host"}),a(ke,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncPort",children:"Sync port"}),a(ke,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(qc,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),a(ke,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),a("div",{className:"small",children:i("sync_coordinator_url")})]}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),a(ke,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),a("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:a(ka,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),a(ke,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),a("div",{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),a(ke,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function wM({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:o,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return a("div",{className:"modal-card",onKeyDown:p=>Ni(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(ui,{ariaLabel:"Close settings",className:"modal-close-button",onClick:o})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(qc,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(ka,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),a(Cv,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:LO,triggerClassName:"settings-tab",value:t,children:[a(xr,{className:"settings-panel",forceMount:!0,value:"observer",children:a(yM,{...e,observerStatusBannerSlot:d})}),a(xr,{className:"settings-panel",forceMount:!0,value:"queue",children:a(bM,{...e})}),a(xr,{className:"settings-panel",forceMount:!0,value:"sync",children:a(_M,{...e})})]}),a("div",{className:"small mono",id:"settingsPath",children:r.pathText}),a("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),a("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),a("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),a("div",{className:"modal-footer",children:[a("div",{className:"small",id:"settingsStatus",children:r.statusText}),a("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function SM(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||Bn(r,c)&&!i.has(c)||qO(l,n[c])||(s[c]=l)}),s}function CM(e){const t=s=>{const c=jO[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function IM(e){const t=e?.effects,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=Array.isArray(n.hot_reloaded_keys)?n.hot_reloaded_keys.map(p=>Hp(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Hp(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Hp(String(p))):[],s=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],c=Array.isArray(n.manual_actions)?n.manual_actions:[],l=n.sync&&typeof n.sync=="object"?n.sync:{},d=[];r.length&&d.push(`Applied now: ${Kp(r)}.`),i.length&&d.push(`Live settings updated: ${Kp(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),o.length&&d.push(`Restart required for ${Kp(o)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=o.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var PM=()=>WO(Z.renderState.values,Z.envOverrides),RM=()=>JO(Z.renderState.values),kM=()=>YO(Z.renderState.values),TM=()=>XO(Z.renderState.values),NM=()=>QO(Z.renderState.values),EM=()=>ZO(Z.showAdvanced),{onTextInput:AM,onSelectValueChange:xM,onSwitchInput:DM}=CM({getTouchedKeys:()=>Z.touchedKeys,getValues:()=>Z.renderState.values,updateFormState:rM,setDirty:e=>Uc(e)});function $M(){const e=Z.renderState.observerStatus;return a(fM,{status:e})}function LM(){const e=Z.renderState.values,t=String(C.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled,o={values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(Z.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((s,c)=>s.localeCompare(c)).map(s=>({label:s,value:s})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:EM,onTextInput:AM,onSelectValueChange:xM,onSwitchInput:DM,getObserverModelLabel:kM,getObserverModelTooltip:TM,getObserverModelDescription:NM,getObserverModelHint:PM,getTieredRoutingHelperText:RM,protectedConfigHelp:tM};return a(wM,{panelProps:o,activeTab:Z.activeTab,showAdvanced:Z.showAdvanced,renderState:Z.renderState,settingsDirty:C.settingsDirty,onClose:()=>{Z.startPolling&&Z.refresh&&Gc(Z.startPolling,Z.refresh)},onSave:()=>{Z.startPolling&&Z.refresh&&FM(Z.startPolling,Z.refresh)},onActiveTabChange:iM,onAdvancedToggle:oM,observerStatusBannerSlot:a($M,{})})}function jM(){return a(vM,{DialogContent:LM,onClose:Gc})}function OM(){const e=Le("settingsDialogMount");e&&We(a(jM,{}),e)}function ew(){Le("settingsDialogMount")&&(Z.shellMounted||(OM(),Z.shellMounted=!0))}function MM(e){Z.shellMounted||ew(),Z.open=!0,Z.previouslyFocused=document.activeElement,e(),Z.controller?.setOpen(!0)}function Gc(e,t){if(C.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){Z.controller?.setOpen(!0);return}Z.open=!1,Z.controller?.setOpen(!1),nM(),(Z.previouslyFocused&&typeof Z.previouslyFocused.focus=="function"?Z.previouslyFocused:Ed("settingsButton"))?.focus(),Z.previouslyFocused=null,Z.touchedKeys=new Set,e(),t()}async function FM(e,t){if(!Z.renderState.isSaving){Zr({isSaving:!0,statusText:"Saving changes…"});try{const n=Q_({allowUntouchedParseErrors:!0}),r=SM({current:n,baseline:Z.baseline,envOverrides:Z.envOverrides,touchedKeys:Z.touchedKeys,isProtected:aM});if(Object.keys(r).length===0){Zr({isSaving:!1,statusText:"No unsaved changes"}),Uc(!1),Gc(e,t);return}const i=await xS(r),o=IM(i);Zr({isSaving:!1,statusText:"Saved changes"}),Uc(!1),Gc(e,t),Q(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";Zr({isSaving:!1,statusText:`Save failed: ${r}`})}}}function BM(e,t,n){Z.startPolling=t,Z.refresh=n,ew(),Ed("settingsButton")?.addEventListener("click",()=>MM(e))}function UM(e){e.dataset.syncRenderRoot="preact"}function qM(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function ft(e,t){UM(e),We(t,e)}function eo(e){e.dataset.syncRenderRoot==="preact"&&We(null,e)}function GM(e){const t=Object.values(e||{}).map(n=>!n||typeof n!="object"?"":String(n.last_ping_at||"").trim()).filter(Boolean).sort();return t[t.length-1]??null}function HM(e){return typeof e=="object"&&e!==null}function KM(e,t){return C.pairingCommandRaw="",{payloadText:e,hintText:t}}function VM(e){if(!HM(e))return KM("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return C.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function zM(){return{title:"Diagnostics still loading.",detail:"Wait a moment for local sync status. If it stays blank, refresh the page or check whether sync is enabled on this device."}}function WM(){return{title:"Diagnostics unavailable right now.",detail:"The viewer could not load sync status. Refresh this page, or check that the local codemem sync service is reachable before retrying."}}function JM(){const e=C.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function YM(){return{title:"Recent attempts unavailable right now.",detail:"Attempt history could not be loaded because sync diagnostics failed. Refresh the page after local sync status is reachable again."}}function XM(e,t){return e==="offline-peers"&&t?"Some recent failures may have happened before all peers went offline. Sync will resume automatically when a peer becomes reachable.":""}function QM({items:e}){return a(z,{children:e.map((t,n)=>a("div",{class:"stat",children:a("div",{class:"stat-content",children:[a("div",{class:"value",children:t.value}),a("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function ZM({attempts:e,note:t}){return a(z,{children:[t?a("div",{class:"small",children:t}):null,e.map((n,r)=>a("div",{class:"diag-line",children:[a("div",{class:"left",children:[a("div",{children:[n.peerLabel," — ",n.status]}),n.detail?a("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?a("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function tw({text:e}){return a(z,{children:e})}function e1({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function t1(e,t){if(!t.length){eo(e);return}ft(e,a(QM,{items:t}))}function n1(e,t,n){if(!t.length){eo(e);return}ft(e,a(ZM,{attempts:t,note:n}))}function ei(e,t){ft(e,a(e1,{...t}))}function nw(e,t,n){ft(e,a(tw,{text:n.payloadText})),t&&ft(t,a(tw,{text:n.hintText}))}function rw({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=q(null),p=q(null),f=q(!1);It(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),K(()=>{if(!e){f.current=!1;return}f.current||(f.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(Go,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(qo,{open:e,onOpenChange:t,children:[a(Zd,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?rn(m,l):m]})}function r1({open:e,onOpenChange:t}){return a(rw,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[a("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),a("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),a("div",{className:"actor-create-row",children:[a("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),a(ke,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),a("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),a("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),a("div",{className:"sync-ttl-group",children:[a("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),a(ke,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),a("span",{children:"hours"})]}),a("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),a("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),a(Ui,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),a("div",{className:"peer-meta",id:"syncInviteAdminHint"}),a("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function i1({contentHost:e,open:t,onOpenChange:n}){return a(rw,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[a("div",{className:"peer-title",children:[a("strong",{children:"Pairing command"}),a("div",{className:"peer-actions",children:a("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),a("div",{className:"pairing-body",children:a("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),a("div",{className:"peer-meta",id:"pairingHint"})]})}function o1(e,t){ft(e,a(r1,{...t}))}function a1(e,t){ft(e,a(i1,{...t}))}function fe(e){return String(e??"").trim()}function s1(e){return fe(e).replace(/\s+/g," ").toLowerCase()}function c1(e){const t=fe(e);return t?t.slice(0,8):"Unnamed device"}function iw(e){return fe(e?.last_error).toLowerCase()}function ow(e){return e.includes("401")&&e.includes("unauthorized")}function aw(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var l1={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function sw(e){return e.device?.needs_local_approval?{state:"needs-your-approval",badgeLabel:"Needs your approval",description:"Another device already approved this pairing. Approve it here to finish the connection on both sides.",actionLabel:"Approve on this device"}:e.device?.waiting_for_peer_approval?{state:"waiting-for-other-device",badgeLabel:"Waiting on other device",description:"You already approved this pairing here. The other device still needs to approve this one before sync can work both ways.",actionLabel:null}:{state:"none",badgeLabel:null,description:null,actionLabel:null}}function d1(e){const t=sw(e);return!fe(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function cw(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),o=m1(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${o}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>lw(i)==="trust").length===n.length?{ok:!1,message:"This device no longer has two-way trust with the peer. Pair it again from the other device, or remove the stale local record if it should be gone.",warning:!0}:n.filter(i=>lw(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review legacy Space access for this device in Coordinator Administration, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:fe(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function lw(e){if(e.failureCategory)return e.failureCategory;const t=Array.isArray(e.perScopeResults)?e.perScopeResults.filter(r=>r&&r.ok===!1).map(r=>r.failureCategory).filter(r=>!!r):[];if(t.length)return new Set(t).size===1?t[0]:"other";const n=fe(e.error);return u1(n)?"trust":p1(n)?"scope":null}function u1(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function p1(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function f1(e){const t=fe(e?.reason);return l1[t]??(t.replaceAll("_"," ")||"sync filters")}function m1(e){const t=new Map;for(const n of e){const r=f1(n),i=Math.max(0,Number(n?.skipped_count??0));i!==0&&t.set(r,(t.get(r)??0)+i)}return t.size?Array.from(t.entries()).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).map(([n,r])=>`${r.toLocaleString()} by ${n}`).join(", "):"sync filters"}function dw(e){const t=fe(e.localName);if(t)return t;const n=fe(e.coordinatorName);return n||c1(fe(e.deviceId))}function h1(e){const t=fe(e.localName),n=fe(e.coordinatorName);return t||n?!1:!!fe(e.deviceId)}function g1(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Ta(e){const t=fe(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=iw(e);return ow(n)?"needs-repair":aw(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function to(e){const t=e?.status||{},n=fe(t.peer_state),r=iw(e),i=fe(t.sync_status)==="ok"||fe(t.ping_status)==="ok";return n==="offline"||n==="stale"?{state:"offline",badgeLabel:"Offline",description:"This device was paired before, but it is offline right now.",isWarning:!0}:ow(r)?{state:"needs-repairing",badgeLabel:"Needs re-pairing",description:"This device no longer accepts this one. Pair again from the other device, or remove this local record if it no longer belongs here.",isWarning:!0}:aw(r)?{state:"offline",badgeLabel:"Offline",description:"This device is saved here, but none of its last known addresses are responding right now.",isWarning:!0}:i||n==="online"?{state:"mutual-trust",badgeLabel:"Two-way trust",description:"Both devices trust each other and sync can run in both directions.",isWarning:!1}:e?.has_error||n==="degraded"?{state:"needs-review",badgeLabel:"Needs review",description:"This device has a sync problem that needs review before you trust the current state again.",isWarning:!0}:{state:"trusted-by-you",badgeLabel:"Waiting on other device",description:"This device is already trusted here. Finish setup on the other device before sync can run both ways.",isWarning:!1}}var v1={missing_scope:"Missing scope id",sender_not_member:"Sender not a scope member",receiver_not_member:"Receiver not a scope member",stale_epoch:"Stale or revoked membership",scope_mismatch:"Scope mismatch",visibility_filter:"Visibility filter",project_filter:"Project filter"};function y1(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,o]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(o??0));if(s===0)continue;const c=i;r.push({reason:c,label:v1[c]??i,count:s})}return r.sort((i,o)=>o.count-i.count||i.label.localeCompare(o.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function uw(e){return Array.isArray(e)?e.map(t=>fe(t)).filter(t=>!!t):[]}function pw(e,t){if(e.length===0)return t;const n=e.slice(0,3).join(", "),r=e.length-3;return r>0?`${n} +${r.toLocaleString()} more`:n}function Hc(e,t){return e?e.replaceAll("_"," "):t}function b1(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=fe(r.scope_id),o=fe(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[Hc(fe(r.kind),"user"),Hc(fe(r.authority_type),"local"),`${Hc(fe(r.role),"member")} role`].filter(Boolean).join(" · ");return{scopeId:i||s,label:s,detail:c}}).filter(r=>r!=null),n=t.length;return{total:n,badgeLabel:n===1?"1 Space":n>1?`${n} Spaces`:"No Space access",isWarning:n===0,domains:t,emptyMessage:"No Space access grants exist for this device yet. Advanced project filters cannot send data by themselves."}}function fw(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=fe(n.scope_id),i=fe(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=fe(n.last_applied_cursor),c=fe(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=Hc(fe(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(f=>!!f).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var _1=["personal","private","home","mine","me"],w1=["oss","open source","opensource","community","public"],S1=["work","client"],C1=["local","legacy","review"];function I1(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>fe(t)??"").join(" ").toLowerCase()}function P1(e){return[e.scope_id,e.label,e.kind].map(t=>fe(t)??"").join(" ").toLowerCase()}function mw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zp(e,t){const n=I1(e);return t.some(r=>{const i=mw(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function hw(e){return zp(e,_1)||zp(e,w1)}function R1(e){const t=P1(e);return C1.some(n=>{const r=mw(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function k1(e){return!hw(e)&&(!R1(e)||zp(e,S1))}function T1(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(fe(e.discovered_via_group_id)||fe(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(hw),r=t.some(k1);return!n||r?{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""}:{badgeLabel:"Review Space fit",detail:"Team discovery helps find the device, and advanced project filters only narrow already-authorized Spaces. Neither one grants missing work/client Space access.",isVisible:!0,message:"This Team-discovered device has personal or OSS Space access, but no separate work/client-like Space access. If this device is meant for work/client sync, grant that Space explicitly before treating sync as validated.",title:"Check this device's Space access"}}function N1(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function E1(e){const t=uw(e?.effective_include),n=uw(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${pw(t,"all projects")}`,o=`Exclude filter: ${pw(n,"no exclusions")}`,s=N1(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:o,summary:`${r}. ${i}; ${o}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function A1(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=fe(n?.display_name),i=fe(n?.actor_id),o=s1(r);if(!r||!i||!o)return;const s=t.get(o)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(o,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function gw(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=fe(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const o=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>fe(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(fe(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var x1=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),D1=new Set(["pending","verifying","waiting"]);function $1(e){return(Array.isArray(e?.groups)?e.groups.map(t=>fe(t)).filter(Boolean):[]).join(", ")||"none"}function L1(e){return fe(e?.projects?.[0]?.display_name)||"the shared Project"}function j1(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=to(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function O1(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&to(n).state==="mutual-trust"&&!fw(n).rows.some(r=>r.status==="pending"))}function M1(e){return e.some(t=>fe(t.status?.peer_state)==="online"&&to(t).state==="mutual-trust")}function F1(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=fe(n.status?.peer_state),i=to(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function B1(e){if(e?.daemon_running===!1)return!0;const t=e?.daemon_state;return t!==void 0&&t!=="ok"&&t!=="offline-peers"&&t!=="stale"&&t!=="degraded"}function vw(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],o=$1(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${o}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${o}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."};if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${o}. Team access needs review before it can continue.`,nextAction:"Open Sharing, review Project access, then sync again."};const l=r.find(p=>{const f=p.lifecycle?.state;return f!==void 0&&x1.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&D1.has(f)});if(l||d){const p=l?L1(l):"the shared Project",f=l?.lifecycle?.primary_action?.kind,m=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:m?"Removal pending":"Setup pending",meta:m?`Team: ${o}. Future access removal for ${p} is still pending.`:`Team: ${o}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:m?`Keep both devices online, then sync again to finish removing future access for ${p}.`:f==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:f==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(B1(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${o}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(j1(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${o}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=fe(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${o}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${o}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}:F1(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${o}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&O1(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${o}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:M1(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${o}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${o}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function U1(e){return e.discovered?.stale?e.peer?Ta(e.peer)!=="connected":!0:!1}function yw(e){return{id:`repair:${e.id}`,kind:"device-needs-repair",priority:10,title:e.title||`${e.name} needs attention`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function Wp(e){return{id:`review:${e.id}:${e.key||"default"}`,kind:"review-team-device",priority:20,title:`${e.name} is available to review`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function q1(e){return{id:`name:${e.id}`,kind:"name-device",priority:30,title:`Name ${e.name}`,summary:e.summary,actionLabel:"Go to name field",deviceId:e.id}}function G1(e){const t=fe(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>fe(r))?e?.sync_enabled===!1?{reason:"sync_disabled",message:"Enable sync before pairing team devices."}:null:{reason:"coordinator_groups_empty",message:"Join or configure a team before pairing team devices."}:{reason:"coordinator_url_missing",message:"Configure a coordinator URL before pairing team devices."}}function H1(e,t){const n=new Map,r=i=>{const o=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,o),o};return e.forEach(i=>{const o=fe(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=fe(i?.name)}),t.forEach(i=>{const o=fe(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=fe(i?.display_name)}),[...n.values()]}function K1(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.coordinator?.discovered_devices)?e.coordinator.discovered_devices:[],i=H1(n,r),o=e.duplicatePersonDecisions??{},s=A1(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=dw({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Ta(l.peer):"waiting",p=l.peer?to(l.peer):null,f=fe(l.discovered?.fingerprint),m=fe(l.peer?.fingerprint);if(l.peer&&f&&m&&f!==m){c.push(yw({id:l.deviceId,name:d,title:`${d} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."}));return}if(l.peer&&u==="needs-repair"){const v=p?.description||fe(l.peer?.last_error)||"Sync needs review.";c.push(yw({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:v}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Wp({id:l.deviceId,key:"other-device-trust",name:d,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),!l.peer&&l.discovered?.stale&&c.push(Wp({id:l.deviceId,key:"stale-discovery",name:d,summary:"This device is no longer advertising fresh coordinator presence. Wait for it to check in again before connecting it here."})),!l.peer&&Array.isArray(l.discovered?.groups)&&l.discovered.groups.length>1&&c.push(Wp({id:l.deviceId,key:"ambiguous-groups",name:d,summary:"This device appears in multiple coordinator groups. Review the team setup before approving it here."})),l.peer&&h1({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(q1({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:vw({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Ta(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>U1(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var bw={actor:"person",actors:"people",actorAssignment:"person assignment",localActor:"you",peer:"device",peers:"devices",pairedLocally:"Connected on this device",discovered:"Seen on team",conflicts:"Needs review"};function ur(e){const t=document.getElementById(e);t&&t.remove()}var _w=!1;function V1(e){_w=e}var Jp=!1;function z1(e){Jp=e}var Yp=!1;function W1(e){Yp=e}var J1=new Set,Xp=new Set,Qp=new Set,ww="codemem-sync-duplicate-person-decisions";function Y1(e){const t=String(e||"").trim();t&&(Xp.add(t),Qp.add(t),J1.add(t))}function Zp(e){const t=String(e||"").trim();return!!t&&Xp.has(t)}function X1(e){const t=String(e||"").trim();t&&Xp.delete(t)}function Q1(e){const t=String(e||"").trim();return!t||!Qp.has(t)?!1:(Qp.delete(t),!0)}function ef(){try{const e=localStorage.getItem(ww);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Sw(e){try{localStorage.setItem(ww,JSON.stringify(e))}catch{}}function Cw(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function Z1(){return ef()}function eF(e,t){const n=Cw(e);if(!n)return;const r=ef();r[n]=t,Sw(r)}function tF(e){const t=Cw(e);if(!t)return;const n=ef();delete n[t],Sw(n)}function Iw(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function Pw(e){const t=String(e||"");return t?Iw(t):""}function nF(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function rF(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Kc(e){if(!e||typeof e!="object")return"Unknown person";const t=String(e.display_name||"").trim();return t||String(e.actor_id||"Unknown person")}function tf(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Kc(e)}function iF(e){return(Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function oF(){return gw({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}).visibleActors}function Rw(e){return oF().filter(t=>String(t?.actor_id||"")!==e)}function aF(e,t){const n=Rw(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${tf(n)}. Assigned devices move now; existing memories keep their current provenance.`}function nf(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Ts("div","sync-action"),i=Ts("div","sync-action-text");i.textContent=n.label,i.appendChild(Ts("span","sync-action-command",n.command));const o=Ts("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Oo(n.command,o)),r.append(i,o),e.appendChild(r)})}}function kw(e,t){return t&&e.error_redacted===!0}function Tw(){const e=document.getElementById("syncAttempts");if(!e)return;const t=C.lastSyncAttempts,n=String(C.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){ei(e,JM());return}const r=XM(n,t.slice(0,5).some(o=>o.status==="error")),i=t.slice(0,5).map(o=>{const s=o.started_at||o.started_at_utc||"",c=String(o.peer_device_id||"").trim(),l=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",p=[],f=Fo();if(u&&o.error){const m=String(o.error);p.push(f?Iw(m):m),kw(o,f)&&p.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&p.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!f&&o.address&&p.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:p.join(" · "),startedAt:s?qr(s):"",...kw(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});n1(e,i,r)}function sF(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&ei(e,WM()),t&&ei(t,YM()),n&&(n.textContent="Advanced diagnostics are unavailable right now. Refresh the page first. If that still fails, verify the local sync service and retry once it responds again."),nf(r,[])}function no(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function cF(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=no(n.would_remove),o=no(n.ambiguous),s=no(r.applied),c=no(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||o>0?`${o} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function Nw(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;ur("syncDiagSkeleton");const r=C.lastSyncStatus;if(!r){ei(e,zM()),nf(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},o=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=o.last_ping_at||r.last_ping_at||GM(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),f=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),v=r.retention||{},g=r.cleanup_diagnostics,h=g?.stale_peer_rows??{},y=no(h.would_remove),w=no(h.ambiguous),_=v.enabled===!0,I=Number(v.last_deleted_ops||0),P=v.last_run_at||null,k=String(v.last_error||""),A=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":By(m),L=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,T=!L&&F===0;if(t){const B=L?["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:T?["Advanced sync is ready but idle","Use Show pairing command under People & devices to connect another device, then this panel will start showing live peer status and recent attempts"]:[`Advanced state: ${A}`,`Peers: ${F}`,c?`Last sync: ${rr(qi(c))} ago`:"Last sync: never"];m==="offline-peers"&&B.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&B.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&B.push(`Detail: ${f}`),_&&B.push(P?`Retention last ran ${rr(qi(P))} ago (approx oldest-first)`:"Retention enabled"),y>0?B.push(`${y.toLocaleString()} stale peer rows pending cleanup`):w>0&&B.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=B.join(" · ")}const M=L?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:T?[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:p},{label:"Last sync",value:"Waiting for first peer"}]:[{label:"State",value:A},{label:"Pending events",value:p},{label:"Last sync",value:c?`${rr(qi(c))} ago`:"never"},{label:"Last peer ping",value:l?`${rr(qi(l))} ago`:"never"},{label:"Retention",value:_?P?`${I.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!L&&!T&&(d||u)&&M.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!L&&!T&&s.seconds_since_last&&M.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!L&&!T&&o.seconds_since_last&&M.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!L&&_&&k&&M.push({label:k,value:"Retention"}),!L&&!T&&g&&M.push({label:"Cleanup",value:cF(g)}),t1(e,M);const j=[];T||m==="offline-peers"||(m==="stopped"?(j.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),j.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?j.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?j.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(j.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),j.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!L&&!T&&p>0&&j.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!L&&w>0?j.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!L&&y>0&&j.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),nf(n,j)}var lF="syncRedactMount",dF="syncRedactLabel",Ew=()=>{};function uF(e){Ew=e}var rf=()=>{};function of(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;a1(e,{contentHost:t,open:C.syncPairingOpen,onOpenChange:r=>{if(oT(r),of(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&nw(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}rf()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=C.pairingCommandRaw;r&&await Oo(r,n)})}function af(){of();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;nw(e,t,VM(C.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!C.pairingCommandRaw)}function Aw(){const e=document.getElementById(lF);e&&ft(e,b(Mi,{"aria-labelledby":dF,checked:Fo(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{aT(t),Aw(),rf(),Nw(),Ew(),Tw(),af()},thumbClassName:"sync-redact-switch-thumb"}))}function pF(e){rf=e,of(),Aw()}function fF(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function ro(e,t){e.classList.add("sync-field-error");const n=e.parentElement?.querySelector(".sync-field-hint");n&&n.remove();const r=document.createElement("div");return r.className="sync-field-hint",r.textContent=t,e.insertAdjacentElement("afterend",r),fF(e),e.addEventListener("input",()=>Na(e),{once:!0}),!1}function Na(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function bt(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var ti=new Map,sf=null,mF={operation_device_binding_missing:"The accepted device has not been linked yet.",operation_not_found:"This sharing operation is no longer available.",operation_scope_mismatch:"The invitation no longer matches the reviewed project access.",operation_state_invalid:"The invitation is no longer in a recoverable state.",reassign_capability_required:"A participating device must be updated before setup can continue."};function hF(e){const t=e instanceof Error?e.message:String(e);return mF[t]??"Setup could not be retried. Review diagnostics for details."}function gF(e){const t=new Map;for(const n of e){const r=n.person.actor_id;t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function vF(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function cf(e){switch(e){case"waiting_for_acceptance":return"Invitation pending";case"active":return"Sharing";case"revoking":return"Removing sharing";case"revoked":return"Previously shared";case"cancelled":return"Invitation cancelled";default:return"Sharing setup"}}function yF({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=x(!1),[c,l]=x(()=>ti.get(e.operation_id)??null),d=q(null),u=e.lifecycle.primary_action;K(()=>{sf!==e.operation_id||!d.current||(sf=null,d.current.focus())},[c?.message,e.operation_id]);async function p(g){s(!0);try{let h=g;if(!h&&n){const w=(await n(e.operation_id)).lifecycle.primary_action;w?.kind==="copy_invite"&&(h=w.invite_link)}if(!h)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(w=>navigator.clipboard.writeText(w)))(h);const y={message:"Invite copied.",tone:"success"};ti.set(e.operation_id,y),l(y)}catch(h){const y={message:h instanceof Error?h.message:"Invite could not be copied.",tone:"warning"};ti.set(e.operation_id,y),l(y)}finally{s(!1)}}async function f(){s(!0);try{const g=await t(e.operation_id),h=g.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:g.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${g.lifecycle.label}.`,tone:"success"};ti.set(e.operation_id,h),sf=e.operation_id,l(h),await r()}catch(g){const h={message:hF(g),tone:"warning"};ti.set(e.operation_id,h),l(h),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const g=e.projects.map(h=>h.project_id?.trim()).filter(h=>!!h);if(g.length!==e.projects.length){const h={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};ti.set(e.operation_id,h),l(h);return}if(!hs(g,e.person.display_name)){const h={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};ti.set(e.operation_id,h),l(h)}}function v(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){f();return}m()}}return a("section",{"aria-label":`${cf(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:cf(e.lifecycle.state)}),a("ul",{"aria-label":`${cf(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((g,h)=>a("li",{className:"peer-scope-chip",children:g.display_name},`${g.display_name}:${h}`))}),a("div",{className:"peer-scope-summary",children:e.lifecycle.label}),a("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?a("div",{className:"peer-actions",children:a("button",{"aria-busy":o,className:"settings-button",disabled:o,type:"button",onClick:v,children:o?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?a("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function bF({operations:e,...t}){const n=e[0].person,r=vF(e);return a("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[a("h3",{className:"device-row-name",children:n.display_name}),r.length>0?a("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>a("li",{children:i.display_name},i.device_id))}):null,e.map(i=>a(yF,{operation:i,...t},i.operation_id))]})}function _F(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:gF(e.operations).map(t=>a(bF,{...e,operations:t},t[0].person.actor_id))})}function wF(e,t){ft(e,a(_F,{...t}))}function xw({title:e,detail:t}){return a("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[a("strong",{children:e}),a("span",{children:t})]})}function SF(e){return e<=0?"Represents you across your own devices.":`Represents you across your own devices. ${e} unresolved duplicate ${e===1?"entry is":"entries are"} hidden until reviewed in Needs attention.`}function CF({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Kc(e),c=iF(o),l=Rw(o),d=l.map(j=>String(j.actor_id||"")).join("|"),[u,p]=x(s),[f,m]=x(!1),[v,g]=x("Rename"),[h,y]=x(!1),[w,_]=x("Merge into selected person"),[I,P]=x(""),[k,A]=x(!1);K(()=>{p(s),m(!1),g("Rename"),y(!1),_("Merge into selected person"),P(""),A(!1)},[o,c,t,s,d]);const L=l.length?aF(I,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(j=>{const B=String(j.actor_id||"");return{label:j.is_local?tf(j):Kc(j),value:B}})];async function T(){const j=u.trim();if(!j)return;m(!0),g("Saving…");let B=!1;try{await n(o,j),B=!0}catch{g("Retry rename")}finally{m(!1),B&&g("Rename")}}async function M(){if(!I)return;const j=l.find(U=>String(U.actor_id||"")===I);if(!j||!await pn({title:`Merge ${s} into ${Kc(j)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;y(!0),_("Merging…");let B=!1;try{await r(I,o),B=!0}catch{_("Retry merge")}finally{y(!1),B&&_("Merge into selected person")}}return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:tf(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?SF(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:a("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),a("div",{className:"actor-actions",children:e.is_local?a("div",{className:"peer-meta",children:"Rename yourself in config"}):a(z,{children:[a(ke,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||h,type:"text",value:u,onInput:j=>p(j.currentTarget.value),onKeyDown:j=>Ni(j,{onSubmit:()=>{T()},disabled:f||h||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||h,onClick:()=>{T()},children:v}),a("button",{type:"button",className:"settings-button danger",disabled:f||h,onClick:async()=>{await pn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:f||h,onClick:()=>A(j=>!j),children:k?"Hide duplicate cleanup":"Show duplicate cleanup"}),k?a(z,{children:[a("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),a("div",{className:"actor-merge-controls",children:[a(nr,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:h||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:P,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:I,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:h||l.length===0||!I,onClick:()=>{M()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:L})]}):null]})})]})}function IF({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(z,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(CF,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(xw,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function PF(e,t){ft(e,a(IF,{...t}))}function RF(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function kF(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${qr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function TF({devices:e}){return a(z,{children:kF(e)})}function NF(e){const t=String(e.origin_device_id||"").trim(),n=Number(e.memory_count||0);return{label:n>0?`${t} (${n} memories)`:t,value:t}}function EF(e){const t=RF(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),eo(e.mount),eo(e.meta);return}const n=t.map(NF),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,ft(e.mount,a(nr,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),ft(e.meta,a(TF,{devices:t}))}var AF={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function xF({state:e,size:t=8,"aria-label":n}){const r=n??AF[e];return a("span",{"aria-label":r,className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function ni({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function DF(){return a("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[a("title",{children:"Chevron"}),a("path",{d:"m9 18 6-6-6-6"})]})}function $F(e){switch(Ta(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Vc=null,Dw=0,lf=new Set;function $w(e){if(Vc!==e){Vc=e,Dw+=1;for(const t of lf)t(Dw)}}function LF(){const[,e]=x(0);return K(()=>(lf.add(e),()=>{lf.delete(e)}),[]),Vc}var jF={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function Lw(e,t){if(!e)return"the selected Identity";const n=t.find(r=>r.actor_id===e);return String(n?.display_name||n?.actor_display_name||"the selected Identity")}function OF(e,t,n,r=!1,i=!1,o=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||o&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${Lw(e.identityId,n)}.`,detail:"This result comes from an active identity_devices binding. Advanced actor_id values are not authoritative ownership.",actionLabel:"Review or rebind in Devices"};if(e?.state==="pairing_required")return{status:"pairing_required",summary:"Identity setup is blocked until pairing is complete.",detail:"Pairing establishes sync trust; it does not establish device ownership.",actionLabel:"Review setup in Devices"};if(e?.state==="conflicted")return{status:"conflicted",summary:"Identity ownership needs review.",detail:"Conflicting device evidence failed closed. Advanced actor_id values cannot resolve ownership.",actionLabel:"Review conflict in Devices"};const s=e?.suggestedIdentityId??t;return{status:e?.state??"unavailable",summary:s?`Suggested Identity: ${Lw(s,n)}.`:"No authoritative Identity binding is configured.",detail:"sync_peers.actor_id is only a suggestion or hint until you confirm an identity_devices binding in Devices.",actionLabel:"Set up Identity in Devices"}}function MF(e){C.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function FF(e){return e?e.authorized?"Private same-person sync is limited to your personal Space. Team and org Spaces do not carry your private memories.":"Private same-person sync is blocked until this device is granted an allowed personal Space.":"Private same-person sync is limited to an allowed personal Space; team or org Spaces do not carry your private memories."}function BF(){window.location.hash="advanced/teams"}function df(e=C.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function UF({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),o=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||o,c=to(e),l=jF[g1(e)],d=e.status||{},u=b1(e),p=Zp(i),f=p&&u.total===0,m=T1(e),v=y1(e),g=fw(e),h=e.project_scope||{},y=E1(h),w=nF(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(re=>String(re)))):[],I=Number(e.address_count??0),P=Number.isFinite(I)&&I>0?I:0,k=_.length?_.map(re=>Fo()?Pw(re):re).join(" · "):P>0?`${P} ${P===1?"address":"addresses"} hidden`:"No addresses",A=C.lastDeviceIdentityInventory?.items.find(re=>re.deviceId===i||re.evidenceDeviceIds.includes(i)),L=OF(A,String(e.actor_id||"")||null,C.lastSyncActors,C.deviceIdentityInventoryLoadError,C.lastDeviceIdentityInventory?.truncated===!0,C.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),T=String(d.last_ping_at||d.last_ping_at_utc||""),M=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,j=Q1(i),B=q(null),[U,$]=x(o),[E,S]=x(()=>C.syncPeerFeedbackById.get(i)??null),[D,H]=x(!1),[G,oe]=x("Save name"),[ae,ee]=x(!1),[ie,Ce]=x(!1),[Ie,Ne]=x("Remove device");K(()=>{p&&u.total>0&&X1(i)},[u.total,i,p]),K(()=>{$(o),S(C.syncPeerFeedbackById.get(i)??null),H(!1),oe("Save name"),ee(!1),Ce(!1),Ne("Remove device")},[o,e.actor_id,i]),K(()=>{!j||!B.current||queueMicrotask(()=>B.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[j]);async function le(){if(!i)return;const re=U.trim();if(!re){const je={message:"Enter a friendly name for this device.",tone:"warning"};S(je),C.syncPeerFeedbackById.set(i,je),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}H(!0),oe("Saving…");try{const je=await n(i,re);S(je),C.syncPeerFeedbackById.set(i,je),oe("Save name")}catch{oe("Retry")}finally{H(!1)}}async function ye(){if(f){const re=df();if(!await pn({title:`Sync ${o} before advanced rule review?`,description:re?"This manual sync will use the current legacy Space access and advanced filters until you review them in Coordinator Administration.":"This manual sync will use the current legacy Space access and advanced filters until a coordinator operator reviews them in Coordinator Administration.",confirmLabel:"Sync anyway",cancelLabel:re?"Review legacy Team/Space setup first":"Cancel"}))return}ee(!0);try{const re=await r(e,w);S(re),re&&C.syncPeerFeedbackById.set(i,re)}finally{ee(!1)}}async function Y(){if(!i||!await pn({title:`Remove device ${s}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;Ce(!0),Ne("Removing…");let re=!1;try{await t(i,s),re=!0}catch{Ne("Retry remove")}finally{Ce(!1),re&&Ne("Remove device")}}const ce=LF()===i&&i!=="",ge=`device-drawer-${i||"unknown"}`,pe=$F(e),He=F?`Sync: ${qr(F)}`:"Sync: never",de=df(),W=`${ce?"Collapse":"Expand"} device ${o}`;return a(qo,{asChild:!0,open:ce,onOpenChange:re=>{re?$w(i):Vc===i&&$w(null)},children:a("div",{ref:B,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Zd,{asChild:!0,children:a("button",{"aria-label":W,className:"device-row-head device-row-head--trigger",type:"button",children:[a(xF,{state:pe}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),f?a("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,a("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),v.badgeLabel?a("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:v.badgeLabel}):null,m.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:m.badgeLabel}):null,e.discovered_via_group_id?a("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:He}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(DF,{})})]})}),a(Go,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:ge,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:ae,onClick:()=>{ye()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:ae?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(ke,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:D,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:U,onInput:re=>$(re.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:D,onClick:()=>{le()},children:G}),a("button",{type:"button",className:"settings-button danger",disabled:ie,onClick:()=>{Y()},children:Ie})]}),a("div",{className:"peer-scope",children:[j?a("div",{className:"peer-meta",children:de?"Review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad.":"A coordinator operator can review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad."}):f?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:k}),M?a("div",{className:"peer-meta",children:M}):null,a("div",{className:"peer-meta",children:[F?`Sync: ${qr(F)}`:"Sync: never",T?`Ping: ${qr(T)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(re=>a("li",{className:"peer-scope-chip",title:re.detail,children:re.label},re.scopeId))}):null,m.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:m.title}),a("div",{children:m.message}),a("div",{children:m.detail})]}):null,a("div",{className:"peer-meta",children:y.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:g.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":g.emptyMessage}),g.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:g.rows.map(re=>a("li",{title:re.detail,children:[a("span",{className:"peer-scope-rejection-label",children:re.label}),a("span",{className:`badge ${re.status==="received"?"badge-online":"actor-badge"}`,children:re.badgeLabel})]},re.scopeId))}):null,v.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":v.total,children:[a("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),a("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),a("ul",{className:"peer-scope-rejections-list",children:v.reasons.map(re=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:re.label}),a("span",{className:"peer-scope-rejection-count",children:re.count.toLocaleString()})]},re.reason))}),v.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",qr(v.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:L.summary}),a("div",{className:"peer-meta",children:L.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:FF(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>MF(A?.deviceId??i),children:L.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[y.statusLabel,". ",y.summary," ",y.note]}),de?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:BF,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(ni,{feedback:E})]})]})]})})}function qF(e){const t=C.syncPeersSectionFeedback,n=C.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(z,{children:[a(ni,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(UF,{peer:i,...e},o)})]}):a(z,{children:[a(ni,{feedback:t}),a(xw,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function GF(e,t){ft(e,a(qF,{...t}))}var pr=async()=>{},zc="";function uf(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function HF(e){pr=e}function KF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;ur("syncActorsSkeleton"),uf(!1);const n=gw({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),PF(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await zC(i,o),await pr()},onMerge:async(i,o)=>{try{await dm(i,o),Q("People combined. Assigned devices moved to the selected person."),await pr()}catch(s){throw Q(bt(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await WC(i),Q("Person removed. Assigned devices have been unassigned."),await pr()}catch(o){throw Q(bt(o,"Failed to remove person."),"warning"),o}}})}function VF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");uf(!0),t&&(t.textContent="People controls are temporarily unavailable. Refresh this page to retry. Device status and sync health are still available below while this recovers."),e&&ei(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function zF(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;wF(e,{operations:C.lastShareOperations,onAdvance:n=>OC(n),onLoadOperation:n=>jC(n),onReload:pr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=C.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":C.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function pf(){const e=document.getElementById("syncPeers");if(!e)return;ur("syncPeersSkeleton");const t=C.lastSyncPeers,n=Array.isArray(t)?t:[];rF(C.syncPeersSectionFeedback,n)&&(C.syncPeersSectionFeedback=null),GF(e,{peers:n,onRename:async(r,i)=>{try{return await Yf(r,i),await pr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:bt(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await yl({address:i,peerDeviceId:o||void 0}),c=cw(s);let l;c.ok?o&&Zp(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${df()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await pr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(o){return{message:bt(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Jf(r);const o={message:`Removed peer ${i}.`,tone:"success"};return C.syncPeerFeedbackById.delete(r),C.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await pr(),o}catch(o){return{message:bt(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function WF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");uf(!0),t&&(t.textContent="People and device details are unavailable right now. Refresh this page to retry once local sync status is reachable again."),e&&ei(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. Named people will reload here once the local sync status endpoint responds again."}),n&&ei(n,{title:"Devices unavailable right now.",detail:"Refresh this page to retry. When sync is reachable again, paired devices will reload here so you can rename, inspect, or re-pair them."})}function jw(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(C.lastSyncLegacyDevices)?C.lastSyncLegacyDevices:[];EF({devices:r,meta:n,mount:t,onValueChange:i=>{i!==zc&&(zc=i,jw())},panel:e,value:zc})}function JF(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Ni(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){ro(n,"Enter a name for the person.");return}Na(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await VC(i),Q("Person created."),n.value="",await e()}catch(o){Q(bt(o,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(zc||"").trim();if(!i||!r||!await pn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const o=r.textContent||"Attach device history";r.textContent="Attaching…";try{await JC(i),Q("Old device history attached to you."),await e()}catch(s){Q(bt(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function YF(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function ff(e=YF()){const t=document.getElementById("syncMainView"),n=document.getElementById("syncDiagnosticsView");!t||!n||(e==="diagnostics"?(t.hidden=!0,n.hidden=!1):(t.hidden=!1,n.hidden=!0))}var Ow=!1;function XF(){Ow||(Ow=!0,window.addEventListener("hashchange",()=>{ff()}))}var hn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function QF(e){hn.loadSyncData=e}var ZF=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function eB(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=C.lastSyncCoordinatorAdminStatus?.readiness;if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent="Legacy Team/Space setup is ready. Technical controls are in Coordinator Administration.";return}const r=n==="partial"?"Finish legacy Team/Space setup before creating remote invites. Use Coordinator Administration to check what is missing.":"Configure a coordinator URL, group, and admin secret before creating remote invites. Use Coordinator Administration to finish legacy Team/Space setup.";e.disabled=!0,t.hidden=!1,t.textContent=r}function mf(){const e=document.getElementById("syncAdminDisclosureMount");e&&o1(e,{open:_w,onOpenChange:t=>{V1(t),mf(),Jc(),hf()}})}function tB(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function hf(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(C.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(C.lastTeamInvite?.warnings)?C.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Wc(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=C.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function Jc(){const e=document.getElementById("syncInvitePolicyMount");e&&ft(e,b(nr,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==hn.invitePolicy&&(hn.invitePolicy=n,Jc())},options:ZF,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:hn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function nB(e,t){mf(),Jc();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),o=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),f=document.getElementById("syncProjectInviteReviewHeading"),m=document.getElementById("syncRecipientName"),v=document.getElementById("syncRecipientDeviceName");let g="",h,y=0;r?.addEventListener("click",()=>{hs()||Q("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(_,I)=>{if(!u||!m||!v)return"other";const P=await Wf(_);if(I!==y||d?.value.trim()!==_)return"stale";if(h=P.kind,P.kind!=="project_share_invite")return"other";const k=(P.projects??[]).map(A=>`${A.display_name} (${A.existing_memory_count} existing ${A.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${P.inviter_name||"A teammate"} invited you${P.team_name?` through ${P.team_name}`:""} to share ${k||"selected projects"}.`),m.value=Ci(P.recipient_name),v.value=Ci(P.device_name),u.hidden=!1,g=_,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==g&&(g="",h=void 0,u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const _=o.value.trim(),I=Number(s.value);let P=!0;if(_?Na(o):P=ro(o,"Team name is required."),!I||I<1?P=ro(s,"Must be at least 1 hour."):Na(s),!!P){i.disabled=!0,i.textContent="Creating…";try{const k=await Hf({group_id:_,policy:hn.invitePolicy,ttl_hours:I||24});C.lastTeamInvite=k,hf(),c.value=String(k.encoded||""),c.hidden=!1,c.focus(),c.select();const A=Array.isArray(k.warnings)?k.warnings:[];Q(A.length?`Invite created. Copy it above and review ${A.length===1?"1 warning":`${A.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",A.length?"warning":"success")}catch(k){Q(bt(k,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",_=>{Ni(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){ro(d,"Paste a team invite or pairing payload.");return}if(Na(d),g!==_){const P=y;try{const k=await w(_,P);if(k==="project"||k==="stale")return}catch{}if(P!==y||d.value.trim()!==_)return;g=_,l.textContent="Accept invite";return}const I=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(I){const P=k=>Ci(k)==="";if(P(I.recipient_name)){m&&ro(m,"Enter a human-readable name using 120 characters or fewer.");return}if(P(I.device_name)){v&&ro(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const P=await pl(_,I,h);C.lastTeamJoin=P;const k=P,A=typeof k.type=="string"?k.type:"team_join";let L;if(A==="pair"){const F=String(P.peer_device_id??"").trim();L={message:F?`Paired with device ${F.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(A==="project_share"){const F=k.restart_required===!0||k.setup_state==="pending_inviter"||P.status==="pending_setup",T=typeof k.detail=="string"?k.detail.trim():"";L=F?{message:T||(k.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":k.setup_state==="pending_inviter"?"Project invitation accepted. Waiting for the inviter to finish setup.":"Project invitation accepted. Setup is still pending."),tone:"warning"}:{message:"Project invitation accepted.",tone:"success"}}else L={message:P.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};C.syncJoinFlowFeedback=L,Wc(),d.value="",g="",u&&(u.hidden=!0);try{await t()}catch(F){L={message:bt(F,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},C.syncJoinFlowFeedback=L,Wc()}}catch(P){C.syncJoinFlowFeedback={message:bt(P,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Wc(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const _=await yl(),I=cw(_);Q(I.message,I.warning?"warning":void 0)}catch(_){Q(bt(_,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function gf({element:e,hidden:t=!1,restoreParent:n=null}){const r=q(null);return It(()=>{e&&(e.hidden=t)},[e,t]),It(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function rB({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(z,{children:[a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Invite a teammate.",a("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?a(gf,{element:e,hidden:!t,restoreParent:n}):null]})}function iB(){return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Pair another device.",a("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),a("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>Oo("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function oB({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return a(z,{children:[a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:["Accept an invite or pairing.",a("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?a(gf,{element:e,hidden:!t,restoreParent:n}):null]})}function aB({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return a(z,{children:[u?a(z,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:["Join this device.",a("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?a(gf,{element:r,hidden:!1,restoreParent:o}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:["This device is not on the team yet.",a("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):a(z,{children:[a(oB,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(rB,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(iB,{}):null]})}function Yc({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function Xc({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function sB({item:e,onAction:t}){const[n,r]=x(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function cB({request:e,onApprove:t,onDeny:n}){const[r,i]=x(null),[o,s]=x(null),[c,l]=x("Approve"),[d,u]=x("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(ni,{feedback:o})]})}function lB({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,o]=x(null),[s,c]=x(null),l=e.actionLabel||"Pair with this device",[d,u]=x(l),[p,f]=x("Remove broken device record");return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{o("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const m=await r(e)||null;c(m),u(m?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{o(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(z,{children:[a("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),a("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{o("remove"),f("Removing…");try{c(await n(e)||null),f("Remove broken device record")}catch{f("Retry")}finally{o(null)}},children:p})]}):null]}),a(ni,{feedback:s})]})}function dB(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(z,{children:[r?a(Yc,{label:"Needs attention"}):null,r?a(Xc,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(sB,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function uB({children:e}){return e?a(z,{children:[a(Yc,{label:"Add devices & teammates"}),a(Xc,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function pB({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!C.syncDiscoveredFeedback?null:rn(a(z,{children:[a(Yc,{count:t.length||void 0,label:"Devices waiting for review"}),a(Xc,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(ni,{feedback:C.syncDiscoveredFeedback}),t.map(o=>a(lB,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function fB({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!C.syncJoinRequestsFeedback?null:rn(a(z,{children:[a(Yc,{count:t.length||void 0,label:"Join requests to review"}),a(Xc,{children:"Approve or deny requests here before those devices become part of the team."}),a(ni,{feedback:C.syncJoinRequestsFeedback}),t.map(i=>a(cB,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function Mw(e){return a(z,{children:[a(dB,{...e}),a(uB,{children:e.children}),a(fB,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(pB,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function Fw(e){e&&(e.textContent="")}function Qc(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function mB(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ea(){return mB()?"auto":"smooth"}var vf="syncTeamActionsMount",hB="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function gB(e,t,n=!1){return e.length>1&&(!t||n)}function vB(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function yB(e,t){const n=document.createElement("div");n.id=vf,e.appendChild(n),ft(n,b(Mw,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function Bw(e,t){const n=document.getElementById(vf);n&&(eo(n),n.remove()),Fw(e),t.forEach(r=>{Fw(r)})}function Aa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;mf(),Jc(),hf(),Wc(),eB();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");ur("syncTeamSkeleton"),tB();const p=C.lastSyncCoordinator,f=C.lastSyncViewModel||{primaryStatus:vw({status:C.lastSyncStatus,coordinator:p,peers:C.lastSyncPeers,shareOperations:C.lastShareOperations,shareOperationsLoadError:C.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},m=E=>{if(E.kind==="possible-duplicate-person"){const G=document.getElementById("syncActorsList");G instanceof HTMLElement&&(G.scrollIntoView({block:"center",behavior:Ea()}),Qc(G));return}const S=String(E.deviceId||"").trim();if(!S)return;if(E.kind==="name-device"){const G=document.querySelector(`[data-device-name-input="${CSS.escape(S)}"]`);if(G instanceof HTMLInputElement){G.scrollIntoView({block:"center",behavior:Ea()}),G.focus(),G.select(),Qc(G);return}}const D=document.querySelector(`[data-peer-device-id="${CSS.escape(S)}"]`);if(D instanceof HTMLElement){D.scrollIntoView({block:"center",behavior:Ea()}),Qc(D);return}const H=document.querySelector(`[data-discovered-device-id="${CSS.escape(S)}"]`);H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:Ea()}),Qc(H))},v=async E=>{const S=Array.isArray(E.actorIds)?E.actorIds.map(ae=>String(ae||"").trim()).filter(Boolean):[],D=(Array.isArray(C.lastSyncActors)?C.lastSyncActors:[]).filter(ae=>S.includes(String(ae?.actor_id||"").trim()));if(D.length<2){Q("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const H=await mx({title:"Review possible duplicate people",summary:E.title.replace(/^Possible duplicate person:\s*/,""),actors:D.map(ae=>({actorId:String(ae?.actor_id||""),label:String(ae?.display_name||ae?.actor_id||"Unknown person"),isLocal:!!ae?.is_local}))});if(H.action==="different-people"){eF(S,"different-people"),Q("Okay. I will keep these people separate on this device."),await hn.loadSyncData();return}if(H.action!=="merge")return;const G=D.find(ae=>String(ae?.actor_id||"")===H.primaryActorId),oe=D.find(ae=>String(ae?.actor_id||"")===H.secondaryActorId);if(!G?.actor_id||!oe?.actor_id){Q("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await dm(String(G.actor_id),String(oe.actor_id)),tF(S),Q(`Combined duplicate people into ${String(G.display_name||G.actor_id)}.`),await hn.loadSyncData()}catch(ae){try{await hn.loadSyncData()}catch{}Q(bt(ae,"Failed to combine these people."),"warning")}},g=async E=>await Du({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:E,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:S=>S.trim()?null:"Enter a device name to pair this device."}),h=!!p?.configured,y=G1(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?vB(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!h){Bw(n,[c,u]),t.hidden=!1,n.hidden=!1,yB(n,f.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const _=String(p.presence_status||""),I=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[],P=Array.isArray(f.attentionItems)?f.attentionItems:[],k=Array.isArray(p.discovered_devices)?p.discovered_devices:[],A=String(p.coordinator_url||"").trim(),L=k.map(E=>{const S=String(E.device_id||"").trim(),D=String(E.display_name||"").trim(),H=dw({coordinatorName:D,deviceId:S})||"Discovered device",G=S&&H!==S?S:null,oe=String(E.fingerprint||"").trim(),ae=String(E.incoming_reciprocal_request_id||"").trim(),ee=Array.isArray(E.groups)?E.groups.map(it=>String(it||"").trim()).filter(Boolean):[],ie=I.find(it=>String(it?.peer_device_id||"")===S),Ce=gB(ee,!!ie,E.needs_local_approval===!0),Ie=sw({device:E,pairedLocally:!!ie}),Ne=String(ie?.fingerprint||"").trim(),le=!!ie&&!!oe&&!!Ne&&Ne!==oe,ye=C.pendingCoordinatorApprovalsByDeviceId.get(S),Y=E.needs_local_approval===!0&&ye?.coordinatorUrl===A&&ye?.incomingRequestId===ae,ce=Y?"approval-pending":E.needs_local_approval===!0?"needs-local-approval":"not-required",ge=!Y&&!y&&d1({device:E,hasAmbiguousCoordinatorGroup:Ce,pairedLocally:!!ie}),pe=Array.isArray(E.addresses)?E.addresses:[],He=Number(E.address_count??0),de=Number.isFinite(He)&&He>0?He:0,W=[pe.length?pe.map(it=>Fo()?Pw(String(it||"")):String(it||"")).filter(Boolean).join(" · "):de>0?`${de} ${E.stale?"last-known":"fresh"} ${de===1?"address":"addresses"} hidden`:"No fresh addresses"];!pe.length&&G&&W.push(`device id: ${S}`);let Pe=null,re=ge?"accept":"none",je=null;return le?re="conflict":Y?(Pe="Waiting for refreshed coordinator status. You do not need to approve again.",re="approval-pending"):y&&(!ie||Ie.state==="needs-your-approval")?(Pe=y.message,re="setup-blocked"):Ce?(Pe="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",re="ambiguous"):ie&&Zp(S)?(Pe="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",re="scope-pending"):ie?.last_error?(W.push(`error: ${String(ie.last_error)}`),ge||(re="paired")):ie?.status?.peer_state?(W.push(`status: ${String(ie.status.peer_state)}`),ge||(re="paired")):!ie&&E.stale?(Pe="Wait for a fresh coordinator presence update, then review this device again here.",re="stale"):ie&&!ge&&(re="paired"),re==="paired"&&(je=Ie.state==="waiting-for-other-device"?Ie.description||"Waiting on the other device.":String(ie?.last_error||"").toLowerCase().includes("401")&&String(ie?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:Pe,actionLabel:Ie.actionLabel||(ie?"Review device":"Pair with this device"),approvalBadgeLabel:Y?"Approval sent":Ie.badgeLabel,approvalState:ce,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:le?bw.conflicts:ie?bw.pairedLocally:"Not connected on this device",coordinatorUrl:A,deviceId:S,displayName:H,displayTitle:G,fingerprint:oe,groupId:ee[0]??"",incomingRequestId:ae,mode:re,note:W.join(" · "),pairedMessage:je}}),F=new Set(L.filter(E=>E.approvalState==="approval-pending").map(E=>E.deviceId)),T=P.filter(E=>!E.deviceId||!F.has(E.deviceId)),M=[],j=L.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),B=L.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,U=T.length+M.length+B;l&&(l.hidden=j.length===0&&!C.syncDiscoveredFeedback),d&&(d.textContent=j.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=M.length===0&&!C.syncJoinRequestsFeedback),Bw(n,[c,u]);const $=document.createElement("div");$.id=vf,n.appendChild($),ft($,b(Mw,{actionItems:T,actionableCount:U,children:b(aB,{invitePanel:r,invitePanelOpen:Jp,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:Yp,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(z1(!Jp),Aa())},onToggleJoinPanel:()=>{o&&(W1(!Yp),Aa())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:_}),discoveredListMount:u,discoveredRows:j,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await v(E);return}m(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const S=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if(S instanceof HTMLElement){S.scrollIntoView({block:"center",behavior:Ea()}),Q(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}Q("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await pn({title:`Remove ${E.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Jf(E.deviceId);const S={message:`Removed the broken local device record for ${E.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return C.syncDiscoveredFeedback=S,await hn.loadSyncData(),S}catch(S){return{message:bt(S,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async E=>{try{const S=await g(E.displayName);return S?await bB(E,S):null}catch(S){return{message:bt(S,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:M,presenceStatus:_,primaryStatus:f.primaryStatus}))}async function bB(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await cC(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&C.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];C.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],Y1(e.deviceId);let u=n?{message:hB,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};C.syncDiscoveredFeedback=u,n&&Aa();try{t.trim()!==l.trim()&&(await Yf(e.deviceId,t.trim()),C.pendingAcceptedSyncPeers=C.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":bt(p,"Device connected, but naming did not finish."),tone:"warning"}}C.syncDiscoveredFeedback=u;try{await hn.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":bt(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},C.syncDiscoveredFeedback=u}return u}function _B(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function io(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function Uw(e){return io(e)?"Unclear project identity":e.displayProject}function Ut(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function wB(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function SB(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CB(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function IB(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function PB(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function RB(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function kB({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",PB(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:RB(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function qw(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${SB(t)}\\b`,"g"),CB(t,n))),r}function TB(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function NB({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function EB({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(S=>[S.workspaceIdentity,S.suggestedScopeId??""])),[s,c]=x({}),[l,d]=x({}),[u,p]=x(o),[f,m]=x({}),[v,g]=x("all"),[h,y]=x(""),[w,_]=x(null),I=r.length,P=e.totalGroupCount??I,k=r.filter(io).length,A=r.filter(S=>S.suggestedScopeId&&!io(S)&&Ut(S)).length,L=r.filter(S=>f[S.workspaceIdentity]&&Ut(S)).length,F=r.filter(S=>f[S.workspaceIdentity]&&Ut(S)&&!!u[S.workspaceIdentity]).length,T=r.filter(S=>{const D=io(S);return v==="suggested"&&(!S.suggestedScopeId||D)||v==="cleanup"&&!D||v==="no-suggestion"&&(S.suggestedScopeId||D)||v==="selected"&&!f[S.workspaceIdentity]?!1:!h.trim()||TB(S,i).includes(h.trim().toLowerCase())});async function M(S){const D=u[S.workspaceIdentity]||S.suggestedScopeId||"";if(!(!D||!t||w)){_(S.workspaceIdentity),d(H=>{const G={...H};return delete G[S.workspaceIdentity],G});try{const H=await t(S,D,!!s[S.workspaceIdentity],s[S.workspaceIdentity]?.confirmation_token);c(H?G=>({...G,[S.workspaceIdentity]:H}):G=>{const oe={...G};return delete oe[S.workspaceIdentity],oe})}catch(H){d(G=>({...G,[S.workspaceIdentity]:qw(H,D,i)}))}finally{_(null)}}}function j(S,D){p(H=>({...H,[S.workspaceIdentity]:D})),c(H=>{const G={...H};return delete G[S.workspaceIdentity],G}),d(H=>{const G={...H};return delete G[S.workspaceIdentity],G})}function B(S,D){m(H=>({...H,[S.workspaceIdentity]:D}))}function U(S){m(D=>({...D,...Object.fromEntries(T.filter(Ut).map(H=>[H.workspaceIdentity,S]))}))}function $(){m(S=>({...S,...Object.fromEntries(r.filter(D=>D.suggestedScopeId&&!io(D)&&Ut(D)).map(D=>[D.workspaceIdentity,!0]))}))}async function E(){if(!t||w||F===0)return;const S=r.filter(D=>f[D.workspaceIdentity]&&Ut(D)&&!!u[D.workspaceIdentity]);if(!S.every(D=>s[D.workspaceIdentity])){_("bulk");try{for(const D of S){if(s[D.workspaceIdentity])continue;const H=u[D.workspaceIdentity]||D.suggestedScopeId||"";if(H)try{const G=await t(D,H,!1);d(oe=>{const ae={...oe};return delete ae[D.workspaceIdentity],ae}),G&&c(oe=>({...oe,[D.workspaceIdentity]:G}))}catch(G){d(oe=>({...oe,[D.workspaceIdentity]:qw(G,H,i)}))}}}finally{_(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[P.toLocaleString()," older"," ",P===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",I<P?` Showing ${I.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${I.toLocaleString()}`],["suggested",`Suggested ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${k.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([S,D])=>a("button",{className:v===S?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>g(S),type:"button",children:D},S))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:S=>y(S.currentTarget.value),placeholder:"Search project, signal, or destination…",value:h}),a("button",{className:"settings-button",onClick:()=>U(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:$,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>U(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:w!=null||F===0||r.filter(S=>f[S.workspaceIdentity]&&Ut(S)&&!!u[S.workspaceIdentity]).every(S=>s[S.workspaceIdentity]),onClick:()=>{E()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&L>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(S=>f[S.workspaceIdentity]&&Ut(S)&&!!u[S.workspaceIdentity]).every(S=>s[S.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:T.map(S=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${Uw(S)}`,checked:!!f[S.workspaceIdentity],className:"cm-checkbox",disabled:!Ut(S),onChange:D=>B(S,D.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:Uw(S)}),a("div",{className:"legacy-review-group-meta",children:[_B(S.identitySource),wB(S,i)]}),Ut(S)?S.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(S.reassignableMemoryCount??S.memoryCount).toLocaleString()," ","local memor",(S.reassignableMemoryCount??S.memoryCount)===1?"y":"ies"," ","can be reassigned; ",S.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",S.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),io(S)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[S.memoryCount.toLocaleString()," memor",S.memoryCount===1?"y":"ies"]})]}),S.suggestionReason?a("div",{className:"legacy-review-reason",children:S.suggestionReason}):null,l[S.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[S.workspaceIdentity]}):null,s[S.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[S.workspaceIdentity].warning," This will reassign"," ",s[S.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[S.workspaceIdentity].memory_count.toLocaleString()," memories",s[S.workspaceIdentity].skipped_memory_count?`; ${s[S.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(kB,{group:S}),i.length>0&&t&&Ut(S)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:D=>j(S,D.currentTarget.value),value:u[S.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(D=>a("option",{value:D.scopeId,children:[D.label," · ",IB(D.authorityType),D.scopeId===S.suggestedScopeId?" · suggested":""]},D.scopeId))]})]}):null,i.length>0&&t&&Ut(S)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[S.workspaceIdentity],onClick:()=>{M(S)},children:w===S.workspaceIdentity?s[S.workspaceIdentity]?"Reassigning…":"Previewing…":s[S.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},S.workspaceIdentity))}):null]})}function AB({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(z,{children:[t?a(EB,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(NB,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function xB(){dv("mine"),C.feedQuery="",window.location.hash="feed"}function DB(){window.location.hash="projects"}async function $B(e,t,n,r){try{const i=await GC({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return C.lastSyncLegacySharedReview=i.legacy_shared_review??null,Q(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),Gw(),null}catch(i){if(i instanceof Qf)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Q(o,"warning"),new Error(o)}}function Gw(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(C.lastSyncSharingReview)?C.lastSyncSharingReview:[],o=C.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,v=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:v,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){eo(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=C.currentProject?`current project (${C.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));ft(n,b(AB,{items:d,legacyReview:c,onLegacyReassign:$B,onLegacyReview:DB,onReview:xB}))}var Zc="";function LB(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of C.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){C.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||C.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function jB(){return[...C.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var xa=null,yf=0,OB=15e3;function Hw(e){return`project:${e||""}|includeJoinRequests:false`}function MB(e){const t=Hw(e);return!xa||xa.key!==t||Date.now()>=xa.expiresAtMs?null:xa.payload}function FB(e,t){xa={key:Hw(e),expiresAtMs:Date.now()+OB,payload:t}}function BB(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function UB(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function oo(){const e=++yf;try{const t=C.currentProject||"",n=!1,r=C.activeTab==="health";let i=!1;const o=!Fo();let s;r?(s=MB(t),s||(s=await Ua(o,t,{includeJoinRequests:!1}),i=!0)):(s=await Ua(o,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=C.lastDeviceIdentityInventory,u=C.lastShareOperations,p=!1,f=!1,m=C.deviceIdentityInventoryLoadError,v=!1;const g=Z1();try{c=await aC()}catch{p=!0}try{l=await ul()}catch{f=!0}if(C.activeTab==="advanced"){m=!1;try{d=await vl()}catch{m=!0}}try{const P=await lm();u=Array.isArray(P.items)?P.items:[]}catch{v=!0}if(e!==yf)return;i&&FB(t,BB(s)),LB(s.coordinator);const h=JSON.stringify([s,c,l,d,m,u,v,g,jB()]);if(h===Zc)return;Zc=h;const y=s.status&&typeof s.status=="object"?s.status:null;y&&(C.lastSyncStatus=y),Array.isArray(c?.items)?C.lastSyncActors=c.items:C.lastSyncActors=[];const w=Array.isArray(s.peers)?s.peers:[],_=new Set(w.map(P=>String(P?.peer_device_id||"").trim()).filter(Boolean)),I=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(P=>{const k=String(P?.peer_device_id||"").trim();return k&&!_.has(k)}):[];C.pendingAcceptedSyncPeers=I,C.lastSyncPeers=[...w,...I],m||(C.lastDeviceIdentityInventory=d),C.deviceIdentityInventoryLoadError=m,C.lastShareOperations=u,C.shareOperationsLoadError=v,C.lastSyncSharingReview=s.sharing_review||[],C.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,C.lastSyncCoordinator=s.coordinator||null,C.lastSyncCoordinatorAdminStatus=l&&typeof l=="object"?l:null,C.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],C.lastSyncAttempts=s.attempts||[],C.lastSyncLegacyDevices=s.legacy_devices||[],C.lastSyncDuplicatePersonDecisions=g,C.lastSyncViewModel=K1({actors:C.lastSyncActors,peers:C.lastSyncPeers,coordinator:C.lastSyncCoordinator,status:y,shareOperations:C.lastShareOperations,shareOperationsLoadError:v,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:C.lastSyncDuplicatePersonDecisions}),Nw(),Aa(),KF(),zF(),Gw(),pf(),jw(),Tw(),u_(),p&&VF(),f&&(C.lastSyncCoordinatorAdminStatus=null,Aa())}catch{if(e!==yf)return;Zc="",C.deviceIdentityInventoryLoadError=!0,ur("syncTeamSkeleton"),ur("syncActorsSkeleton"),ur("syncPeersSkeleton"),ur("syncDiagSkeleton"),UB(),WF(),sF()}}function qB(){Zc="",C.lastSyncPeers?.length&&pf()}async function GB(){try{const e=await sC();C.pairingPayloadRaw=e||null,af()}catch{C.pairingPayloadRaw=null,af()}}function HB(e){qM(),ic(),QF(oo),HF(oo),uF(pf),nB(e,oo),JF(oo),pF(e),ff(),XF()}function KB(e,t){const n=Le("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function VB(){try{const e=await QS();if(!e?.version)return;KB(e.version,"7b56c01")}catch{}}var bf=null,Kw=1500,Vw="codemem-legacy-upgrade-notice-dismissed",fr=null,gn=!1,_f=!1,Da=null;function zw(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function Ww(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=zw(n.total_group_count,r.length),o=zw(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function Jw(){try{return localStorage.getItem(Vw)==="1"}catch{return!1}}function el(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(Vw,"1")}catch{}}function Yw(){const e=Le("legacyUpgradeModal");return!e||e.hidden?[]:Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(t=>!t.hidden&&t.offsetParent!==null)}function zB(){const e=Yw(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function Xw(e){const t=Le("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),el(),$a(!1);return}if(e.key==="Enter"){const o=Le("legacyUpgradeReviewGroups");Ni(e,{onSubmit:()=>o?.click(),disabled:!o||o.disabled});return}if(e.key!=="Tab")return;const n=Yw();if(n.length===0)return;const r=n[0],i=n[n.length-1];if(e.shiftKey&&document.activeElement===r){e.preventDefault(),i.focus();return}!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus())}function Qw(e){for(const t of document.querySelectorAll("header, .tab-bar, .tab-panel, #toastRoot, #viewerReconnectOverlay, #settingsDialogMount"))t.id==="viewerReconnectOverlay"&&t.hidden||(t.inert=e,e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}function $a(e,t){const n=Le("legacyUpgradeModalBackdrop"),r=Le("legacyUpgradeModal"),i=Le("legacyUpgradeSummary");if(!(!n||!r||!i)){if(t&&(i.textContent=`${t.groupCount.toLocaleString()} older ${t.groupCount===1?"project needs":"projects need"} a Sharing domain. They contain ${t.memoryCount.toLocaleString()} older shared memories total; you will review the projects, not individual memories.`),n.hidden=!e,r.hidden=!e,e){Da=document.activeElement,document.addEventListener("keydown",Xw),zB(),Qw(!0);return}Qw(!1),document.removeEventListener("keydown",Xw),Da&&document.contains(Da)&&Da.focus(),Da=null}}function Zw(e){!e||_f||Jw()||(_f=!0,$a(!0,e))}async function WB(){if(!(_f||Jw()))try{Zw(Ww(await Ua(!1,"",{includeJoinRequests:!1})))}catch{}}function ri(e,t){const n=Le("viewerReconnectOverlay"),r=Le("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function wf(){try{return await XS(),!0}catch{return!1}}function JB(){return document.visibilityState!=="hidden"&&!X_()}function eS(){if(gn)return;gn=!0,Sf(),ii("error","(reconnecting)"),ri(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await wf()){if(fr&&(clearTimeout(fr),fr=null),gn=!1,ri(!0,"Viewer responded. Restoring your session…"),JB()){ii("refreshing"),La();try{await tl()}catch{}}else ii("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");gn||ri(!1);return}ri(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),fr=setTimeout(e,Kw)};fr=setTimeout(e,Kw)}function ii(e,t){C.refreshState=e;const n=Le("refreshStatus");if(!n)return;const r=o=>{const s=Le("refreshAnnouncer");!s||bf===e||(s.textContent=o,bf=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,bf=null}function Sf(){C.refreshTimer&&(clearInterval(C.refreshTimer),C.refreshTimer=null)}function La(){C.refreshTimer||(C.refreshTimer=setInterval(()=>mr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Sf(),ii("paused","(tab hidden)")):!X_()&&!gn&&(La(),mr())});function tS(){const e=C.advancedSection==="sync",t=Le("advancedSyncContent"),n=Le("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Le("advancedSyncButton"),i=Le("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const o=window.location.hash.replace(/^#/,"");ff(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function nS(e){const t=new Set(Qk(C.lastCoordinatorAdminStatus));Er.forEach(n=>{const r=Le(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),Er.forEach(n=>{const r=Le(`tabBtn-${n}`);if(!r)return;r.hidden=!t.has(n);const i=n===e&&t.has(n);r.classList.toggle("active",i),i?r.setAttribute("aria-current","page"):r.removeAttribute("aria-current")}),tS()}function oi(e,t={}){const n=Mo(e,C.lastCoordinatorAdminStatus);n==="advanced"&&$d(t.advancedSection??Dd()??C.advancedSection),lv(n,t.canonicalHash?{canonicalHash:!0}:{}),nS(n),mr()}function YB(){Er.forEach(e=>{Le(`tabBtn-${e}`)?.addEventListener("click",()=>oi(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Le("advancedSyncButton")?.addEventListener("click",()=>$d("sync",!0)),Le("advancedTeamsButton")?.addEventListener("click",()=>{$d("teams",!0),tS(),queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}),Le("coordinatorAdminOpenSharing")?.addEventListener("click",()=>{oi("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=xd();if(e){const t=Dd();oi(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}}),oi(C.activeTab)}async function XB(){try{const e=await Fa();C.knownProjects=e,qB();const t=Nd("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function QB(e){C.pendingDeviceIdentityFocus=e?.trim()||null,oi("devices",{canonicalHash:!0})}var ja=XR({},{onOpenTeamSetup:R_,onReviewDevices:QB}),rS={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Cf=0,If=null,qt=null;async function ZB(){const e=[];let t=0;for(;;){const n=await ho({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return fs(e)}function eU(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of C.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of C.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=Ta(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function tU(){return C.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function iS(e){if(e==="advanced_sync"){oi("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}oi(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function Pf(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=nU(e,++Cf);return If=t,t}async function nU(e,t){qt||dc(e,rS,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,o]=await Promise.all([ZB(),gl(),kC(),vl().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:qt?.inventory,unavailable:!0})),oo()]);if(t!==Cf)return If??!1;const s=eU(),c=tU(),l=um(C.lastSyncStatus);return!o.unavailable&&o.inventory&&(C.lastDeviceIdentityInventory=o.inventory),C.deviceIdentityInventoryLoadError=o.unavailable,dc(e,r,i,n,s,{inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:l,onCommitted:async()=>{const[d,u]=await Promise.all([Pf(),ja()]);return d&&u},onNavigate:iS,peerRuntimeMetadata:c}),qt={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==Cf?If??!1:(qt?dc(e,qt.intent,qt.reconciliation,qt.projects,qt.availability,{coordinatorEnrollmentIssueCount:qt.coordinatorEnrollmentIssueCount,inventory:qt.inventory,inventoryUnavailable:qt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Pf(),ja()]);return n&&r},onNavigate:iS,peerRuntimeMetadata:qt.peerRuntimeMetadata,refreshError:!0}):dc(e,rS,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Nd("projectFilter")?.addEventListener("change",()=>{C.currentProject=Nd("projectFilter")?.value||"",Jr(!0),mr()});var Rf=null;async function mr(){gn||(Rf&&clearTimeout(Rf),Rf=setTimeout(()=>tl(),80))}async function tl(){if(!gn){if(C.refreshInFlight){C.refreshQueued=!0;return}C.refreshInFlight=!0;try{ii("refreshing");const e=C.activeTab,t=[tj(),lM()];let n=!0;if(e==="feed"){const i=Kx();t.push($y(i))}e==="feed"&&t.push(Cp()),e==="projects"&&t.push(Pa()),e==="sharing"&&t.push(ja()),e==="devices"&&t.push(Pf().then(i=>{n=i})),(e==="advanced"&&C.advancedSection==="sync"||e==="health")&&t.push(oo()),e==="advanced"&&C.advancedSection==="teams"&&t.push(sc()),C.syncPairingOpen&&t.push(GB()),await Promise.all(t),Zw(Ww(C.lastSyncLegacySharedReview));const r=Mo(C.activeTab,C.lastCoordinatorAdminStatus);r!==C.activeTab&&lv(r),nS(C.activeTab),ii(n?"idle":"error")}catch{await wf()?ii("error"):eS()}finally{C.refreshInFlight=!1,C.refreshQueued&&!gn&&(C.refreshQueued=!1,tl())}}}sT();var oS=document.getElementById("toastRoot");oS&&qk(oS);var aS=document.getElementById("legacyTeamSetupMount");aS&&Yj(aS,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(C.activeTab==="sharing"?(t=await Pa(n),e=await ja(n)):(e=await ja(n),t=await Pa(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),cT(Ed("themeToggle")),fv(jd()),YB(),UL(),DO(()=>mr(),{onOpenTeamSetup:R_}),HB(()=>mr()),Qx(),BM(Sf,La,()=>mr()),XB(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(ri(!0,"Checking whether the viewer server is back…"),!await wf()){eS();return}fr&&(clearTimeout(fr),fr=null),gn=!1,ri(!0,"Viewer responded. Restoring your session…"),La();try{await tl()}catch{}gn||ri(!1)}),Le("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{el(),$a(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Le("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{el(),$a(!1),window.location.hash="projects"}),Le("legacyUpgradeNotNow")?.addEventListener("click",()=>{el(),$a(!1)}),VB(),WB(),mr(),La()})();
|