@codemem/server 0.44.0-beta.1 → 0.44.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/index.d.ts.map +1 -1
- package/dist/index.js +464 -45
- package/dist/index.js.map +1 -1
- package/dist/routes/diagnostics.d.ts +31 -0
- package/dist/routes/diagnostics.d.ts.map +1 -0
- package/dist/routes/memory.d.ts.map +1 -1
- package/dist/routes/pack.d.ts.map +1 -1
- package/dist/routes/stats.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +37 -37
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +207 -19
package/static/app.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
(function(){var Bf=Object.defineProperty,ES=(e,t)=>{let n={};for(var r in e)Bf(n,r,{get:e[r],enumerable:!0});return t||Bf(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 Uf(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 AS(){return Oe("/api/observer-status")}async function xS(){return Oe("/api/config")}async function DS(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 qf(e){return Oe(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function $S(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 LS(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 jS(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 OS(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 MS(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 FS(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 Gf(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 BS(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 US(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 qS(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 Hf(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 GS(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 HS(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 KS(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 VS(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 zS(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 Kf(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 Vf(e,t){const n=Uf(e,t?.limit,t?.offset,t?.scope,t?.q);return Oe(`/api/observations?${n}`)}async function WS(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 JS(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 YS(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 zf(e,t){const n=Uf(e,t?.limit,t?.offset,t?.scope,t?.q);return Oe(`/api/summaries?${n}`)}async function XS(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 QS(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 ZS(){return Oe("/api/runtime")}async function Fa(){return(await Oe("/api/projects")).projects||[]}async function eC(){return Oe("/api/stats")}async function tC(e){return Oe(`/api/usage?project=${encodeURIComponent(e)}`)}async function nC(e){return Oe(`/api/session?project=${encodeURIComponent(e)}`)}async function rC(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"}},iC=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 oC(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,iC.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 aC=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"]),Wf=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&&aC.has(c)?new Wf(l,c):new Error(l)}return o}async function Jf(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 sC(){return Oe("/api/sync/actors")}async function cC(e=!1){return Oe(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function Yf(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 Xf(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 lC(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 Qf=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??[]}},Zf=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,em=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"]),dC=new Set(["coordinator_route_missing","coordinator_rejected_manifest","coordinator_unreachable","local_candidate_scan_budget_exceeded","coordinator_roster_unavailable"]),uC=new Set(["needs_setup","in_progress","stale","ready"]),pC=new Set(["reviewing","ready_to_finish","unavailable","completed"]),fC=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 Gn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function Ht(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 tm(e){return et(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&uC.has(e.status)&&br(e.deviceCount)&&br(e.projectCount)&&br(e.unresolvedDeviceCount)&&br(e.unresolvedProjectCount):!1}function mC(e){return et(e)&&e.version===ml&&tn(e.candidates,t=>tm(t)&&t.status!=="ready")}function hC(e){return et(e)?e.kind==="absent"||e.kind==="existing"&&br(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function Hn(e){return!et(e)||!Gn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&fC.has(e.blockedReason)}function gC(e){return!et(e)||!Gn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:Hn(e.assignIdentity)&&Hn(e.include)&&Hn(e.exclude)&&Hn(e.remove)&&Hn(e.clearDecision)}function vC(e){return et(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&Ht(e.existingIdentityRef)&&Ht(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&Ht(e.targetIdentityRef)&&hC(e.expectation)&&gC(e.actions):!1}function yC(e){return et(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&Ht(e.canonicalProjectRef)&&Ht(e.resolvedProjectRef)&&tn(e.mappingChoices,t=>et(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&et(e.actions)&&Gn(e.actions,["map"])&&Hn(e.actions.map):!1}function bC(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"&&Ht(n.fromCanonicalProjectRef)&&Ht(n.fromResolvedProjectRef)&&Ht(n.fromResolvedProjectDisplayName)&&Ht(n.toCanonicalProjectRef)&&Ht(n.toResolvedProjectRef)&&Ht(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 _C(e){return et(e)&&Gn(e,["finish","refresh"])&&Hn(e.refresh)&&Hn(e.finish)}function nm(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&&tm(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&pC.has(e.state)&&br(e.unresolvedDeviceCount)&&br(e.unresolvedProjectCount)&&tn(e.devices,vC)&&tn(e.projects,yC)&&_C(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"?Gn(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"&&bC(e.accessDelta):e.state==="unavailable"?Gn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&em.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&nm(n,r,"setup_unavailable"):e.state==="completed"?Gn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&nm(n,r,"setup_completed"):Gn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function wC(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 Nt=class extends Error{statusCode;errorCode;reason;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.reason=n,this.name="LegacyTeamSetupApiError"}};function Kn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function Vn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new Nt(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 Nt(r.status,"team_setup_failed")}if(!r.ok){const o=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=em.has(o)?o:"team_setup_failed",c=i&&typeof i=="object"&&"reason"in i&&typeof i.reason=="string"?i.reason:"",l=dC.has(c)?c:void 0;throw new Nt(r.status,s,l)}if(!t(i))throw new Nt(r.status,"team_setup_failed");return i}function li(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function rm(){return Vn(Kn(),mC)}function SC(e){return Vn(Kn(e),ci)}function CC(e,t,n){return Vn(`${Kn(e)}/devices/${encodeURIComponent(t)}/assignment`,ci,li("PUT",n))}function IC(e,t,n){return Vn(`${Kn(e)}/devices/${encodeURIComponent(t)}/decision`,ci,li("PUT",n))}function RC(e,t,n){return Vn(`${Kn(e)}/devices/${encodeURIComponent(t)}/decision`,ci,li("DELETE",n))}function PC(e,t,n){return Vn(`${Kn(e)}/projects/${encodeURIComponent(t)}/mapping`,ci,li("PUT",n))}function kC(e){return Vn(`${Kn(e)}/refresh`,ci,li("POST",{}))}function TC(e,t){return Vn(`${Kn(e)}/finish`,wC,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 im(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 om(e){return im("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function am(e){return im("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function NC(){return Oe("/api/sync/recipient-policy/v1/reconciliation-status")}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){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 EC(e){return sm("/api/sync/recipient-policy/v1/edges/preview",e)}function AC(e){return sm("/api/sync/recipient-policy/v1/edges/commit",e)}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 xC(e){return cm("/api/sync/recipient-policy/v1/invites/preview",e)}function DC(e){return cm("/api/sync/recipient-policy/v1/invites",e)}async function $C(){const e=await Oe("/api/sync/recipient-policy/v1/review"),t=e.continuity??null;if(e.categoryCounts)return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:Math.max(0,e.categoryCounts.preservedContinuity),blockedRepair:e.blockedItems.length}};const n=Math.max(0,(t?.findingCount??0)-e.reviewItems.length);return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:n,blockedRepair:e.blockedItems.length}}}async function LC(){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 lm(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 jC(e){return lm("/api/sync/project-invites/preview",e)}function OC(e){return lm("/api/sync/project-invites",e)}function dm(){return Oe("/api/sync/share-operations")}function MC(e){return Oe(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function FC(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 BC(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 UC(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 qC(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 GC(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 HC(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 Qf(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 KC(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 Zf(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 VC(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 zC(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 WC(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 JC(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 um(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 YC(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 XC(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 QC(){return Oe("/api/update-status")}function ZC(e){return{current_version:"unknown",channel:null,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 pm(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,fm,mm,zn,hm,gm,vm,bl,Ha,vo,ym,_l,wl,Sl,bm,Ka={},Va=[],eI=/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??++fm,__i:-1,__u:0};return i==null&&he.vnode!=null&&he.vnode(o),o}function _m(){return{current:null}}function z(e){return e.children}function Ot(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 tI(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),Rl(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,km(r,o,i),t.__e=t.__=null,o.__e!=n&&wm(o)}}function wm(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}),wm(e)}function Il(e){(!e.__d&&(e.__d=!0)&&zn.push(e)&&!za.__r++||hm!=he.debounceRendering)&&((hm=he.debounceRendering)||gm)(za)}function za(){try{for(var e,t=1;zn.length;)zn.length>t&&zn.sort(vm),e=zn.shift(),t=zn.length,tI(e)}finally{zn.length=za.__r=0}}function Sm(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=nI(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=Rl(e,m,f,i,o,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Pl(f.ref,null,m),u.push(m.ref,m.__c||v,m)),g==null&&v!=null&&(g=v),4&m.__u?(l=Cm(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 nI(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=rI(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)),Nm(c,c));return r}function Cm(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=Cm(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 rI(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 Im(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||eI.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||Im(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Im(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(ym,"$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 Rm(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 Rl(e,t,n,r,i,o,s,c,l,d){var u,p,f,m,v,g,h,y,w,_,I,R,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],R=u?I?I.props.value:u.__:r,n.__c?y=(f=t.__c=n.__c).__=f.__E:(_?t.__c=f=new T(w,R):(t.__c=f=new Ot(w,R),f.constructor=T,f.render=oI),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,R),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(w,f.__s,R)===!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,R),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(v,g,h)})}if(f.context=R,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?Tm(u.props.children):u,c=Sm(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=iI(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 km(e,t,n){for(var r=0;r<n.length;r++)Pl(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 Tm(e){return typeof e!="object"||e==null||e.__b>0?e:yo(e)?e.map(Tm):e.constructor!==void 0?null:nn({},e)}function iI(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=""),Sm(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 Pl(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 Nm(e,t,n){var r,i;if(he.unmount&&he.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Pl(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]&&Nm(r[i],t,n||typeof e.type!="function");n||Cl(e.__e),e.__c=e.__=e.__e=void 0}function oI(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=[],Rl(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),km(o,e,s),e.props.children=null}function Em(e,t){We(e,t,Em)}function aI(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"+bm++,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}},fm=0,mm=function(e){return e!=null&&e.constructor===void 0},Ot.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))},Ot.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Il(this))},Ot.prototype.render=z,zn=[],gm=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,vm=function(e,t){return e.__v.__b-t.__v.__b},za.__r=0,bl=Math.random().toString(8),Ha="__d"+bl,vo="__a"+bl,ym=/(PointerCapture)$|Capture$/i,_l=0,wl=Rm(!1),Sl=Rm(!0),bm=0;var Sn,Be,kl,Am,di=0,xm=[],Je=he,Dm=Je.__b,$m=Je.__r,Lm=Je.diffed,jm=Je.__c,Om=Je.unmount,Mm=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,Wn(Bm,e)}function Wn(e,t,n){var r=Sr(Sn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Bm(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,Pe(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 Pe(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,Pe(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 sI(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 cI(){for(var e;e=xm.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,Dm&&Dm(e)},Je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Mm&&Mm(e,t)},Je.__r=function(e){$m&&$m(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){Lm&&Lm(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(xm.push(t)!==1&&Am===Je.requestAnimationFrame||((Am=Je.requestAnimationFrame)||lI)(cI)),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)}}),jm&&jm(e,t)},Je.unmount=function(e){Om&&Om(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 Fm=typeof requestAnimationFrame=="function";function lI(e){var t,n=function(){clearTimeout(r),Fm&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Fm&&(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 Bm(e,t){return typeof t=="function"?t(e):t}var dI=0,PU=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:--dI,__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=ES({Children:()=>Ir,Component:()=>Ot,Fragment:()=>z,PureComponent:()=>Xa,StrictMode:()=>z,Suspense:()=>_o,SuspenseList:()=>fi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>ih,cloneElement:()=>Rr,createContext:()=>wr,createElement:()=>b,createFactory:()=>oh,createPortal:()=>rn,createRef:()=>_m,default:()=>SI,findDOMNode:()=>lh,flushSync:()=>Qa,forwardRef:()=>J,hydrate:()=>Zm,isElement:()=>uh,isFragment:()=>ah,isMemo:()=>sh,isValidElement:()=>In,lazy:()=>Jm,memo:()=>qm,render:()=>Qm,startTransition:()=>$l,unmountComponentAtNode:()=>ch,unstable_batchedUpdates:()=>dh,useCallback:()=>se,useContext:()=>Cn,useDebugValue:()=>Tl,useDeferredValue:()=>Ll,useEffect:()=>K,useErrorBoundary:()=>sI,useId:()=>Cr,useImperativeHandle:()=>Ja,useInsertionEffect:()=>Ol,useLayoutEffect:()=>It,useMemo:()=>Pe,useReducer:()=>Wn,useRef:()=>q,useState:()=>x,useSyncExternalStore:()=>xl,useTransition:()=>jl,version:()=>wI});function Um(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 qm(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 Ot).isPureReactComponent=!0,Xa.prototype.shouldComponentUpdate=function(e,t){return Al(this.props,e)||Al(this.state,t)};var Gm=he.__b;he.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Gm&&Gm(e)};var uI=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=Um({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=uI,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Hm=function(e,t){return e==null?null:wn(wn(e).map(t))},Ir={map:Hm,forEach:Hm,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},pI=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)}pI(e,t,n,r)};var Km=he.unmount;function Vm(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=Um({},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 Vm(r,t,n)})),e}function zm(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return zm(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 Wm(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Jm(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),Km&&Km(e)},(_o.prototype=new Ot).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Wm(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]=zm(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]=Vm(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 Ym=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 fI(e){return this.getChildContext=function(){return e.context},e.children}function mI(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(fI,{context:t.context},e.__v),t.v)}function rn(e,t){var n=b(mI,{__v:e,h:t});return n.containerInfo=t,n}(fi.prototype=new Ot).__a=function(e){var t=this,n=Wm(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),Ym(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){Ym(e,n,t)})};var Xm=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,hI=/^(?: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]/,gI=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,vI=/[A-Z0-9]/g,yI=typeof document<"u",bI=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Qm(e,t,n){return t.__k??(t.textContent=""),We(e,t),typeof n=="function"&&n(),e?e.__c:null}function Zm(e,t,n){return Em(e,t),typeof n=="function"&&n(),e?e.__c:null}Ot.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Ot.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var eh=he.event;he.event=function(e){return eh&&(e=eh(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Ml,_I={configurable:!0,get:function(){return this.class}},th=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||yI&&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"||bI(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":gI.test(s)&&(s=l):l=s="oninput":o&&hI.test(s)?s=s.replace(vI,"-$&").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",_I)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Xm,th&&th(e)};var nh=he.__r;he.__r=function(e){nh&&nh(e),Ml=e.__c};var rh=he.diffed;he.diffed=function(e){rh&&rh(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 ih={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:Pe,useReducer:Wn,useRef:q,useState:x,useSyncExternalStore:xl,useTransition:jl}}},wI="18.3.1";function oh(e){return b.bind(null,e)}function In(e){return!!e&&e.$$typeof===Xm}function ah(e){return In(e)&&e.type===z}function sh(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Rr(e){return In(e)?aI.apply(null,arguments):e}function ch(e){return!!e.__k&&(We(null,e),!0)}function lh(e){return e&&(e.base||e.nodeType===1&&e)||null}var dh=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}},uh=In,SI={useState:x,useId:Cr,useReducer:Wn,useEffect:K,useLayoutEffect:It,useInsertionEffect:Ol,useTransition:jl,useDeferredValue:Ll,useSyncExternalStore:xl,startTransition:$l,useRef:q,useImperativeHandle:Ja,useMemo:Pe,useCallback:se,useContext:Cn,useDebugValue:Tl,version:"18.3.1",Children:Ir,render:Qm,hydrate:Zm,unmountComponentAtNode:ch,createPortal:rn,createElement:b,createContext:wr,createFactory:oh,cloneElement:Rr,createRef:_m,Fragment:z,isValidElement:In,isElement:uh,isFragment:ah,isMemo:sh,findDOMNode:lh,Component:Ot,PureComponent:Xa,memo:qm,forwardRef:J,flushSync:Qa,unstable_batchedUpdates:dh,StrictMode:z,Suspense:_o,SuspenseList:fi,lazy:Jm,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ih},CI=Object.defineProperty,mi=(e,t)=>CI(e,"name",{value:t,configurable:!0}),ph=!!(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 II(e){if(!ph)throw new Error("Cannot access window outside of the DOM");return e?.ownerDocument?.defaultView??window}mi(II,"getOwnerWindow");function Fl(e){if(!ph)throw new Error("Cannot access document outside of the DOM");return e?.ownerDocument??document}mi(Fl,"getOwnerDocument");function fh(e,t=!1){const{activeElement:n}=Fl(e);if(!n?.nodeName)return null;if(mh(n)&&n.contentDocument)return fh(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(fh,"getActiveElement");function mh(e){return e.tagName==="IFRAME"}mi(mh,"isFrame");var RI=Object.defineProperty,Bl=(e,t)=>RI(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 hh(...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(hh,"composeRefs");function Se(...e){return se(hh(...e),e)}Bl(Se,"useComposedRefs");var PI=Object.defineProperty,Mt=(e,t)=>PI(e,"name",{value:t,configurable:!0});function kI(e,t){const n=wr(t);n.displayName=e+"Context";const r=Mt(o=>{const{children:s,...c}=o,l=Pe(()=>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 Mt(i,"useContext"),[r,i]}Mt(kI,"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=Mt(p=>{const{scope:f,children:m,...v}=p,g=f?.[e]?.[l]||c,h=Pe(()=>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 Mt(u,"useContext"),[d,u]}Mt(r,"createContext");const i=Mt(()=>{const o=n.map(s=>wr(s));return Mt(function(c){const l=c?.[e]||o;return Pe(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])},"useScope")},"createScope");return i.scopeName=e,[r,gh(i,...t)]}Mt(lt,"createContextScope");function gh(...e){const t=e[0];if(e.length===1)return t;const n=Mt(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Mt(function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return Pe(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Mt(gh,"composeContextScopes");var Xe=globalThis?.document?It:()=>{},TI=Object.defineProperty,NI=(e,t)=>TI(e,"name",{value:t,configurable:!0}),EI=pi[" useId ".trim().toString()]||(()=>{}),AI=0;function Et(e){const[t,n]=x(EI());return Xe(()=>{e||n(r=>r??String(AI++))},[e]),e||(t?`radix-${t}`:"")}NI(Et,"useId");var xI=Object.defineProperty,DI=(e,t)=>xI(e,"name",{value:t,configurable:!0}),vh=pi[" useEffectEvent ".trim().toString()],yh=pi[" useInsertionEffect ".trim().toString()];function bh(e){if(typeof vh=="function")return vh(e);const t=q(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof yh=="function"?yh(()=>{t.current=e}):Xe(()=>{t.current=e}),Pe(()=>((...n)=>t.current?.(...n)),[])}DI(bh,"useEffectEvent");var $I=Object.defineProperty,wo=(e,t)=>$I(e,"name",{value:t,configurable:!0}),LI=pi[" useInsertionEffect ".trim().toString()]||Xe;function At({prop:e,defaultProp:t,onChange:n=wo(()=>{},"onChange"),caller:r}){const[i,o,s]=_h({defaultProp:t,onChange:n}),c=e!==void 0;return[c?e:i,se(d=>{if(c){const u=wh(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}wo(At,"useControllableState");function _h({defaultProp:e,onChange:t}){const[n,r]=x(e),i=q(n),o=q(t);return LI(()=>{o.current=t},[t]),K(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}wo(_h,"useUncontrolledState");function wh(e){return typeof e=="function"}wo(wh,"isFunction");var Sh=Symbol("RADIX:SYNC_STATE");function jI(e,t,n,r){const{prop:i,defaultProp:o,onChange:s,caller:c}=t,l=i!==void 0,d=bh(s),u=[{...n,state:o}];r&&u.push(r);const[p,f]=Wn((h,y)=>{if(y.type===Sh)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=Pe(()=>i!==void 0?{...p,state:i}:p,[p,i]);return K(()=>{l&&!Object.is(i,p.state)&&f({type:Sh,state:i})},[i,p.state,l]),[g,f]}wo(jI,"useControllableStateReducer");var OI=Object.defineProperty,Kt=(e,t)=>OI(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(kh(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=MI(m,v),l.push(s?.props?.children)}else l.push(f)}),s?s=Rr(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?UI(e):BI(e));return i}const p=Rh(o,s.props??{});return s.type!==z&&(p.ref=r?u:d),Rr(s,p)});return t.displayName=`${e}.Slot`,t}Kt(on,"createSlot");var Ch=Symbol.for("radix.slottable");function Ih(e){const t=Kt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=Ch,t}Kt(Ih,"createSlottable");var MI=Kt((e,t)=>{if("child"in e.props){const n=e.props.child;return In(n)?Rr(n,void 0,e.props.children(n.props.children)):null}return In(t)?t:null},"getSlottableElementFromSlottable");function Rh(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(Rh,"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 kh(e){return In(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ch}Kt(kh,"isSlottable");var FI=Symbol.for("react.lazy");function ql(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===FI&&"_payload"in e&&Th(e._payload)}Kt(ql,"isLazyComponent");function Th(e){return typeof e=="object"&&e!==null&&"then"in e}Kt(Th,"isPromiseLike");var BI=Kt(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),UI=Kt(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Za=pi[" use ".trim().toString()],qI=Object.defineProperty,GI=(e,t)=>qI(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))}GI(es,"dispatchDiscreteCustomEvent");var HI=Object.defineProperty,KI=(e,t)=>HI(e,"name",{value:t,configurable:!0});function mt(e){const t=q(e);return K(()=>{t.current=e}),Pe(()=>((...n)=>t.current?.(...n)),[])}KI(mt,"useCallbackRef");var VI=Object.defineProperty,tt=(e,t)=>VI(e,"name",{value:t,configurable:!0}),Gl="dismissableLayer.update",zI="dismissableLayer.pointerDownOutside",WI="dismissableLayer.focusOutside",Nh,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,R=p.layersWithOutsidePointerEventsDisabled.size>0,k=I>=_,A=q(!1),L=Ah(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=xh(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&&(Nh=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=Nh))}},[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:R?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")),JI=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 Eh(){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(Eh,"useDismissableLayerSurface");var YI=tt(()=>!0,"IS_TRUE");function Ah(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:s=YI}=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(R=>R.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(zI,c,R,{discrete:!0})};if(tt(I,"handleAndDispatchPointerDownOutsideEvent"),!s(_.target)){n.removeEventListener("click",p.current),f(),l.current=!1;return}const R={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(Ah,"usePointerDownOutside");function xh(e,t=globalThis?.document){const n=mt(e),r=q(!1);return K(()=>{const i=tt(o=>{o.target&&!r.current&&Vl(WI,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(xh,"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 XI=hi,QI=JI,ZI=Object.defineProperty,wt=(e,t)=>ZI(e,"name",{value:t,configurable:!0}),zl="focusScope.autoFocusOnMount",Wl="focusScope.autoFocusOnUnmount",Dh={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 R=I.target;l.contains(R)?f.current=R:Rn(f.current,{select:!0})},y=function(I){if(v.paused||!l)return;const R=I.relatedTarget;R!==null&&(l.contains(R)||Rn(f.current,{select:!0}))},w=function(I){if(document.activeElement===document.body)for(const R of I)R.removedNodes.length>0&&Rn(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){Mh.add(v);const h=document.activeElement;if(!l.contains(h)){const y=new CustomEvent(zl,Dh);l.addEventListener(zl,u),l.dispatchEvent(y),y.defaultPrevented||($h(Bh(Jl(l)),{select:!0}),document.activeElement===h&&Rn(l))}return()=>{l.removeEventListener(zl,u),setTimeout(()=>{const y=new CustomEvent(Wl,Dh);l.addEventListener(Wl,p),l.dispatchEvent(y),y.defaultPrevented||Rn(h??document.body,{select:!0}),l.removeEventListener(Wl,p),Mh.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,R]=Lh(_);I&&R?!h.shiftKey&&w===R?(h.preventDefault(),r&&Rn(I,{select:!0})):h.shiftKey&&w===I&&(h.preventDefault(),r&&Rn(R,{select:!0})):w===_&&h.preventDefault()}},[r,i,v.paused]);return a(ve.div,{tabIndex:-1,...c,ref:m,onKeyDown:g})},"FocusScope"));function $h(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Rn(r,{select:t}),document.activeElement!==n)return}wt($h,"focusFirst");function Lh(e){const t=Jl(e);return[Yl(t,e),Yl(t.reverse(),e)]}wt(Lh,"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}):jh(r,{upTo:t})))return r}wt(Yl,"findVisible");function jh(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(jh,"isHidden");function Oh(e){return e instanceof HTMLInputElement&&"select"in e}wt(Oh,"isSelectableInput");function Rn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Oh(e)&&t&&e.select()}}wt(Rn,"focus");var Mh=Fh();function Fh(){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(Fh,"createFocusScopesStack");function Xl(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}wt(Xl,"arrayRemove");function Bh(e){return e.filter(t=>t.tagName!=="A")}wt(Bh,"removeLinks");var eR=Object.defineProperty,tR=(e,t)=>eR(e,"name",{value:t,configurable:!0}),gi=J(tR(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")),nR=Object.defineProperty,Pn=(e,t)=>nR(e,"name",{value:t,configurable:!0});function Uh(e,t){return Wn((n,r)=>t[n][r]??n,e)}Pn(Uh,"useStateMachine");var Rt=Pn(e=>{const{present:t,children:n}=e,r=qh(t),i=typeof n=="function"?n({present:r.isPresent}):Ir.only(n),o=Gh(r.ref,Hh(i));return typeof n=="function"||r.isPresent?Rr(i,{ref:o}):null},"Presence");function qh(e){const[t,n]=x(),r=q(null),i=q(e),o=q("none"),s=q(void 0),[c,l]=Uh(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=Pn(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=Pn(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)},[])}}Pn(qh,"usePresence");function Ql(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Pn(Ql,"setRef");function Gh(...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)}}},[])}Pn(Gh,"useStableComposedRefs");function vi(e){return e?.animationName||"none"}Pn(vi,"getAnimationName");function Hh(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)}Pn(Hh,"getElementRef");var rR=Object.defineProperty,Zl=(e,t)=>rR(e,"name",{value:t,configurable:!0}),ns=0,yi=null;function iR(e){return bi(),e.children}Zl(iR,"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 Kh(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 oR(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",aR="with-scroll-bars-hidden",sR="--removed-body-scroll-bar-size";function td(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function cR(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 lR=typeof window<"u"?It:K,Vh=new WeakMap;function dR(e,t){var n=cR(t||null,function(r){return e.forEach(function(i){return td(i,r)})});return lR(function(){var r=Vh.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)})}Vh.set(n,e)},[e]),n}function uR(e){return e}function pR(e,t){t===void 0&&(t=uR);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 fR(e){e===void 0&&(e={});var t=pR(null);return t.options=an({async:!0,ssr:!1},e),t}var zh=function(e){var t=e.sideCar,n=Kh(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))};zh.isSideCarExport=!0;function mR(e,t){return e.useMedium(t),zh}var Wh=fR(),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=Kh(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),R=f,k=dR([n,t]),A=an(an({},I),i);return b(z,null,u&&b(R,{sideCar:Wh,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:g,setCallbacks:o,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?Rr(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 Jh,hR=function(){if(Jh)return Jh;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function gR(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=hR();return t&&e.setAttribute("nonce",t),e}function vR(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function yR(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var bR=function(){var e=0,t=null;return{add:function(n){e==0&&(t=gR())&&(vR(t,n),yR(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},_R=function(){var e=bR();return function(t,n){K(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Yh=function(){var e=_R(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},wR={left:0,top:0,right:0,gap:0},rd=function(e){return parseInt(e||"",10)||0},SR=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)]},CR=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return wR;var t=SR(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])}},IR=Yh(),So="data-scroll-locked",RR=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(
|
|
1
|
+
(function(){var dm=Object.defineProperty,vC=(e,t)=>{let n={};for(var r in e)dm(n,r,{get:e[r],enumerable:!0});return t||dm(n,Symbol.toStringTag,{value:"Module"}),n};function Se(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function je(e,t){const n=t?await fetch(e,t):await fetch(e);if(!n.ok)throw new Error(`${e}: ${n.status} ${n.statusText}`);return n.json()}async function Ce(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function um(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 yC(){return je("/api/observer-status")}async function bC(){return je("/api/config")}async function _C(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=Se(r)||n||"request failed";throw new Error(i)}return r}async function Rl(){return je("/api/coordinator/admin/status")}async function pm(e){return je(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function wC(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function SC(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function CC(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function RC(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function IC(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function kC(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function fm(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return je(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function TC(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 Ce(r);if(!r.ok)throw new Error(Se(o)||i||"request failed");return o}async function PC(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 Ce(i);if(!i.ok)throw new Error(Se(s)||o||"request failed");return s}async function NC(e){const t=new URLSearchParams;e&&t.set("group_id",e);const n=t.size?`?${t.toString()}`:"";return je(`/api/coordinator/admin/join-requests${n}`)}async function mm(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 je(`/api/coordinator/admin/devices${r}`)}async function EC(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function AC(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 Ce(r);if(!r.ok)throw new Error(Se(o)||i||"request failed");return o}async function xC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function DC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function LC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function hm(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function gm(e,t){const n=um(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/observations?${n}`)}async function $C(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function OC(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function jC(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function vm(e,t){const n=um(e,t?.limit,t?.offset,t?.scope,t?.q);return je(`/api/summaries?${n}`)}async function MC(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function FC(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 BC(){return je("/api/runtime")}async function Va(){return(await je("/api/projects")).projects||[]}function qC(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return!["available","no_data","unavailable"].includes(t.availability)||t.captureVersion!=="opencode-retained-v1"||t.windowLimit!==1e3||typeof t.periodStart!="string"||!Number.isFinite(Date.parse(t.periodStart))||typeof t.periodEnd!="string"||!Number.isFinite(Date.parse(t.periodEnd))||Date.parse(t.periodStart)>Date.parse(t.periodEnd)||![t.freshEvaluations,t.evaluationsWithDuplicates,t.candidateItems,t.duplicatesOmitted,t.beforeTokens,t.afterTokens,t.estimatedTokensAvoided,t.missingRetainedMetadata,t.invalidRetainedMetadata,t.packMetadataGaps,t.unmeasuredAttempts].every(n=>Number.isSafeInteger(n)&&n>=0&&n<=1e9)||t.freshEvaluations+t.unmeasuredAttempts>1e3||[t.evaluationsWithDuplicates,t.missingRetainedMetadata,t.invalidRetainedMetadata,t.packMetadataGaps].some(n=>n>t.freshEvaluations)||t.candidateItems>t.freshEvaluations*50||t.duplicatesOmitted>t.candidateItems||t.afterTokens>t.beforeTokens||t.estimatedTokensAvoided!==t.beforeTokens-t.afterTokens||t.availability==="available"!=t.freshEvaluations>0?null:t}async function UC(){return je("/api/stats")}async function GC(e){return je(`/api/usage?project=${encodeURIComponent(e)}`)}async function HC(e){return je(`/api/session?project=${encodeURIComponent(e)}`)}async function VC(e){return je(`/api/raw-events?project=${encodeURIComponent(e)}`)}var Ka=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="RecipientPolicyTeamRenameApiError"}},KC=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 zC(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 Ka(0,"team_rename_failed")}const{payload:n}=await Ce(t);if(!t.ok){const r=n&&typeof n=="object"&&"error"in n?String(n.error):"";throw new Ka(t.status,KC.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 Ka(t.status,"team_rename_failed");return n}var WC=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"]),ym=class extends Error{errorCode;constructor(e,t){super(e),this.errorCode=t,this.name="ProjectInviteAcceptanceError"}};async function Il(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 je(`/api/sync/status${i}`)}async function kl(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 Ce(r);if(!r.ok){const s=typeof o?.detail=="string"?o.detail.trim():"",c=Se(o),l=s||c||i||"request failed";throw n==="project_share_invite"&&c&&WC.has(c)?new ym(l,c):new Error(l)}return o}async function bm(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function JC(){return je("/api/sync/actors")}async function YC(e=!1){return je(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function _m(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function wm(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function XC(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||Se(o)||i||"request failed");return o}var Sm=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},za=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??[]}},Cm=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},Tl=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},Pl=1,Rm=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"]),QC=new Set(["coordinator_route_missing","coordinator_rejected_manifest","coordinator_unreachable","local_candidate_scan_budget_exceeded","coordinator_roster_unavailable"]),ZC=new Set(["needs_setup","in_progress","stale","ready"]),eR=new Set(["reviewing","ready_to_finish","unavailable","completed"]),tR=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 nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Kn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function zt(e){return typeof e=="string"||e===null}function wr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function on(e,t){return Array.isArray(e)&&e.every(t)}function Im(e){return nt(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&ZC.has(e.status)&&wr(e.deviceCount)&&wr(e.projectCount)&&wr(e.unresolvedDeviceCount)&&wr(e.unresolvedProjectCount):!1}function nR(e){return nt(e)&&e.version===Pl&&on(e.candidates,t=>Im(t)&&t.status!=="ready")}function rR(e){return nt(e)?e.kind==="absent"||e.kind==="existing"&&wr(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function zn(e){return!nt(e)||!Kn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&tR.has(e.blockedReason)}function iR(e){return!nt(e)||!Kn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:zn(e.assignIdentity)&&zn(e.include)&&zn(e.exclude)&&zn(e.remove)&&zn(e.clearDecision)}function oR(e){return nt(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&zt(e.existingIdentityRef)&&zt(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&zt(e.targetIdentityRef)&&rR(e.expectation)&&iR(e.actions):!1}function aR(e){return nt(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&zt(e.canonicalProjectRef)&&zt(e.resolvedProjectRef)&&on(e.mappingChoices,t=>nt(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&nt(e.actions)&&Kn(e.actions,["map"])&&zn(e.actions.map):!1}function sR(e){if(!nt(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return on(e.teamChanges,n=>nt(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")&&on(e.membershipChanges,n=>nt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&on(e.projectChanges,n=>nt(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&zt(n.fromCanonicalProjectRef)&&zt(n.fromResolvedProjectRef)&&zt(n.fromResolvedProjectDisplayName)&&zt(n.toCanonicalProjectRef)&&zt(n.toResolvedProjectRef)&&zt(n.toResolvedProjectDisplayName)&&t(n.change))&&on(e.recipientChanges,n=>nt(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))&&on(e.deviceAccessChanges,n=>nt(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 cR(e){return nt(e)&&Kn(e,["finish","refresh"])&&zn(e.refresh)&&zn(e.finish)}function km(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 fi(e){if(!nt(e)||!(e.version===Pl&&Im(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&eR.has(e.state)&&wr(e.unresolvedDeviceCount)&&wr(e.unresolvedProjectCount)&&on(e.devices,oR)&&on(e.projects,aR)&&cR(e.actions)&&on(e.identityChoices,o=>nt(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"?Kn(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"&&sR(e.accessDelta):e.state==="unavailable"?Kn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&Rm.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&km(n,r,"setup_unavailable"):e.state==="completed"?Kn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&km(n,r,"setup_completed"):Kn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function lR(e){return nt(e)&&e.version===Pl&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var wt=class extends Error{statusCode;errorCode;reason;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.reason=n,this.name="LegacyTeamSetupApiError"}};function Wn(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function Jn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new wt(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 wt(r.status,"team_setup_failed")}if(!r.ok){const o=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=Rm.has(o)?o:"team_setup_failed",c=i&&typeof i=="object"&&"reason"in i&&typeof i.reason=="string"?i.reason:"",l=QC.has(c)?c:void 0;throw new wt(r.status,s,l)}if(!t(i))throw new wt(r.status,"team_setup_failed");return i}function mi(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function Tm(){return Jn(Wn(),nR)}function dR(e){return Jn(Wn(e),fi)}function uR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/assignment`,fi,mi("PUT",n))}function pR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/decision`,fi,mi("PUT",n))}function fR(e,t,n){return Jn(`${Wn(e)}/devices/${encodeURIComponent(t)}/decision`,fi,mi("DELETE",n))}function mR(e,t,n){return Jn(`${Wn(e)}/projects/${encodeURIComponent(t)}/mapping`,fi,mi("PUT",n))}function hR(e){return Jn(`${Wn(e)}/refresh`,fi,mi("POST",{}))}function gR(e,t){return Jn(`${Wn(e)}/finish`,lR,mi("POST",t))}var Nl=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function El(){return je("/api/sync/recipient-policy/v1/intent")}function Al(){return je("/api/sync/recipient-policy/v1/device-inventory")}async function Pm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok){const o=i?.errorCode||i?.error||Se(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new Tl(n.status,o,s)}return i}function Nm(e){return Pm("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function Em(e){return Pm("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function vR(){return je("/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 Ce(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Nl(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||Se(i)||r||"request failed")}return i}function yR(e){return Am("/api/sync/recipient-policy/v1/edges/preview",e)}function bR(e){return Am("/api/sync/recipient-policy/v1/edges/commit",e)}async function xm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}function _R(e){return xm("/api/sync/recipient-policy/v1/invites/preview",e)}function wR(e){return xm("/api/sync/recipient-policy/v1/invites",e)}async function SR(){const e=await je("/api/sync/recipient-policy/v1/review"),t=e.continuity??null;if(e.categoryCounts)return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:Math.max(0,e.categoryCounts.preservedContinuity),blockedRepair:e.blockedItems.length}};const n=Math.max(0,(t?.findingCount??0)-e.reviewItems.length);return{...e,continuity:t,categoryCounts:{actionableReview:e.reviewItems.length,preservedContinuity:n,blockedRepair:e.blockedItems.length}}}async function CR(){return je("/api/sync/sharing-domains/settings")}async function bo(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 je(`/api/sync/projects${n?`?${n}`:""}`)}async function Dm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}function RR(e){return Dm("/api/sync/project-invites/preview",e)}function IR(e){return Dm("/api/sync/project-invites",e)}function Lm(){return je("/api/sync/share-operations")}function kR(e){return je(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function TR(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function PR(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 Ce(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new za(r):new Error(Se(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 NR(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 Ce(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new za(r):new Error(Se(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function ER(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return!!r?.deleted}async function AR(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function xR(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 Ce(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new Sm(r.preview):new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function DR(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 Ce(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new Cm(r.preview):new Error(Se(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function LR(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function $R(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");const o=i?.preferences;if(!o)throw new Error("response missing preferences");return o}async function OR(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function jR(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function $m(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 Ce(n);if(!n.ok)throw new Error(Se(i)||r||"request failed");return i}async function MR(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function FR(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 Ce(t);if(!t.ok)throw new Error(Se(r)||n||"request failed");return r}async function xl(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 Ce(i);if(!i.ok)throw new Error(Se(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 BR(){return je("/api/update-status")}function qR(e){return{current_version:"unknown",channel:null,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 Wa(e){return e!==null&&typeof e=="object"?e:null}function Om(e){const t=Wa(e),n=Wa(t?.status),r=Wa(Wa(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var _o,ge,jm,Mm,Yn,Fm,Bm,qm,Dl,Ja,wo,Um,Ll,$l,Ol,Gm,Ya={},Xa=[],UR=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,So=Array.isArray;function an(e,t){for(var n in t)e[n]=t[n];return e}function jl(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function y(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?_o.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 Co(e,s,r,i,null)}function Co(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??++jm,__i:-1,__u:0};return i==null&&ge.vnode!=null&&ge.vnode(o),o}function Hm(){return{current:null}}function z(e){return e.children}function Mt(e,t){this.props=e,this.context=t}function Sr(e,t){if(t==null)return e.__?Sr(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"?Sr(e):null}function GR(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],o=an({},t);o.__v=t.__v+1,ge.vnode&&ge.vnode(o),Fl(e.__P,o,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Sr(t),!!(32&t.__u),i),o.__v=t.__v,o.__.__k[o.__i]=o,Xm(r,o,i),t.__e=t.__=null,o.__e!=n&&Vm(o)}}function Vm(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}),Vm(e)}function Ml(e){(!e.__d&&(e.__d=!0)&&Yn.push(e)&&!Qa.__r++||Fm!=ge.debounceRendering)&&((Fm=ge.debounceRendering)||Bm)(Qa)}function Qa(){try{for(var e,t=1;Yn.length;)Yn.length>t&&Yn.sort(qm),e=Yn.shift(),t=Yn.length,GR(e)}finally{Yn.length=Qa.__r=0}}function Km(e,t,n,r,i,o,s,c,l,d,u){var p,f,m,v,g,h,b=r&&r.__k||Xa,w=t.length;for(l=HR(n,t,b,l,w),p=0;p<w;p++)(m=n.__k[p])!=null&&(f=m.__i!=-1&&b[m.__i]||Ya,m.__i=p,h=Fl(e,m,f,i,o,s,c,l,d,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Bl(f.ref,null,m),u.push(m.ref,m.__c||v,m)),g==null&&v!=null&&(g=v),4&m.__u?(l=zm(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 HR(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]=Co(null,s,null,null,null):So(s)?s=e.__k[o]=Co(z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[o]=Co(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=VR(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=Sr(c)),Zm(c,c));return r}function zm(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=zm(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=Sr(e)),t=n.insertBefore(e.__e,t||null));do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function Cn(e,t){return t=t||[],e==null||typeof e=="boolean"||(So(e)?e.some(function(n){Cn(n,t)}):t.push(e)),t}function VR(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 Wm(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||UR.test(t)?n:n+"px"}function Za(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||Wm(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Wm(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")o=t!=(t=t.replace(Um,"$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[wo]=r[wo]:(n[wo]=Ll,e.addEventListener(t,o?Ol:$l,o)):e.removeEventListener(t,o?Ol:$l,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 Jm(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Ja]==null)t[Ja]=Ll++;else if(t[Ja]<n[wo])return;return n(ge.event?ge.event(t):t)}}}function Fl(e,t,n,r,i,o,s,c,l,d){var u,p,f,m,v,g,h,b,w,_,R,I,T,A,O,F,N=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),o=[c=t.__e=n.__e]),(u=ge.__b)&&u(t);e:if(typeof N=="function"){p=s.length;try{if(w=t.props,_=N.prototype&&N.prototype.render,R=(u=N.contextType)&&r[u.__c],I=u?R?R.props.value:u.__:r,n.__c?b=(f=t.__c=n.__c).__=f.__E:(_?t.__c=f=new N(w,I):(t.__c=f=new Mt(w,I),f.constructor=N,f.render=zR),R&&R.sub(f),f.state||(f.state={}),f.__n=r,m=f.__d=!0,f.__h=[],f._sb=[]),_&&f.__s==null&&(f.__s=f.state),_&&N.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=an({},f.__s)),an(f.__s,N.getDerivedStateFromProps(w,f.__s))),v=f.props,g=f.state,f.__v=t,m)_&&N.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),_&&f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(_&&N.getDerivedStateFromProps==null&&w!==v&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(w,I),t.__v==n.__v||!f.__e&&f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(w,f.__s,I)===!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(L){L&&(L.__=t)}),Xa.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&s.push(f),c=Sr(n);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(w,f.__s,I),_&&f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(v,g,h)})}if(f.context=I,f.props=w,f.__P=e,f.__e=!1,T=ge.__r,A=0,_)f.state=f.__s,f.__d=!1,T&&T(t),u=f.render(f.props,f.state,f.context),Xa.push.apply(f.__h,f._sb),f._sb=[];else do f.__d=!1,T&&T(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=an(an({},r),f.getChildContext())),_&&!m&&f.getSnapshotBeforeUpdate!=null&&(h=f.getSnapshotBeforeUpdate(v,g)),O=u!=null&&u.type===z&&u.key==null?Qm(u.props.children):u,c=Km(e,So(O)?O:[O],t,n,r,i,o,s,c,l,d),f.base=t.__e,t.__u&=-161,f.__h.length&&s.push(f),b&&(f.__E=f.__=null)}catch(L){if(s.length=p,t.__v=null,l||o!=null){if(L.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--;)jl(o[F])}else t.__e=n.__e;t.__k??=n.__k||[],L.then||Ym(t),ge.__e(L,t,n)}}else o==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=KR(n.__e,t,n,r,i,o,s,l,d);return(u=ge.diffed)&&u(t),128&t.__u?void 0:c}function Ym(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ym))}function Xm(e,t,n){for(var r=0;r<n.length;r++)Bl(n[r],n[++r],n[++r]);ge.__c&&ge.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(o){o.call(i)})}catch(o){ge.__e(o,i.__v)}})}function Qm(e){return typeof e!="object"||e==null||e.__b>0?e:So(e)?e.map(Qm):e.constructor!==void 0?null:an({},e)}function KR(e,t,n,r,i,o,s,c,l){var d,u,p,f,m,v,g,h=n.props||Ya,b=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(b);e=document.createElementNS(i,w,b.is&&b),c&&(ge.__m&&ge.__m(t,o),c=!1),o=null}if(w==null)h===b||c&&e.data==b||(e.data=b);else{if(o=w=="textarea"&&b.defaultValue!=null?null:o&&_o.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 b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||Za(e,d,null,m,i);for(d in b)m=b[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?u=m:d=="value"?v=m:d=="checked"?g=m:c&&typeof m!="function"||h[d]===m||Za(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=""),Km(t.type=="template"?e.content:e,So(f)?f:[f],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,o,s,o?o[0]:n.__k&&Sr(n,0),c,l),o!=null)for(d=o.length;d--;)jl(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])&&Za(e,d,v,h[d],i),d="checked",g!=null&&g!=e[d]&&Za(e,d,g,h[d],i))}return e}function Bl(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){ge.__e(i,n)}}function Zm(e,t,n){var r,i;if(ge.unmount&&ge.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Bl(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(o){ge.__e(o,t)}r.base=r.__P=r.__n=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Zm(r[i],t,n||typeof e.type!="function");n||jl(e.__e),e.__c=e.__=e.__e=void 0}function zR(e,t,n){return this.constructor(e,n)}function Ue(e,t,n){var r,i,o,s;t==document&&(t=document.documentElement),ge.__&&ge.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,o=[],s=[],Fl(t,e=(!r&&n||t).__k=y(z,null,[e]),i||Ya,Ya,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?_o.call(t.childNodes):null,o,!r&&n?n:i?i.__e:t.firstChild,r,s),Xm(o,e,s),e.props.children=null}function eh(e,t){Ue(e,t,eh)}function WR(e,t,n){var r,i,o,s,c=an({},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?_o.call(arguments,2):n),Co(e.type,c,r||e.key,i||e.ref,null)}function Cr(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,Ml(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"+Gm++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}_o=Xa.slice,ge={__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}},jm=0,Mm=function(e){return e!=null&&e.constructor===void 0},Mt.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=an({},this.state);typeof e=="function"&&(e=e(an({},n),this.props)),e&&an(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ml(this))},Mt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ml(this))},Mt.prototype.render=z,Yn=[],Bm=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,qm=function(e,t){return e.__v.__b-t.__v.__b},Qa.__r=0,Dl=Math.random().toString(8),Ja="__d"+Dl,wo="__a"+Dl,Um=/(PointerCapture)$|Capture$/i,Ll=0,$l=Jm(!1),Ol=Jm(!0),Gm=0;var Rn,Be,ql,th,hi=0,nh=[],Je=ge,rh=Je.__b,ih=Je.__r,oh=Je.diffed,ah=Je.__c,sh=Je.unmount,ch=Je.__;function Rr(e,t){Je.__h&&Je.__h(Be,e,hi||t),hi=0;var n=Be.__H||(Be.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function x(e){return hi=1,In(dh,e)}function In(e,t,n){var r=Rr(Rn++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):dh(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 V(e,t){var n=Rr(Rn++,3);!Je.__s&&Hl(n.__H,t)&&(n.__=e,n.u=t,Be.__H.__h.push(n))}function It(e,t){var n=Rr(Rn++,4);!Je.__s&&Hl(n.__H,t)&&(n.__=e,n.u=t,Be.__h.push(n))}function B(e){return hi=5,ke(function(){return{current:e}},[])}function es(e,t,n){hi=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 ke(e,t){var n=Rr(Rn++,7);return Hl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ae(e,t){return hi=8,ke(function(){return e},t)}function kn(e){var t=Be.context[e.__c],n=Rr(Rn++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(Be)),t.props.value):e.__}function Ul(e,t){Je.useDebugValue&&Je.useDebugValue(t?t(e):e)}function JR(e){var t=Rr(Rn++,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 Ir(){var e=Rr(Rn++,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 YR(){for(var e;e=nh.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(ts),t.__h.some(Gl),t.__h=[]}catch(n){t.__h=[],Je.__e(n,e.__v)}}}Je.__b=function(e){Be=null,rh&&rh(e)},Je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ch&&ch(e,t)},Je.__r=function(e){ih&&ih(e),Rn=0;var t=(Be=e.__c).__H;t&&(ql===Be?(t.__h=[],Be.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(ts),t.__h.some(Gl),t.__h=[],Rn=0)),ql=Be},Je.diffed=function(e){oh&&oh(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(nh.push(t)!==1&&th===Je.requestAnimationFrame||((th=Je.requestAnimationFrame)||XR)(YR)),t.__H.__.some(function(n){n.u&&(n.__H=n.u,n.u=void 0)})),ql=Be=null},Je.__c=function(e,t){t.some(function(n){try{n.__h.some(ts),n.__h=n.__h.filter(function(r){return!r.__||Gl(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Je.__e(r,n.__v)}}),ah&&ah(e,t)},Je.unmount=function(e){sh&&sh(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{ts(r)}catch(i){t=i}}),n.__H=void 0,t&&Je.__e(t,n.__v))};var lh=typeof requestAnimationFrame=="function";function XR(e){var t,n=function(){clearTimeout(r),lh&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);lh&&(t=requestAnimationFrame(n))}function ts(e){var t=Be,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Be=t}function Gl(e){var t=Be;e.__c=e.__(),Be=t}function Hl(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function dh(e,t){return typeof t=="function"?t(e):t}var QR=0,M2=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:--QR,__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 ge.vnode&&ge.vnode(d),d}function kr({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 gi=vC({Children:()=>Tr,Component:()=>Mt,Fragment:()=>z,PureComponent:()=>ns,StrictMode:()=>z,Suspense:()=>Ro,SuspenseList:()=>vi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Ph,cloneElement:()=>Pr,createContext:()=>Cr,createElement:()=>y,createFactory:()=>Nh,createPortal:()=>sn,createRef:()=>Hm,default:()=>dI,findDOMNode:()=>Dh,flushSync:()=>rs,forwardRef:()=>J,hydrate:()=>Ch,isElement:()=>$h,isFragment:()=>Eh,isMemo:()=>Ah,isValidElement:()=>Tn,lazy:()=>bh,memo:()=>ph,render:()=>Sh,startTransition:()=>Wl,unmountComponentAtNode:()=>xh,unstable_batchedUpdates:()=>Lh,useCallback:()=>ae,useContext:()=>kn,useDebugValue:()=>Ul,useDeferredValue:()=>Jl,useEffect:()=>V,useErrorBoundary:()=>JR,useId:()=>Ir,useImperativeHandle:()=>es,useInsertionEffect:()=>Xl,useLayoutEffect:()=>It,useMemo:()=>ke,useReducer:()=>In,useRef:()=>B,useState:()=>x,useSyncExternalStore:()=>Kl,useTransition:()=>Yl,version:()=>lI});function uh(e,t){for(var n in t)e[n]=t[n];return e}function Vl(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 Kl(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,zl(i)&&o({t:i})},[e,n,t]),V(function(){return zl(i)&&o({t:i}),e(function(){zl(i)&&o({t:i})})},[e]),n}function zl(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 Wl(e){e()}function Jl(e){return e}function Yl(){return[!1,Wl]}var Xl=It;function ns(e,t){this.props=e,this.context=t}function ph(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:Vl(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}(ns.prototype=new Mt).isPureReactComponent=!0,ns.prototype.shouldComponentUpdate=function(e,t){return Vl(this.props,e)||Vl(this.state,t)};var fh=ge.__b;ge.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),fh&&fh(e)};var ZR=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=uh({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=ZR,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var mh=function(e,t){return e==null?null:Cn(Cn(e).map(t))},Tr={map:mh,forEach:mh,count:function(e){return e?Cn(e).length:0},only:function(e){var t=Cn(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:Cn},eI=ge.__e;ge.__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)}eI(e,t,n,r)};var hh=ge.unmount;function gh(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=uh({},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 gh(r,t,n)})),e}function vh(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return vh(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 Ro(){this.__u=0,this.o=null,this.__b=null}function yh(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function bh(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?y(i,s):null}return o.displayName="Lazy",o.__f=!0,o}function vi(){this.i=null,this.l=null}ge.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),hh&&hh(e)},(Ro.prototype=new Mt).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=yh(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]=vh(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)},Ro.prototype.componentWillUnmount=function(){this.o=[]},Ro.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]=gh(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 _h=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 tI(e){return this.getChildContext=function(){return e.context},e.children}function nI(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ue(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)}}}Ue(y(tI,{context:t.context},e.__v),t.v)}function sn(e,t){var n=y(nI,{__v:e,h:t});return n.containerInfo=t,n}(vi.prototype=new Mt).__a=function(e){var t=this,n=yh(t.__v),r=t.l.get(e);return r[0]++,function(i){var o=function(){t.props.revealOrder?(r.push(i),_h(t,e,r)):i()};n?n(o):o()}},vi.prototype.render=function(e){this.i=null,this.l=new Map;var t=Cn(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},vi.prototype.componentDidUpdate=vi.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){_h(e,n,t)})};var wh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,rI=/^(?: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]/,iI=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,oI=/[A-Z0-9]/g,aI=typeof document<"u",sI=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Sh(e,t,n){return t.__k??(t.textContent=""),Ue(e,t),typeof n=="function"&&n(),e?e.__c:null}function Ch(e,t,n){return eh(e,t),typeof n=="function"&&n(),e?e.__c:null}Mt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Mt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Rh=ge.event;ge.event=function(e){return Rh&&(e=Rh(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Ql,cI={configurable:!0,get:function(){return this.class}},Ih=ge.vnode;ge.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||aI&&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"||sI(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":iI.test(s)&&(s=l):l=s="oninput":o&&rI.test(s)?s=s.replace(oI,"-$&").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=Cn(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=Cn(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",cI)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=wh,Ih&&Ih(e)};var kh=ge.__r;ge.__r=function(e){kh&&kh(e),Ql=e.__c};var Th=ge.diffed;ge.diffed=function(e){Th&&Th(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),Ql=null};var Ph={ReactCurrentDispatcher:{current:{readContext:function(e){return Ql.__n[e.__c].props.value},useCallback:ae,useContext:kn,useDebugValue:Ul,useDeferredValue:Jl,useEffect:V,useId:Ir,useImperativeHandle:es,useInsertionEffect:Xl,useLayoutEffect:It,useMemo:ke,useReducer:In,useRef:B,useState:x,useSyncExternalStore:Kl,useTransition:Yl}}},lI="18.3.1";function Nh(e){return y.bind(null,e)}function Tn(e){return!!e&&e.$$typeof===wh}function Eh(e){return Tn(e)&&e.type===z}function Ah(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Pr(e){return Tn(e)?WR.apply(null,arguments):e}function xh(e){return!!e.__k&&(Ue(null,e),!0)}function Dh(e){return e&&(e.base||e.nodeType===1&&e)||null}var Lh=function(e,t){return e(t)},rs=function(e,t){var n,r=ge.debounceRendering;ge.debounceRendering=function(o){n=o};try{var i=e(t);return n&&n(),i}finally{ge.debounceRendering=r}},$h=Tn,dI={useState:x,useId:Ir,useReducer:In,useEffect:V,useLayoutEffect:It,useInsertionEffect:Xl,useTransition:Yl,useDeferredValue:Jl,useSyncExternalStore:Kl,startTransition:Wl,useRef:B,useImperativeHandle:es,useMemo:ke,useCallback:ae,useContext:kn,useDebugValue:Ul,version:"18.3.1",Children:Tr,render:Sh,hydrate:Ch,unmountComponentAtNode:xh,createPortal:sn,createElement:y,createContext:Cr,createFactory:Nh,cloneElement:Pr,createRef:Hm,Fragment:z,isValidElement:Tn,isElement:$h,isFragment:Eh,isMemo:Ah,findDOMNode:Dh,Component:Mt,PureComponent:ns,memo:ph,forwardRef:J,flushSync:rs,unstable_batchedUpdates:Lh,StrictMode:z,Suspense:Ro,SuspenseList:vi,lazy:bh,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ph},uI=Object.defineProperty,yi=(e,t)=>uI(e,"name",{value:t,configurable:!0}),Oh=!!(typeof window<"u"&&window.document&&window.document.createElement);function te(e,t,{checkForDefaultPrevented:n=!0}={}){return yi(function(i){if(e?.(i),n===!1||!i||!i.defaultPrevented)return t?.(i)},"handleEvent")}yi(te,"composeEventHandlers");function pI(e){if(!Oh)throw new Error("Cannot access window outside of the DOM");return e?.ownerDocument?.defaultView??window}yi(pI,"getOwnerWindow");function Zl(e){if(!Oh)throw new Error("Cannot access document outside of the DOM");return e?.ownerDocument??document}yi(Zl,"getOwnerDocument");function jh(e,t=!1){const{activeElement:n}=Zl(e);if(!n?.nodeName)return null;if(Mh(n)&&n.contentDocument)return jh(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const i=Zl(n).getElementById(r);if(i)return i}}return n}yi(jh,"getActiveElement");function Mh(e){return e.tagName==="IFRAME"}yi(Mh,"isFrame");var fI=Object.defineProperty,ed=(e,t)=>fI(e,"name",{value:t,configurable:!0});function td(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}ed(td,"setRef");function Fh(...e){return t=>{let n=!1;const r=e.map(i=>{const o=td(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():td(e[i],null)}}}}ed(Fh,"composeRefs");function Re(...e){return ae(Fh(...e),e)}ed(Re,"useComposedRefs");var mI=Object.defineProperty,Ft=(e,t)=>mI(e,"name",{value:t,configurable:!0});function hI(e,t){const n=Cr(t);n.displayName=e+"Context";const r=Ft(o=>{const{children:s,...c}=o,l=ke(()=>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=kn(n);if(l)return l;if(t!==void 0)return t;if(!c)throw new Error(`\`${o}\` must be used within \`${e}\``)}return Ft(i,"useContext"),[r,i]}Ft(hI,"createContext");function dt(e,t=[]){let n=[];function r(o,s){const c=Cr(s);c.displayName=o+"Context";const l=n.length;n=[...n,s];const d=Ft(p=>{const{scope:f,children:m,...v}=p,g=f?.[e]?.[l]||c,h=ke(()=>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=kn(g);if(h)return h;if(s!==void 0)return s;if(!v)throw new Error(`\`${p}\` must be used within \`${o}\``)}return Ft(u,"useContext"),[d,u]}Ft(r,"createContext");const i=Ft(()=>{const o=n.map(s=>Cr(s));return Ft(function(c){const l=c?.[e]||o;return ke(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])},"useScope")},"createScope");return i.scopeName=e,[r,Bh(i,...t)]}Ft(dt,"createContextScope");function Bh(...e){const t=e[0];if(e.length===1)return t;const n=Ft(()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return Ft(function(o){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(o)[`__scope${d}`];return{...c,...u}},{});return ke(()=>({[`__scope${t.scopeName}`]:s}),[s])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}Ft(Bh,"composeContextScopes");var Ze=globalThis?.document?It:()=>{},gI=Object.defineProperty,vI=(e,t)=>gI(e,"name",{value:t,configurable:!0}),yI=gi[" useId ".trim().toString()]||(()=>{}),bI=0;function Et(e){const[t,n]=x(yI());return Ze(()=>{e||n(r=>r??String(bI++))},[e]),e||(t?`radix-${t}`:"")}vI(Et,"useId");var _I=Object.defineProperty,wI=(e,t)=>_I(e,"name",{value:t,configurable:!0}),qh=gi[" useEffectEvent ".trim().toString()],Uh=gi[" useInsertionEffect ".trim().toString()];function Gh(e){if(typeof qh=="function")return qh(e);const t=B(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof Uh=="function"?Uh(()=>{t.current=e}):Ze(()=>{t.current=e}),ke(()=>((...n)=>t.current?.(...n)),[])}wI(Gh,"useEffectEvent");var SI=Object.defineProperty,Io=(e,t)=>SI(e,"name",{value:t,configurable:!0}),CI=gi[" useInsertionEffect ".trim().toString()]||Ze;function At({prop:e,defaultProp:t,onChange:n=Io(()=>{},"onChange"),caller:r}){const[i,o,s]=Hh({defaultProp:t,onChange:n}),c=e!==void 0;return[c?e:i,ae(d=>{if(c){const u=Vh(d)?d(e):d;u!==e&&s.current?.(u)}else o(d)},[c,e,o,s])]}Io(At,"useControllableState");function Hh({defaultProp:e,onChange:t}){const[n,r]=x(e),i=B(n),o=B(t);return CI(()=>{o.current=t},[t]),V(()=>{i.current!==n&&(o.current?.(n),i.current=n)},[n,i]),[n,r,o]}Io(Hh,"useUncontrolledState");function Vh(e){return typeof e=="function"}Io(Vh,"isFunction");var Kh=Symbol("RADIX:SYNC_STATE");function RI(e,t,n,r){const{prop:i,defaultProp:o,onChange:s,caller:c}=t,l=i!==void 0,d=Gh(s),u=[{...n,state:o}];r&&u.push(r);const[p,f]=In((h,b)=>{if(b.type===Kh)return{...h,state:b.state};const w=e(h,b);return l&&!Object.is(w.state,h.state)&&d(w.state),w},...u),m=p.state,v=B(m);V(()=>{v.current!==m&&(v.current=m,l||d(m))},[m,v,l]);const g=ke(()=>i!==void 0?{...p,state:i}:p,[p,i]);return V(()=>{l&&!Object.is(i,p.state)&&f({type:Kh,state:i})},[i,p.state,l]),[g,f]}Io(RI,"useControllableStateReducer");var II=Object.defineProperty,Wt=(e,t)=>II(e,"name",{value:t,configurable:!0});function cn(e){const t=J((n,r)=>{let{children:i,...o}=n,s=null,c=!1;const l=[];nd(i)&&typeof is=="function"&&(i=is(i._payload)),Tr.forEach(i,f=>{if(Xh(f)){c=!0;const m=f;let v="child"in m.props?m.props.child:m.props.children;nd(v)&&typeof is=="function"&&(v=is(v._payload)),s=kI(m,v),l.push(s?.props?.children)}else l.push(f)}),s?s=Pr(s,void 0,l):!c&&Tr.count(i)===1&&Tn(i)&&(s=i);const d=s?Yh(s):void 0,u=Re(r,d);if(!s){if(i||i===0)throw new Error(c?NI(e):PI(e));return i}const p=Jh(o,s.props??{});return s.type!==z&&(p.ref=r?u:d),Pr(s,p)});return t.displayName=`${e}.Slot`,t}Wt(cn,"createSlot");var zh=Symbol.for("radix.slottable");function Wh(e){const t=Wt(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${e}.Slottable`,t.__radixId=zh,t}Wt(Wh,"createSlottable");var kI=Wt((e,t)=>{if("child"in e.props){const n=e.props.child;return Tn(n)?Pr(n,void 0,e.props.children(n.props.children)):null}return Tn(t)?t:null},"getSlottableElementFromSlottable");function Jh(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}}Wt(Jh,"mergeProps");function Yh(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)}Wt(Yh,"getElementRef");function Xh(e){return Tn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===zh}Wt(Xh,"isSlottable");var TI=Symbol.for("react.lazy");function nd(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===TI&&"_payload"in e&&Qh(e._payload)}Wt(nd,"isLazyComponent");function Qh(e){return typeof e=="object"&&e!==null&&"then"in e}Wt(Qh,"isPromiseLike");var PI=Wt(e=>`${e} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),NI=Wt(e=>`${e} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),is=gi[" use ".trim().toString()],EI=Object.defineProperty,AI=(e,t)=>EI(e,"name",{value:t,configurable:!0}),ye=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=cn(`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 os(e,t){e&&rs(()=>e.dispatchEvent(t))}AI(os,"dispatchDiscreteCustomEvent");var xI=Object.defineProperty,DI=(e,t)=>xI(e,"name",{value:t,configurable:!0});function ht(e){const t=B(e);return V(()=>{t.current=e}),ke(()=>((...n)=>t.current?.(...n)),[])}DI(ht,"useCallbackRef");var LI=Object.defineProperty,rt=(e,t)=>LI(e,"name",{value:t,configurable:!0}),rd="dismissableLayer.update",$I="dismissableLayer.pointerDownOutside",OI="dismissableLayer.focusOutside",Zh,id=Cr({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),bi=J(rt(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:o,onPointerDownOutside:s,onFocusOutside:c,onInteractOutside:l,onDismiss:d,...u}=t,p=kn(id),[f,m]=x(null),v=f?.ownerDocument??globalThis?.document,[,g]=x({}),h=Re(n,m),b=Array.from(p.layers),[w]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),_=w?b.indexOf(w):-1,R=f?b.indexOf(f):-1,I=p.layersWithOutsidePointerEventsDisabled.size>0,T=R>=_,A=B(!1),O=tg(D=>{s?.(D),l?.(D),D.defaultPrevented||d?.()},{ownerDocument:v,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:A,dismissableSurfaces:p.dismissableSurfaces,shouldHandlePointerDownOutside:ae(D=>{if(!(D instanceof Node))return!1;const G=[...p.branches].some(q=>q.contains(D));return T&&!G},[p.branches,T])}),F=ng(D=>{if(i&&A.current)return;const G=D.target;[...p.branches].some(q=>q.contains(G))||(c?.(D),l?.(D),D.defaultPrevented||d?.())},v),N=f?R===b.length-1:!1,L=ht(D=>{D.key==="Escape"&&(o?.(D),!D.defaultPrevented&&d&&(D.preventDefault(),d()))});return V(()=>{if(N)return v.addEventListener("keydown",L,{capture:!0}),()=>v.removeEventListener("keydown",L,{capture:!0})},[v,N,L]),V(()=>{if(f)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(Zh=v.body.style.pointerEvents,v.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(f)),p.layers.add(f),od(),()=>{r&&(p.layersWithOutsidePointerEventsDisabled.delete(f),p.layersWithOutsidePointerEventsDisabled.size===0&&(v.body.style.pointerEvents=Zh))}},[f,v,r,p]),V(()=>()=>{f&&(p.layers.delete(f),p.layersWithOutsidePointerEventsDisabled.delete(f),od())},[f,p]),V(()=>{const D=rt(()=>g({}),"handleUpdate");return document.addEventListener(rd,D),()=>document.removeEventListener(rd,D)},[]),a(ye.div,{...u,ref:h,style:{pointerEvents:I?T?"auto":"none":void 0,...t.style},onFocusCapture:te(t.onFocusCapture,F.onFocusCapture),onBlurCapture:te(t.onBlurCapture,F.onBlurCapture),onPointerDownCapture:te(t.onPointerDownCapture,O.onPointerDownCapture)})},"DismissableLayer")),jI=J(rt(function(t,n){const r=kn(id),i=B(null),o=Re(n,i);return V(()=>{const s=i.current;if(s)return r.branches.add(s),()=>{r.branches.delete(s)}},[r.branches]),a(ye.div,{...t,ref:o})},"DismissableLayerBranch"));function eg(){const e=kn(id),[t,n]=x(null);return V(()=>{if(t)return e.dismissableSurfaces.add(t),()=>{e.dismissableSurfaces.delete(t)}},[t,e.dismissableSurfaces]),n}rt(eg,"useDismissableLayerSurface");var MI=rt(()=>!0,"IS_TRUE");function tg(e,t){const{ownerDocument:n=globalThis?.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:o,shouldHandlePointerDownOutside:s=MI}=t,c=ht(e),l=B(!1),d=B(!1),u=B(new Map),p=B(()=>{});return V(()=>{function f(){d.current=!1,i.current=!1,u.current.clear()}rt(f,"resetOutsideInteraction");function m(){return Array.from(u.current.values()).some(Boolean)}rt(m,"isOutsideInteractionIntercepted");function v(_){if(!d.current)return;const R=_.target;R instanceof Node&&[...o].some(I=>I.contains(R))||u.current.set(_.type,!0),_.type==="click"&&window.setTimeout(()=>{d.current&&p.current()},0)}rt(v,"handleInteractionCapture");function g(_){d.current&&u.current.set(_.type,!1)}rt(g,"handleInteractionBubble");const h=rt(_=>{if(_.target&&!l.current){let R=function(){n.removeEventListener("click",p.current);const T=m();f(),T||ad($I,c,I,{discrete:!0})};if(rt(R,"handleAndDispatchPointerDownOutsideEvent"),!s(_.target)){n.removeEventListener("click",p.current),f(),l.current=!1;return}const I={originalEvent:_};d.current=!0,i.current=r&&_.button===0,u.current.clear(),!r||_.button!==0?R():(n.removeEventListener("click",p.current),p.current=R,n.addEventListener("click",p.current,{once:!0}))}else n.removeEventListener("click",p.current),f();l.current=!1},"handlePointerDown"),b=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const _ of b)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 b)n.removeEventListener(_,v,!0),n.removeEventListener(_,g)}},[n,c,r,i,o,s]),{onPointerDownCapture:rt(()=>l.current=!0,"onPointerDownCapture")}}rt(tg,"usePointerDownOutside");function ng(e,t=globalThis?.document){const n=ht(e),r=B(!1);return V(()=>{const i=rt(o=>{o.target&&!r.current&&ad(OI,n,{originalEvent:o},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:rt(()=>r.current=!0,"onFocusCapture"),onBlurCapture:rt(()=>r.current=!1,"onBlurCapture")}}rt(ng,"useFocusOutside");function od(){const e=new CustomEvent(rd);document.dispatchEvent(e)}rt(od,"dispatchUpdate");function ad(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?os(i,o):i.dispatchEvent(o)}rt(ad,"handleAndDispatchCustomEvent");var FI=bi,BI=jI,qI=Object.defineProperty,St=(e,t)=>qI(e,"name",{value:t,configurable:!0}),sd="focusScope.autoFocusOnMount",cd="focusScope.autoFocusOnUnmount",rg={bubbles:!1,cancelable:!0},as=J(St(function(t,n){const{loop:r=!1,trapped:i=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...c}=t,[l,d]=x(null),u=ht(o),p=ht(s),f=B(null),m=Re(n,d),v=B({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;V(()=>{if(i){let h=function(R){if(v.paused||!l)return;const I=R.target;l.contains(I)?f.current=I:Pn(f.current,{select:!0})},b=function(R){if(v.paused||!l)return;const I=R.relatedTarget;I!==null&&(l.contains(I)||Pn(f.current,{select:!0}))},w=function(R){if(document.activeElement===document.body)for(const I of R)I.removedNodes.length>0&&Pn(l)};St(h,"handleFocusIn"),St(b,"handleFocusOut"),St(w,"handleMutations"),document.addEventListener("focusin",h),document.addEventListener("focusout",b);const _=new MutationObserver(w);return l&&_.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",b),_.disconnect()}}},[i,l,v.paused]),V(()=>{if(l){cg.add(v);const h=document.activeElement;if(!l.contains(h)){const b=new CustomEvent(sd,rg);l.addEventListener(sd,u),l.dispatchEvent(b),b.defaultPrevented||(ig(dg(ld(l)),{select:!0}),document.activeElement===h&&Pn(l))}return()=>{l.removeEventListener(sd,u),setTimeout(()=>{const b=new CustomEvent(cd,rg);l.addEventListener(cd,p),l.dispatchEvent(b),b.defaultPrevented||Pn(h??document.body,{select:!0}),l.removeEventListener(cd,p),cg.remove(v)},0)}}},[l,u,p,v]);const g=ae(h=>{if(!r&&!i||v.paused)return;const b=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,w=document.activeElement;if(b&&w){const _=h.currentTarget,[R,I]=og(_);R&&I?!h.shiftKey&&w===I?(h.preventDefault(),r&&Pn(R,{select:!0})):h.shiftKey&&w===R&&(h.preventDefault(),r&&Pn(I,{select:!0})):w===_&&h.preventDefault()}},[r,i,v.paused]);return a(ye.div,{tabIndex:-1,...c,ref:m,onKeyDown:g})},"FocusScope"));function ig(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Pn(r,{select:t}),document.activeElement!==n)return}St(ig,"focusFirst");function og(e){const t=ld(e);return[dd(t,e),dd(t.reverse(),e)]}St(og,"getTabbableEdges");function ld(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:St(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}St(ld,"getTabbableCandidates");function dd(e,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of e)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):ag(r,{upTo:t})))return r}St(dd,"findVisible");function ag(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}St(ag,"isHidden");function sg(e){return e instanceof HTMLInputElement&&"select"in e}St(sg,"isSelectableInput");function Pn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&sg(e)&&t&&e.select()}}St(Pn,"focus");var cg=lg();function lg(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=ud(e,t),e.unshift(t)},remove(t){e=ud(e,t),e[0]?.resume()}}}St(lg,"createFocusScopesStack");function ud(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}St(ud,"arrayRemove");function dg(e){return e.filter(t=>t.tagName!=="A")}St(dg,"removeLinks");var UI=Object.defineProperty,GI=(e,t)=>UI(e,"name",{value:t,configurable:!0}),_i=J(GI(function(t,n){const{container:r,...i}=t,[o,s]=x(!1);Ze(()=>s(!0),[]);const c=r||o&&globalThis?.document?.body;return c?sn(a(ye.div,{...i,ref:n}),c):null},"Portal")),HI=Object.defineProperty,Nn=(e,t)=>HI(e,"name",{value:t,configurable:!0});function ug(e,t){return In((n,r)=>t[n][r]??n,e)}Nn(ug,"useStateMachine");var kt=Nn(e=>{const{present:t,children:n}=e,r=pg(t),i=typeof n=="function"?n({present:r.isPresent}):Tr.only(n),o=fg(r.ref,mg(i));return typeof n=="function"||r.isPresent?Pr(i,{ref:o}):null},"Presence");function pg(e){const[t,n]=x(),r=B(null),i=B(e),o=B("none"),s=B(void 0),[c,l]=ug(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return V(()=>{c==="mounted"?(o.current=s.current??wi(r.current),s.current=void 0):o.current="none"},[c]),Ze(()=>{const d=r.current,u=i.current;if(u!==e){const p=o.current,f=wi(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]),Ze(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,p=Nn(m=>{const v=wi(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=Nn(m=>{m.target===t&&(o.current=wi(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:ae(d=>{if(d){const u=getComputedStyle(d);r.current=u,s.current=wi(u)}else r.current=null;n(d)},[])}}Nn(pg,"usePresence");function pd(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}Nn(pd,"setRef");function fg(...e){const t=B(e);return t.current=e,ae(n=>{const r=t.current;let i=!1;const o=r.map(s=>{const c=pd(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():pd(r[s],null)}}},[])}Nn(fg,"useStableComposedRefs");function wi(e){return e?.animationName||"none"}Nn(wi,"getAnimationName");function mg(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)}Nn(mg,"getElementRef");var VI=Object.defineProperty,fd=(e,t)=>VI(e,"name",{value:t,configurable:!0}),ss=0,Si=null;function KI(e){return Ci(),e.children}fd(KI,"FocusGuards");function Ci(){V(()=>{Si||(Si={start:md(),end:md()});const{start:e,end:t}=Si;return document.body.firstElementChild!==e&&document.body.insertAdjacentElement("afterbegin",e),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),ss++,()=>{ss===1&&(Si?.start.remove(),Si?.end.remove(),Si=null),ss=Math.max(0,ss-1)}},[])}fd(Ci,"useFocusGuards");function md(){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}fd(md,"createFocusGuard");var ln=function(){return ln=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},ln.apply(this,arguments)};function hg(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 zI(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 cs="right-scroll-bar-position",ls="width-before-scroll-bar",WI="with-scroll-bars-hidden",JI="--removed-body-scroll-bar-size";function hd(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function YI(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 XI=typeof window<"u"?It:V,gg=new WeakMap;function QI(e,t){var n=YI(t||null,function(r){return e.forEach(function(i){return hd(i,r)})});return XI(function(){var r=gg.get(n);if(r){var i=new Set(r),o=new Set(e),s=n.current;i.forEach(function(c){o.has(c)||hd(c,null)}),o.forEach(function(c){i.has(c)||hd(c,s)})}gg.set(n,e)},[e]),n}function ZI(e){return e}function ek(e,t){t===void 0&&(t=ZI);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 tk(e){e===void 0&&(e={});var t=ek(null);return t.options=ln({async:!0,ssr:!1},e),t}var vg=function(e){var t=e.sideCar,n=hg(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,ln({},n))};vg.isSideCarExport=!0;function nk(e,t){return e.useMedium(t),vg}var yg=tk(),gd=function(){},ds=J(function(e,t){var n=B(null),r=x({onScrollCapture:gd,onWheelCapture:gd,onTouchMoveCapture:gd}),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,b=e.as,w=b===void 0?"div":b,_=e.gapMode,R=hg(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),I=f,T=QI([n,t]),A=ln(ln({},R),i);return y(z,null,u&&y(I,{sideCar:yg,removeScrollBar:d,shards:p,noRelative:m,noIsolation:v,inert:g,setCallbacks:o,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?Pr(Tr.only(c),ln(ln({},A),{ref:T})):y(w,ln({},A,{className:l,ref:T}),c))});ds.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ds.classNames={fullWidth:ls,zeroRight:cs};var bg,rk=function(){if(bg)return bg;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function ik(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=rk();return t&&e.setAttribute("nonce",t),e}function ok(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ak(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var sk=function(){var e=0,t=null;return{add:function(n){e==0&&(t=ik())&&(ok(t,n),ak(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ck=function(){var e=sk();return function(t,n){V(function(){return e.add(t),function(){e.remove()}},[t&&n])}},_g=function(){var e=ck(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},lk={left:0,top:0,right:0,gap:0},vd=function(e){return parseInt(e||"",10)||0},dk=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[vd(n),vd(r),vd(i)]},uk=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return lk;var t=dk(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])}},pk=_g(),ko="data-scroll-locked",fk=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(WI,` {
|
|
3
3
|
overflow: hidden `).concat(r,`;
|
|
4
4
|
padding-right: `).concat(c,"px ").concat(r,`;
|
|
5
5
|
}
|
|
6
|
-
body[`).concat(
|
|
6
|
+
body[`).concat(ko,`] {
|
|
7
7
|
overflow: hidden `).concat(r,`;
|
|
8
8
|
overscroll-behavior: contain;
|
|
9
9
|
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
@@ -16,39 +16,39 @@
|
|
|
16
16
|
`),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
.`).concat(
|
|
19
|
+
.`).concat(cs,` {
|
|
20
20
|
right: `).concat(c,"px ").concat(r,`;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
.`).concat(
|
|
23
|
+
.`).concat(ls,` {
|
|
24
24
|
margin-right: `).concat(c,"px ").concat(r,`;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
.`).concat(
|
|
27
|
+
.`).concat(cs," .").concat(cs,` {
|
|
28
28
|
right: 0 `).concat(r,`;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
.`).concat(
|
|
31
|
+
.`).concat(ls," .").concat(ls,` {
|
|
32
32
|
margin-right: 0 `).concat(r,`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
body[`).concat(
|
|
36
|
-
`).concat(
|
|
35
|
+
body[`).concat(ko,`] {
|
|
36
|
+
`).concat(JI,": ").concat(c,`px;
|
|
37
37
|
}
|
|
38
|
-
`)},
|
|
38
|
+
`)},wg=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},mk=function(){V(function(){return document.body.setAttribute(ko,(wg()+1).toString()),function(){var e=wg()-1;e<=0?document.body.removeAttribute(ko):document.body.setAttribute(ko,e.toString())}},[])},hk=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;mk();var o=ke(function(){return uk(i)},[i]);return y(pk,{styles:fk(o,!t,i,n?"":"!important")})},yd=!1;if(typeof window<"u")try{var us=Object.defineProperty({},"passive",{get:function(){return yd=!0,!0}});window.addEventListener("test",us,us),window.removeEventListener("test",us,us)}catch{yd=!1}var Ri=yd?{passive:!1}:!1,gk=function(e){return e.tagName==="TEXTAREA"},Sg=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!gk(e)&&n[t]==="visible")},vk=function(e){return Sg(e,"overflowY")},yk=function(e){return Sg(e,"overflowX")},Cg=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),Rg(e,r)){var i=Ig(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},bk=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},_k=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Rg=function(e,t){return e==="v"?vk(t):yk(t)},Ig=function(e,t){return e==="v"?bk(t):_k(t)},wk=function(e,t){return e==="h"&&t==="rtl"?-1:1},Sk=function(e,t,n,r,i){var o=wk(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=Ig(e,c),v=m[0],g=m[1]-m[2]-o*v;(v||g)&&Rg(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},ps=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},kg=function(e){return[e.deltaX,e.deltaY]},Tg=function(e){return e&&"current"in e?e.current:e},Ck=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Rk=function(e){return`
|
|
39
39
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
40
40
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
41
|
-
`)},OR=0,wi=[];function MR(e){var t=q([]),n=q([0,0]),r=q(),i=x(OR++)[0],o=x(Yh)[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=oR([e.lockRef.current],(e.shards||[]).map(rg),!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],R,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=Zh(A,k);if(!T)return!0;if(T?R=A:(R=A==="v"?"h":"v",T=Zh(A,k)),!T)return!1;if(!r.current&&"changedTouches"in g&&(_||I)&&(r.current=R),!R)return!0;var M=r.current||R;return $R(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?ng(h):ss(h),w=t.current.filter(function(I){return I.name===h.type&&(I.target===h.target||h.target===I.shadowParent)&&LR(I.delta,y)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(rg).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:FR(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,ng(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:jR(i)}):null,m?b(kR,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function FR(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var BR=mR(Wh,MR),Co=J(function(e,t){return b(os,an({},e,{ref:t,sideCar:BR}))});Co.classNames=os.classNames;var UR=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},Si=new WeakMap,cs=new WeakMap,ls={},od=0,ig=function(e){return e&&(e.host||ig(e.parentNode))},qR=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=ig(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})},GR=function(e,t,n,r){var i=qR(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||UR(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),GR(r,i,n,"aria-hidden")):function(){return null}},HR=Object.defineProperty,sn=(e,t)=>HR(e,"name",{value:t,configurable:!0}),ad="Dialog",[og,kU]=lt(ad),[KR,Jn]=og(ad),VR=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]=At({prop:r,defaultProp:i??!1,onChange:o,caller:ad}),[p,f]=x(0),[m,v]=x(0);return a(KR,{scope:t,triggerRef:c,contentRef:l,contentId:Et(),titleId:Et(),descriptionId:Et(),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"),ag="DialogPortal",[zR,sg]=og(ag,{forceMount:void 0}),WR=sn(e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=Jn(ag,t);return a(zR,{scope:t,forceMount:n,children:Ir.map(r,s=>a(Rt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:s})}))})},"DialogPortal"),sd="DialogOverlay",JR=J(sn(function(t,n){const r=sg(sd,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Jn(sd,t.__scopeDialog);return s.modal?a(Rt,{present:i||s.open,children:a(XR,{...o,ref:n})}):null},"DialogOverlay")),YR=on("DialogOverlay.RemoveScroll"),XR=J(sn(function(t,n){const{__scopeDialog:r,...i}=t,o=Jn(sd,r),s=Eh(),c=Se(n,s);return a(Co,{as:YR,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",QR=J(sn(function(t,n){const r=sg(Io,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Jn(Io,t.__scopeDialog);return a(Rt,{present:i||s.open,children:s.modal?a(ZR,{...o,ref:n}):a(eP,{...o,ref:n})})},"DialogContent")),ZR=J(sn(function(t,n){const r=Jn(Io,t.__scopeDialog),i=q(null),o=Se(n,r.contentRef,i);return K(()=>{const s=i.current;if(s)return ds(s)},[]),a(cg,{...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")),eP=J(sn(function(t,n){const r=Jn(Io,t.__scopeDialog),i=q(!1),o=q(!1);return a(cg,{...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")),cg=J(sn(function(t,n){const{__scopeDialog:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,...c}=t,l=Jn(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")),tP="DialogTitle",nP=J(sn(function(t,n){const{__scopeDialog:r,...i}=t,o=Jn(tP,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 Pr({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(VR,{modal:o,open:p,onOpenChange:u,children:p?a(WR,{children:[a(JR,{asChild:!0,children:a("div",{className:f,id:m})}),a(QR,{"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 rP(e){return a(nP,{...e})}function iP(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function Ro(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function lg(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(iP)}function kr(e){const t=new Map;for(const r of lg(e)){const i=Ro(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 oP(e){const t=new Map;for(const n of lg(e)){const r=Ro(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=Ro(n.displayName).localeCompare(Ro(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 dg=500,us=null,Po=null,ko=null;function To(e){return Po?Po(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 ug(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 aP(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 sP(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 cP(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 pg(e,t){return e instanceof hl?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function fg({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 lP(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 mg(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function dP(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=>aP(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function uP(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 pP(e,t,n){return e.mode==="project-add"?mg(e).flatMap(r=>t.flatMap(i=>{const o=ug(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=ug(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 fP(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 hg(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 mP(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 hP(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 gP({preview:e,projectLabels:t,recipientLabels:n}){const r=hP(e.effectiveDevices),i=mP(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:["— ",hg(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:["— ",hg(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 vP({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 yP({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),R=q(new Map),k=Pe(()=>sP(e,r),[e,r]),A=Pe(()=>lP(e,r,k),[e,r,k]),L=Pe(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName]),...k]),[e,k]),F=Pe(()=>cP(n,r,c),[c,n,r]),T=Pe(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]),M=Pe(()=>{const Y=kr(n.map(ce=>({canonicalId:ce.canonicalProjectIdentity,displayName:ce.displayName})));return new Map([...Y,...F])},[n,F]);if(K(()=>{if(Po=Y=>{if(_.current)return!1;const ce=dP(Y,e);return i(Y),l(ce),s(Y.mode==="recipient-add"?[]:ce),u(null),f(null),I.current=new Map,R.current=new Map,v(null),h(""),w(!1),_.current=!1,!0},us){const Y=us;us=null,Po(Y)}return()=>{Po=null}},[e]),K(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const j=fP(r),B=mg(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=pP(r,o,c),D=S.length>dg,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=uP(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,R.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 EC({version:1,changes:S});I.current=new Map(L),R.current=new Map(M),u(Y),h("Review ready. Confirm the exact changes.")}catch(Y){v(pg(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 AC({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,R.current=new Map,h("")),v(pg(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(Pr,{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(vP,{preview:d,projectLabels:R.current,recipientLabels:I.current,result:p}):d?a(gP,{preview:d,projectLabels:R.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(fg,{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(fg,{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 ",dg.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,R.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 gg(e,t,n,r={}){We(a(yP,{intent:n,options:r,projects:t}),e)}function ps(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function bP(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 vg({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 _P(e){return e.state!=="configured"}function yg(e){return e?.items.filter(_P)??[]}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 wP=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,SP=/^(?:actor|device|identity|local):\S+$/iu,CP=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,IP=/^pending[_-]\S+$/iu,RP=/^[a-f0-9]{12,64}$/iu;function ud(e){return[wP,SP,CP,IP,RP].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,Ri=null;function hs(e=[],t=""){if(Ri){const n=Ri(e,t);return n||(Ii=null),n}return Ii={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function bg(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function _g(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 PP(e){const t=`share-project-${Cr()}`,n=bg(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 kP({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 TP({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=Pe(()=>e.filter(bg),[e]);K(()=>{if(Ri=(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,Ri(T.projectIds,T.teammateName)}return()=>{Ri=null}},[I,t]),K(()=>{t&&(Ii=null,r(!1),o(""),c([]),d(null),p(null),m(null),y(null),_(!1))},[t]);const R=()=>{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 jC({teammate_name:i.trim(),project_ids:s}))}catch(T){m(_g(T,"Unable to review this invitation."))}finally{g(!1)}},L=async()=>{if(l){m(null),g(!0);try{p(await OC({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(_g(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:()=>Ri?.([]),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(Pr,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:T=>{T||R()},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:R,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(kP,{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(PP,{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:R,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 wg(e,t,n={}){We(a(TP,{inventoryError:n.inventoryError===!0,projects:t}),e)}function pd(e){return Ci(String(e??"").trim())}function Pi(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 NP(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 Wf?{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 EP({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 AP({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(EP,{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 xP({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 Sg({preview:e}){return e.journey==="team"?a(AP,{preview:e}):a(xP,{preview:e})}function DP({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 $P({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 LP({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 jP({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 Cg(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function OP({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(""),[R,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,Re)=>{oe(),S.current=Re,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 xC(Cg(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 DC({...Cg(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(),Re=D.current;if(!W){E("Paste an invitation first.");return}const re=()=>D.current===Re&&H.current.trim()===W;j(!0),E(""),U("Reviewing invitation…");try{const je=await Jf(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"&&(Pi(R,"Identity display name")||Pi(A,"Device display name")))&&!(m.kind==="team_member"&&Pi(_,"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:R.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(NP(W)),U("");else{const Re=m.kind,re=W.restart_required===!0||W.setup_state==="restart_required";w({kind:Re,restartRequired:re,detail:Re==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:Re==="add_device"&&(m.onboarding?.projects?.length??0)>0}),U("")}}catch(W){G.current=!1;const Re=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,Re)),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"?Pi(_,"Identity display name"):"",He=ge?Pi(R,"Identity display name"):"",de=ge?Pi(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(Pr,{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(Sg,{preview:p}):null,ce&&!y?a(Sg,{preview:ce}):null,m?.kind==="team_member"&&!y?a(DP,{error:pe,name:_,onChange:W=>{I(W),E("")}}):null,ge&&!g?a($P,{deviceName:A,deviceNameError:de,invite:ge,onDeviceNameChange:W=>{L(W),E("")},onRecipientNameChange:W=>{k(W),E("")},recipientName:R,recipientNameError:He}):null,g?a(LP,{result:g}):null,y?a(jP,{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 MP(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 FP(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 BP({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=oC,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 R=MP(l);if(R){m(R);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(FP(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(Pr,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:R=>{R.preventDefault(),h.current?.focus()},onEscapeKeyDown:R=>{u&&R.preventDefault()},onInteractOutside:R=>{u&&R.preventDefault()},onOpenAutoFocus:R=>{R.preventDefault(),y.current?.focus(),y.current?.select()},onOpenChange:R=>{R||_()},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:R=>{d(R.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 Ig={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Rg={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},fd={role:"list"},md={role:"listitem"};function UP(e){return typeof e=="string"&&Object.hasOwn(Ig,e)?Ig[e]:"Ready to review"}function qP(e){return typeof e=="string"&&Object.hasOwn(Rg,e)?Rg[e]:"needs_attention"}function GP(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 HP({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=GP(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 ${qP(i.status)}`.trim(),children:UP(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 KP(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:KP(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 kg(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var Tg=3;function Ng({empty:e,identities:t,qualifier:n}){if(t.length===0)return a(z,{children:e});const r=oP(t),i=s=>s.identityCount>1?`${s.displayName} (${Vt(s.identityCount,"identity","identities")})`:s.displayName,o=r.slice(0,Tg);return a(z,{children:[Vt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",o.map(i).join(", "),r.length>Tg?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 Eg({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 VP({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=kg(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(Ng,{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(Eg,{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(BP,{descriptionId:g,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function zP({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=kg(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(Ng,{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(Eg,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function WP({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 JP({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=yg(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(HP,{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(vg,{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(VP,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):m.id==="identities"?a(zP,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?a(WP,{received:t.received??[]}):a(OP,{intent:e})})},m.id))]})}function YP(e,t,n,r={}){We(a(JP,{intent:n,options:r,projects:t}),e)}var gd={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function XP(){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:bP(e)}}var QP={loadDeviceInventory:vl,loadIntent:gl,loadProjects:XP,loadSyncStatus:Ua,loadTeamSetupSummary:rm,mountManagement:gg,mountSharing:YP};function ZP(e={},t={}){const n={...QP,...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)),[R,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=pm(L.value));let T,M,j;const B=R.status==="fulfilled"&&k.status==="fulfilled";if(u=!B,p=F,B){const E=R.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 ek=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)&&xg(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(bs=0,kn--,t)throw e}}function tk(e){if(kn>0)return e();vd=++nk,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,nk=0,vd=0,_s=void 0,ws=0;function Ag(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=ek,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=Ag(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 xg(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 Dg(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 $g(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&&!xg(this))return this.f&=-2,!0;var e=Ke;try{Dg(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,$g(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=Ag(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Lg(e,t){return new Nr(e,t)}function jg(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,jg(e)}function rk(e){if(Ke!==this)throw new Error("Out-of-order effect");$g(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,jg(this),Dg(this),kn++;var e=Ke;return Ke=this,rk.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 Og,_d,Ss,ik=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Mg=[];Do(function(){Og=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 Fg(e){var t=this,n=e.data,r=ak(n);r.name="ReactiveDom",r.value=n;var i=Pe(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Lg(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=Lg(function(){return!Array.isArray(d.value)&&!mm(d.value)}),p=Do(function(){if(this.N=Bg,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}Fg.displayName="ReactiveTextNode",Object.defineProperties(ut.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Fg},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;ik&&((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=ok(n,l,u,i),o[l]=d):d.o(u,i)}}}e(t)});function ok(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=Bg;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)}),Ot.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 ak(e,t){return Pe(function(){return yd(e,t)},[])}var sk=function(e){queueMicrotask(function(){queueMicrotask(e)})};function ck(){tk(function(){for(var e;e=Mg.shift();)Og.call(e)})}function Bg(){Mg.push(this)===1&&(he.requestAnimationFrame||sk)(ck)}var lk=Object.defineProperty,at=(e,t)=>lk(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),R=Se(h,I),k=o(u,y);return K(()=>(k.itemMap.set(I,{ref:I,..._}),()=>{k.itemMap.delete(I)})),a(f,{[p]:"",ref:R,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 Ug=new WeakMap,wd=class yr extends Map{static{at(this,"OrderedDict")}#e;constructor(t){super(t),this.#e=[...super.keys()],Ug.set(this,!0)}set(t,n){return Ug.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=qg(e,t);return n===-1?void 0:e[n]}at(Is,"at");function qg(e,t){const n=e.length,r=Sd(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}at(qg,"toSafeIndex");function Sd(e){return e!==e||e===0?0:Math.trunc(e)}at(Sd,"toSafeInteger");function dk(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:R}=w,k=q(null),[A,L]=x(null),F=Se(k,L),[T,M]=R;return K(()=>{if(!A)return;const j=Kg(()=>{});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:R}=w,k=o(d,I),A=Se(_,k.collectionRef);return a(u,{ref:A,children:R})});p.displayName=d;const f=e+"CollectionItemSlot",m="data-radix-collection-item",v=on(f),g=J((w,_)=>{const{scope:I,children:R,...k}=w,A=q(null),[L,F]=x(null),T=Se(_,A,F),{setItemMap:M}=o(f,I),j=q(k);Gg(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:R})});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(dk,"createCollection");function Gg(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(Gg,"shallowEqual");function Hg(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}at(Hg,"isElementPreceding");function Cd(e,t){return!e[1].element||!t[1].element?0:Hg(e[1].element,t[1].element)?-1:1}at(Cd,"sortByDocumentPosition");function Kg(e){return new MutationObserver(t=>{for(const n of t)if(n.type==="childList"){e();return}})}at(Kg,"getChildListObserver");var uk=Object.defineProperty,pk=(e,t)=>uk(e,"name",{value:t,configurable:!0}),Vg=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(pk(function(t,n){return a(ve.span,{...t,ref:n,style:{...Vg,...t.style}})},"VisuallyHidden")),fk=Id,mk=Object.defineProperty,qe=(e,t)=>mk(e,"name",{value:t,configurable:!0}),zg="ToastProvider",[Rd,Wg,hk]=$o("Toast"),[Jg,TU]=lt("Toast",[hk]),[gk,Rs]=Jg(zg),vk=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 \`${zg}\`. Expected non-empty \`string\`.`),a(Rd.Provider,{scope:t,children:a(gk,{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"),yk="ToastViewport",bk=["F8"],Pd="toast.viewportPause",kd="toast.viewportResume",_k=J(qe(function(t,n){const{__scopeToast:r,hotkey:i=bk,label:o="Notifications ({hotkey})",...s}=t,c=Rs(yk,r),l=Wg(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(Pd);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"),R=qe(A=>{y.contains(A.relatedTarget)||I()},"handleFocusOutResume"),k=qe(()=>{y.contains(document.activeElement)||I()},"handlePointerLeaveResume");return y.addEventListener("focusin",_),y.addEventListener("focusout",R),y.addEventListener("pointermove",_),y.addEventListener("pointerleave",k),window.addEventListener("blur",_),window.addEventListener("focus",I),()=>{y.removeEventListener("focusin",_),y.removeEventListener("focusout",R),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,R=[I,...ev(I)];return y==="forwards"?R:R.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 R=document.activeElement,k=_.shiftKey;if(_.target===y&&k){u.current?.focus();return}const A=h({tabbingDirection:k?"backwards":"forwards"}),L=A.findIndex(F=>F===R);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(QI,{ref:d,role:"region","aria-label":o.replace("{hotkey}",v),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Yg,{ref:u,onFocusFromOutsideViewport:()=>{ks(h({tabbingDirection:"forwards"}))}}),a(Rd.Slot,{scope:r,children:a(ve.ol,{tabIndex:-1,...s,ref:m})}),g&&a(Yg,{ref:p,onFocusFromOutsideViewport:()=>{ks(h({tabbingDirection:"backwards"}))}})]})},"ToastViewport")),wk="ToastFocusProxy",Yg=J(qe(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:i,...o}=t,s=Rs(wk,r);return a(Id,{tabIndex:0,...o,ref:n,style:{position:"fixed"},onFocus:c=>{const l=c.relatedTarget;s.viewport?.contains(l)||i()}})},"ToastFocusProxy")),Ps="Toast",Sk="toast.swipeStart",Ck="toast.swipeMove",Ik="toast.swipeCancel",Rk="toast.swipeEnd",Pk=J(qe(function(t,n){const{forceMount:r,open:i,defaultOpen:o,onOpenChange:s,...c}=t,[l,d]=At({prop:i,defaultProp:o??!0,onChange:s,caller:Ps});return a(Rt,{present:r||l,children:a(Nk,{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")),[kk,Tk]=Jg(Ps,{onClose(){}}),Nk=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=Rs(Ps,r),y=Wg(r),[w,_]=x(null),I=Se(n,_),R=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(Pd,D),E.addEventListener(kd,S),()=>{E.removeEventListener(Pd,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 $=Pe(()=>w?Td(w):null,[w]);return h.viewport?a(z,{children:[$&&a(Ek,{__scopeToast:r,role:"status","aria-live":i==="foreground"?"assertive":"polite",children:$}),a(kk,{scope:r,onClose:B,children:rn(a(Rd.ItemSlot,{scope:r,children:a(XI,{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&&(R.current={x:E.clientX,y:E.clientY})}),onPointerMove:ne(t.onPointerMove,E=>{if(!R.current)return;const S=E.clientX-R.current.x,D=E.clientY-R.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(Ck,f,Ie,{discrete:!1})):Xg(Ce,h.swipeDirection,ie)?(k.current=Ce,Lo(Sk,p,Ie,{discrete:!1}),E.target.setPointerCapture(E.pointerId)):(Math.abs(S)>ie||Math.abs(D)>ie)&&(R.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,R.current=null,S){const H=E.currentTarget,G={originalEvent:E,delta:S};Xg(S,h.swipeDirection,h.swipeThreshold)?Lo(Rk,v,G,{discrete:!0}):Lo(Ik,m,G,{discrete:!0}),H.addEventListener("click",oe=>oe.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null},"ToastImpl")),Ek=qe(e=>{const{__scopeToast:t,children:n,...r}=e,i=Rs(Ps,t),[o,s]=x(!1),[c,l]=x(!1);return Qg(()=>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"),Ak=J(qe(function(t,n){const{__scopeToast:r,...i}=t;return a(ve.div,{...i,ref:n})},"ToastDescription")),xk="ToastClose",Dk=J(qe(function(t,n){const{__scopeToast:r,...i}=t,o=Tk(xk,r);return a($k,{asChild:!0,children:a(ve.button,{type:"button",...i,ref:n,onClick:ne(t.onClick,o.onClose)})})},"ToastClose")),$k=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),Zg(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 Xg=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 Qg(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(Qg,"useNextFrame");function Zg(e){return e.nodeType===e.ELEMENT_NODE}qe(Zg,"isHTMLElement");function ev(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(ev,"getTabbableCandidates");function ks(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}qe(ks,"focusFirst");var Lk=vk,jk=_k,Ok=Pk,Mk=Ak,Fk=Dk,jo=yd([]),Bk=1;function Uk(e,t="success",n=8e3){if(!e)return;const r=Bk++;jo.value=[...jo.value,{id:r,message:e,variant:t,durationMs:n}]}function qk(e){jo.value=jo.value.filter(t=>t.id!==e)}function Gk(){const e=jo.value;return a(Lk,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(Ok,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||qk(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(Mk,{className:"toast-message",children:t.message}),a(Fk,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(jk,{className:"toast-viewport"})]})}function Hk(e){We(a(Gk,{}),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 tv(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Kk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vk(e,t){const n=t.trim();if(!n)return tv(e);const r=tv(e);try{const i=new RegExp(`(${Kk(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 zk=new Set(["BUTTON","A","SELECT"]),Wk=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function Jk(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function Yk(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function Xk(e){return e?zk.has(e.tagName)?!0:e instanceof HTMLInputElement&&Wk.has(e.type):!1}function Qk(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(!Jk(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}Xk(n)||Yk(n)&&!Qk(e)||(e.preventDefault(),t.onSubmit())}}var Er=["feed","projects","sharing","devices","health","advanced"],nv=["sync","coordinator-admin"],Ad="codemem-tab",rv="codemem-advanced-section",iv="codemem-feed-filter",ov="codemem-feed-scope",Zk="codemem-sync-diagnostics",av="codemem-sync-pairing",sv="codemem-sync-redact",cv=["all","observations","summaries"],lv=["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 eT(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 nv.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 tT(){const e=xd();if(e)return Mo(e,C.lastCoordinatorAdminStatus);const t=localStorage.getItem(Ad);return t&&(Er.includes(t)||nv.includes(t))?Mo(t,C.lastCoordinatorAdminStatus):"feed"}function nT(){const e=Dd();if(e)return e;const t=localStorage.getItem(Ad);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(rv)==="teams"?"teams":"sync"}function $d(e,t=!1){C.advancedSection=e,localStorage.setItem(rv,e),t&&(window.location.hash=`advanced/${e}`)}function dv(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 rT(){const e=localStorage.getItem(iv)||"all";return cv.includes(e)?e:"all"}function iT(){const e=localStorage.getItem(ov)||"all";return lv.includes(e)?e:"all"}function oT(e){C.feedTypeFilter=cv.includes(e)?e:"all",localStorage.setItem(iv,C.feedTypeFilter)}function uv(e){C.feedScopeFilter=lv.includes(e)?e:"all",localStorage.setItem(ov,C.feedScopeFilter)}function aT(){return localStorage.getItem(Zk)==="1"}function sT(e){C.syncPairingOpen=e;try{localStorage.setItem(av,e?"1":"0")}catch{}}function Fo(){return localStorage.getItem(sv)!=="0"}function cT(e){localStorage.setItem(sv,e?"1":"0")}function lT(){C.activeTab=tT(),C.advancedSection=nT(),C.feedTypeFilter=rT(),C.feedScopeFilter=iT(),C.syncDiagnosticsOpen=aT();try{C.syncPairingOpen=localStorage.getItem(av)==="1"}catch{C.syncPairingOpen=!1}}var Ld=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],pv="codemem-theme";function fv(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(pv);return e?fv(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function mv(e){const t=fv(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(pv,t.id)}function dT(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";mv(n),t(n)})}var uT=Object.defineProperty,pT=(e,t)=>uT(e,"name",{value:t,configurable:!0}),fT=wr(void 0);function Ei(e){const t=Cn(fT);return e||t||"ltr"}pT(Ei,"useDirection");var mT=Object.defineProperty,Od=(e,t)=>mT(e,"name",{value:t,configurable:!0}),Md=!1;function hv(){const[e,t]=x(Md);return K(()=>{Md||(Md=!0,t(!0))},[]),e}Od(hv,"useIsHydrated");var gv=pi[" useSyncExternalStore ".trim().toString()];function vv(){return()=>{}}Od(vv,"subscribe");function yv(){return gv(vv,()=>!0,()=>!1)}Od(yv,"useIsHydratedModern");var hT=typeof gv=="function"?yv:hv,gT=Object.defineProperty,Ar=(e,t)=>gT(e,"name",{value:t,configurable:!0}),Fd="rovingFocusGroup.onEntryFocus",vT={bubbles:!1,cancelable:!0},Ns="RovingFocusGroup",[Bd,bv,yT]=$o(Ns),[bT,Ai]=lt(Ns,[yT]),[_T,wT]=bT(Ns),ST=J(Ar(function(t,n){return a(Bd.Provider,{scope:t.__scopeRovingFocusGroup,children:a(Bd.Slot,{scope:t.__scopeRovingFocusGroup,children:a(CT,{...t,ref:n})})})},"RovingFocusGroup")),CT=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]=At({prop:c,defaultProp:l??null,onChange:d,caller:Ns}),[w,_]=x(!1),I=mt(u),R=bv(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(_T,{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,vT);if(F.currentTarget.dispatchEvent(M),!M.defaultPrevented){const j=R().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")),IT="RovingFocusGroupItem",RT=J(Ar(function(t,n){const{__scopeRovingFocusGroup:r,focusable:i=!0,active:o=!1,tabStopId:s,children:c,...l}=t,d=Et(),u=s||d,p=wT(IT,r),f=p.currentTabStopId===u,m=bv(r),{onFocusableItemAdd:v,onFocusableItemRemove:g,currentTabStopId:h}=p,y=hT();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 _=wv(w,p.orientation,p.dir);if(_!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let I=m().filter(R=>R.focusable).map(R=>R.ref.current);if(_==="last")I.reverse();else if(_==="prev"||_==="next"){_==="prev"&&I.reverse();const R=I.indexOf(w.currentTarget);I=p.loop?Sv(I,R+1):I.slice(R+1)}setTimeout(()=>Ud(I))}}),children:typeof c=="function"?c({isCurrentTabStop:f,hasTabStop:h!=null}):c})})},"RovingFocusGroupItem")),PT={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function _v(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Ar(_v,"getDirectionAwareKey");function wv(e,t,n){const r=_v(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return PT[r]}Ar(wv,"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 Sv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Ar(Sv,"wrapArray");var qd=ST,Gd=RT,kT=Object.defineProperty,xi=(e,t)=>kT(e,"name",{value:t,configurable:!0}),Hd="Tabs",[TT,NU]=lt(Hd,[Ai]),Cv=Ai(),[NT,Kd]=TT(Hd),ET=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]=At({prop:i,onChange:o,defaultProp:s??"",caller:Hd});return a(NT,{scope:r,baseId:Et(),value:f,onValueChange:m,orientation:c,dir:p,activationMode:d,children:a(ve.div,{dir:p,"data-orientation":c,...u,ref:n})})},"Tabs")),AT="TabsList",xT=J(xi(function(t,n){const{__scopeTabs:r,loop:i=!0,...o}=t,s=Kd(AT,r),c=Cv(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")),DT="TabsTrigger",$T=J(xi(function(t,n){const{__scopeTabs:r,value:i,disabled:o=!1,...s}=t,c=Kd(DT,r),l=Cv(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")),LT="TabsContent",jT=J(xi(function(t,n){const{__scopeTabs:r,value:i,forceMount:o,children:s,...c}=t,l=Kd(LT,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(Rt,{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 OT=ET,MT=xT,FT=$T,BT=jT;function Iv({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(OT,{onValueChange:r,value:s,children:[a(MT,{"aria-label":e,className:n,children:i.map(c=>a(FT,{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(BT,{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 Rv(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=Rv(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 UT(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 qT(){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 kv(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 GT="codemem-coordinator-admin-target-group",N={recovery:qT(),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 Tv(){return N.loadGeneration+=1,N.loadGeneration}function Yd(e){return N.loadGeneration===e}function HT(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=UT(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 KT=Object.defineProperty,Uo=(e,t)=>KT(e,"name",{value:t,configurable:!0}),Xd="Collapsible",[VT,EU]=lt(Xd),[zT,Qd]=VT(Xd),WT=J(Uo(function(t,n){const{__scopeCollapsible:r,open:i,defaultOpen:o,disabled:s,onOpenChange:c,...l}=t,[d,u]=At({prop:i,defaultProp:o??!1,onChange:c,caller:Xd});return a(zT,{scope:r,disabled:s,contentId:Et(),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")),JT="CollapsibleTrigger",YT=J(Uo(function(t,n){const{__scopeCollapsible:r,...i}=t,o=Qd(JT,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")),Nv="CollapsibleContent",XT=J(Uo(function(t,n){const{forceMount:r,...i}=t,o=Qd(Nv,t.__scopeCollapsible);return a(Rt,{present:r||o.open,children:({present:s})=>a(QT,{...i,ref:n,present:s})})},"CollapsibleContent")),QT=J(Uo(function(t,n){const{__scopeCollapsible:r,present:i,children:o,...s}=t,c=Qd(Nv,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=WT,Zd=YT,Go=XT,ZT=["top","right","bottom","left"],Yn=Math.min,xt=Math.max,Ls=Math.round,js=Math.floor,ln=e=>({x:e,y:e}),eN={left:"right",right:"left",bottom:"top",top:"bottom"};function eu(e,t,n){return xt(e,Yn(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 tN(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 nN(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 Ev=["left","right"],Av=["right","left"],rN=["top","bottom"],iN=["bottom","top"];function oN(e,t,n){switch(e){case"top":case"bottom":return n?t?Av:Ev:t?Ev:Av;case"left":case"right":return t?rN:iN;default:return[]}}function aN(e,t,n,r){const i=$i(e);let o=oN(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 eN[t]+e.slice(t.length)}function sN(e){return{top:0,right:0,bottom:0,left:0,...e}}function xv(e){return typeof e!="number"?sN(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 Dv(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 cN(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=xv(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 lN=50,dN=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:cN},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}=Dv(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:R,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],...R},k&&m<lN&&(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}=Dv(d,f,l)),g=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},uN=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=xv(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],R=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-R/2,F=A/2-g[v]/2-1,T=Yn(p[y],F),M=Yn(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}}}),pN=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)),R=f||(_||!g?[Os(c)]:nN(c)),k=v!=="none";!f&&k&&R.push(...aN(c,g,v,I));const A=[c,...R],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=tN(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 $v(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Lv(e){return ZT.some(t=>e[t]>=0)}var fN=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=$v(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:Lv(s)}}}case"escaped":{const s=$v(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:Lv(s)}}}default:return{}}}}},jv=new Set(["left","top"]);async function mN(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=jv.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 hN=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 mN(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}}}}},gN=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}}}}}},vN=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,R=o.reference[f]+o.reference[_]-h.mainAxis;m<I?m=I:m>R&&(m=R)}if(d){var y,w;const _=f==="y"?"width":"height",I=jv.has(En(i)),R=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<R?v=R:v>k&&(v=k)}return{[f]:m,[p]:v}}}},yN=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=Yn(g-u[h],w),R=Yn(v-u[y],_),k=!t.middlewareData.shift;let A=I,L=R;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),k&&!f){const T=xt(u.left,0),M=xt(u.right,0),j=xt(u.top,0),B=xt(u.bottom,0);m?L=v-2*(T!==0||M!==0?T+M:xt(u.left,u.right)):A=g-2*(j!==0||B!==0?j+B:xt(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 Ov(e)?(e.nodeName||"").toLowerCase():"#document"}function Dt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function un(e){var t;return(t=(Ov(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ov(e){return Fs()?e instanceof Node||e instanceof Dt(e).Node:!1}function zt(e){return Fs()?e instanceof Element||e instanceof Dt(e).Element:!1}function An(e){return Fs()?e instanceof HTMLElement||e instanceof Dt(e).HTMLElement:!1}function Mv(e){return!Fs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Dt(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 bN(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 _N=/transform|translate|scale|rotate|perspective|filter/,wN=/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))||_N.test(t.willChange||"")||wN.test(t.contain||"")}function SN(e){let t=Xn(e);for(;An(t)&&!ji(t);){if(au(t))return t;if(Bs(t))return null;t=Xn(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 Dt(e).getComputedStyle(e)}function Us(e){return zt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Xn(e){if(Li(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Mv(e)&&e.host||un(e);return Mv(t)?t.host:t}function Fv(e){const t=Xn(e);return ji(t)?e.ownerDocument?e.ownerDocument.body:e.body:An(t)&&Ho(t)?t:Fv(t)}function Ko(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Fv(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=Dt(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 Bv(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}=Bv(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 CN=ln(0);function Uv(e){const t=Dt(e);return!su()||!t.visualViewport?CN:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function IN(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Dt(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=IN(o,n,r)?Uv(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=Dt(o),m=r&&zt(r)?Dt(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=Dt(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 qv(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-qs(e,n),y:n.top+t.scrollTop}}function RN(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?qv(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 PN(e){return Array.from(e.getClientRects())}function kN(e){const t=un(e),n=Us(e),r=e.ownerDocument.body,i=xt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=xt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+qs(e);const c=-n.scrollTop;return Wt(r).direction==="rtl"&&(s+=xt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var Gv=25;function TN(e,t){const n=Dt(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<=Gv&&(o-=v)}else d<=Gv&&(o+=d);return{width:o,height:s,x:c,y:l}}function NN(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 Hv(e,t,n){let r;if(t==="viewport")r=TN(e,n);else if(t==="document")r=kN(un(e));else if(zt(t))r=NN(t,n);else{const i=Uv(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Ms(r)}function Kv(e,t){const n=Xn(e);return n===t||!zt(n)||ji(n)?!1:Wt(n).position==="fixed"||Kv(n,t)}function EN(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?Xn(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&&Kv(e,s))?r=r.filter(d=>d!==s):i=c,s=Xn(s)}return t.set(e,r),r}function AN(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Bs(t)?[]:EN(t,this._c):[].concat(n),r],s=Hv(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=Hv(t,o[p],i);c=xt(f.top,c),l=Yn(f.right,l),d=Yn(f.bottom,d),u=xt(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function xN(e){const{width:t,height:n}=Bv(e);return{width:t,height:n}}function DN(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?qv(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 Vv(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 zv(e,t){const n=Dt(e);if(Bs(e))return n;if(!An(e)){let i=Xn(e);for(;i&&!ji(i);){if(zt(i)&&!du(i))return i;i=Xn(i)}return n}let r=Vv(e,t);for(;r&&bN(r)&&du(r);)r=Vv(r,t);return r&&ji(r)&&du(r)&&!au(r)?n:r||SN(e)||n}var $N=async function(e){const t=this.getOffsetParent||zv,n=this.getDimensions,r=await n(e.floating);return{reference:DN(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function LN(e){return Wt(e).direction==="rtl"}var jN={convertOffsetParentRelativeRectToViewportRelativeRect:RN,getDocumentElement:un,getClippingRect:AN,getOffsetParent:zv,getElementRects:$N,getClientRects:PN,getDimensions:xN,getScale:Oi,isElement:zt,isRTL:LN};function Wv(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ON(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:xt(0,Yn(1,l))||1};let _=!0;function I(R){const k=R[0].intersectionRatio;if(k!==l){if(!_)return s();k?s(!1,k):r=setTimeout(()=>{s(!1,1e-7)},1e3)}k===1&&!Wv(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 MN(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?ON(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&&!Wv(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 FN=hN,BN=gN,UN=pN,qN=yN,GN=fN,Jv=uN,HN=vN,KN=(e,t,n)=>{const r=new Map,i={platform:jN,...n},o={...i.platform,_c:r};return dN(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 Yv(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Xv(e,t){const n=Yv(e);return Math.round(t*n)/n}function uu(e){const t=q(e);return Gs(()=>{t.current=e}),t}function VN(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,R=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),KN(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),R&&(A.current=R),I&&R){if(T.current)return T.current(I,R,B);B()}},[I,R,B,T,F]);const $=Pe(()=>({reference:k,floating:A,setReference:w,setFloating:_}),[w,_]),E=Pe(()=>({reference:I,floating:R}),[I,R]),S=Pe(()=>{const D={position:n,left:0,top:0};if(!E.floating)return D;const H=Xv(E.floating,u.x),G=Xv(E.floating,u.y);return c?{...D,transform:"translate("+H+"px, "+G+"px)",...Yv(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:G}},[n,c,E.floating,u.x,u.y]);return Pe(()=>({...u,update:B,refs:$,elements:E,floatingStyles:S}),[u,B,$,E,S])}var zN=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?Jv({element:r.current,padding:i}).fn(n):{}:r?Jv({element:r,padding:i}).fn(n):{}}}},WN=(e,t)=>{const n=FN(e);return{name:n.name,fn:n.fn,options:[e,t]}},JN=(e,t)=>{const n=BN(e);return{name:n.name,fn:n.fn,options:[e,t]}},YN=(e,t)=>({fn:HN(e).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=qN(e);return{name:n.name,fn:n.fn,options:[e,t]}},ZN=(e,t)=>{const n=GN(e);return{name:n.name,fn:n.fn,options:[e,t]}},eE=(e,t)=>{const n=zN(e);return{name:n.name,fn:n.fn,options:[e,t]}},tE=Object.defineProperty,nE=(e,t)=>tE(e,"name",{value:t,configurable:!0}),rE=J(nE(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")),iE=rE,oE=Object.defineProperty,aE=(e,t)=>oE(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}aE(Ks,"useSize");var sE=Object.defineProperty,xn=(e,t)=>sE(e,"name",{value:t,configurable:!0}),Qv="Popper",[Zv,Qn]=lt(Qv),[cE,ey]=Zv(Qv),lE=xn(e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null),[o,s]=x(void 0);return a(cE,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:s,children:n})},"Popper"),dE="PopperAnchor",uE=J(xn(function(t,n){const{__scopePopper:r,virtualRef:i,...o}=t,s=ey(dE,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")),ty="PopperContent",[pE,fE]=Zv(ty),mE=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=ey(ty,r),[w,_]=x(null),I=Se(n,_),[R,k]=x(null),A=Ks(R),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(ny),altBoundary:B},{refs:$,floatingStyles:E,placement:S,isPositioned:D,middlewareData:H}=VN({strategy:"fixed",placement:T,whileElementsMounted:xn((...ye)=>MN(...ye,{animationFrame:v==="always"}),"whileElementsMounted"),elements:{reference:y.anchor},middleware:[WN({mainAxis:o+F,alignmentAxis:c}),d&&JN({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?YN():void 0,...U}),d&&XN({...U}),QN({...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")}),R&&eE({element:R,padding:l}),yE({arrowWidth:L,arrowHeight:F}),m&&ZN({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(pE,{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")),hE="PopperArrow",gE={top:"bottom",right:"left",bottom:"top",left:"right"},vE=J(xn(function(t,n){const{__scopePopper:r,...i}=t,o=fE(hE,r),s=gE[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(iE,{...i,ref:n,style:{...i.style,display:"block"}})})},"PopperArrow"));function ny(e){return e!==null}xn(ny,"isNotNull");var yE=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=lE,Vo=uE,Ws=mE,bE=vE,_E=Object.defineProperty,Dn=(e,t)=>_E(e,"name",{value:t,configurable:!0}),pu="Popover",[ry,AU]=lt(pu,[Qn]),Js=Qn(),[wE,jr]=ry(pu),SE=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]=At({prop:r,defaultProp:i??!1,onChange:o,caller:pu});return a(zs,{...c,children:a(wE,{scope:t,contentId:Et(),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"),CE="PopoverAnchor",IE=J(Dn(function(t,n){const{__scopePopover:r,...i}=t,o=jr(CE,r),s=Js(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:l}=o;return K(()=>(c(),()=>l()),[c,l]),a(Vo,{...s,...i,ref:n})},"PopoverAnchor")),RE="PopoverTrigger",PE=J(Dn(function(t,n){const{__scopePopover:r,...i}=t,o=jr(RE,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")),iy="PopoverPortal",[kE,TE]=ry(iy,{forceMount:void 0}),NE=Dn(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=jr(iy,t);return a(kE,{scope:t,forceMount:n,children:a(Rt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),zo="PopoverContent",EE=J(Dn(function(t,n){const r=TE(zo,t.__scopePopover),{forceMount:i=r.forceMount,...o}=t,s=jr(zo,t.__scopePopover);return a(Rt,{present:i||s.open,children:s.modal?a(xE,{...o,ref:n}):a(DE,{...o,ref:n})})},"PopoverContent")),AE=on("PopoverContent.RemoveScroll"),xE=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:AE,allowPinchZoom:!0,children:a(oy,{...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")),DE=J(Dn(function(t,n){const r=jr(zo,t.__scopePopover),i=q(!1),o=q(!1);return a(oy,{...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")),oy=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 ay=SE,$E=IE,LE=PE,sy=NE,cy=EE;function mu(e){return e.trim()}function ly({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=Pe(()=>{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=Pe(()=>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 R=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&&R(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(ay,{onOpenChange:T=>{l(T),T||(u(""),f(0))},open:c,children:[a(LE,{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(sy,{children:a(cy,{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),R(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 jE=Object.defineProperty,Zn=(e,t)=>jE(e,"name",{value:t,configurable:!0}),hu="Switch",[OE,xU]=lt(hu),[ME,gu]=OE(hu);function dy(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]=At({prop:n,defaultProp:i??!1,onChange:l,caller:hu}),[v,g]=x(null),[h,y]=x(null),w=q(!1),[_,I]=Wn(k=>k+1,0),R={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(ME,{scope:t,...R,children:uy(p)?p(R):r})}Zn(dy,"SwitchProvider");var FE="SwitchTrigger",BE=J(Zn(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(FE,t),y=Se(i,p),w=q(d);return K(()=>{const _=s?o?.ownerDocument.getElementById(s):o?.form;if(_ instanceof HTMLFormElement){const I=Zn(()=>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")),UE=J(Zn(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(dy,{__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(BE,{...f,ref:n,__scopeSwitch:r}),m&&a(KE,{__scopeSwitch:r})]})})},"Switch")),qE="SwitchThumb",GE=J(Zn(function(t,n){const{__scopeSwitch:r,...i}=t,o=gu(qE,r);return a(ve.span,{"data-state":vu(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n})},"SwitchThumb")),HE="SwitchBubbleInput",KE=J(Zn(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(HE,t),y=Se(i,h),w=Ks(o),_=q(!1),I=q(l),R=q(c);K(()=>{const A=g;if(!A)return;const L=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(L,"checked").set,T=c!==R.current;R.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 uy(e){return typeof e=="function"}Zn(uy,"isFunction");function vu(e){return e?"checked":"unchecked"}Zn(vu,"getState");function Mi({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a(UE,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(GE,{className:c})})}function Q(e,t="success"){Uk(e,t)}function $n(e){return String(e||"").trim().replace(/\/+$/u,"")}function py(e){return`${GT}:${$n(e)}`}function VE(e){try{return localStorage.getItem(py(e))||""}catch{return""}}function zE(e,t){try{localStorage.setItem(py(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()||er()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function $t(e){const t=Ys();return!!(e&&t&&$n(e.coordinatorUrl)===$n(t.coordinatorUrl)&&e.groupId===t.groupId)}function yu(e){C.coordinatorAdminTargetGroup=e,zE(C.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function er(){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=er(),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 WE(){const e=new Map;for(const t of er())e.set(t.group_id,t.display_name||"");N.groupRenameDrafts.clear();for(const[t,n]of e.entries())N.groupRenameDrafts.set(t,n)}function JE(){const e=Ln();return er().find(t=>t.group_id===e)||null}function fy(){const e=C.lastCoordinatorAdminStatus,t=er(),n=String(e?.active_group||"").trim(),r=VE(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 YE(){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 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 legacy group 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 legacy group defaults to inspect"}function eA(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function tA(e){const t=eA(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function nA(e){const t=XE(e.groupId,e.setupGuide);return{autoGrant:ZE(e.preferences,t),defaultSpace:QE(e.preferences,t),spaces:tA(e.scopeManagement)}}var _u=null,Xs=null,wu=null;function rA(){return _u}function Su(e){Xs=e}function my(e){wu=e}function iA(e){return wu===e}function oA(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 tr(e){const t=Xs;Xs=null,Qs(null),t?.(e)}function aA(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var sA=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=Pe(()=>{const R=t.trim().toLowerCase();return(R?r.filter(k=>k.toLowerCase().includes(R)):r).slice(0,o)},[t,r,o]);K(()=>{g>=y.length&&h(y.length-1)},[y.length,g]);const w=m&&y.length>0,_=R=>{n(R),v(!1),h(-1),f.current?.focus()};return a(ay,{open:w,onOpenChange:v,children:[a($E,{asChild:!0,children:a("input",{...u,ref:f,className:d,value:t,onInput:R=>{n(R.currentTarget.value),v(!0),h(-1)},onFocus:R=>{c?.(R)},onBlur:R=>{window.setTimeout(()=>v(!1),120),l?.(R)},onKeyDown:R=>{if(R.key==="ArrowDown"){R.preventDefault(),v(!0),h(k=>y.length===0?-1:Math.min(k+1,y.length-1));return}if(R.key==="ArrowUp"){R.preventDefault(),m||v(!0),h(k=>Math.max(k-1,-1));return}if(R.key==="Escape"&&w){R.preventDefault(),v(!1),h(-1);return}if((R.key==="Tab"||R.key==="Enter")&&g>=0){const k=y[g];if(k){R.preventDefault(),_(k);return}}if(R.key==="Enter"&&i){R.preventDefault(),i();return}s?.(R)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":g>=0?`autocomplete-option-${g}`:void 0})}),a(sy,{children:a(cy,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:R=>R.preventDefault(),onCloseAutoFocus:R=>R.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:y.map((R,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(),_(R)},onMouseEnter:()=>h(k),role:"option",tabIndex:-1,children:R},R)})})})})]})}),cA=Object.defineProperty,ht=(e,t)=>cA(e,"name",{value:t,configurable:!0}),hy="Radio",[lA,gy]=lt(hy),[dA,Zs]=lA(hy);function vy(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]=Wn(_=>_+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(dA,{scope:t,...w,children:yy(u)?u(w):r})}ht(vy,"RadioProvider");var uA="RadioTrigger",pA=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(uA,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")),fA="RadioIndicator",mA=J(ht(function(t,n){const{__scopeRadio:r,forceMount:i,...o}=t,s=Zs(fA,r);return a(Rt,{present:i||s.checked,children:a(ve.span,{"data-state":Iu(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:n})})},"RadioIndicator")),hA="RadioBubbleInput",gA=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(hA,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 R=q(s);return a(ve.input,{type:"radio","aria-hidden":!0,defaultChecked:R.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 yy(e){return typeof e=="function"}ht(yy,"isFunction");function Iu(e){return e?"checked":"unchecked"}ht(Iu,"getState");var vA=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ru="RadioGroup",[yA,DU]=lt(Ru,[Ai,gy]),by=Ai(),ec=gy(),[bA,_A]=yA(Ru),wA=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=by(r),h=Ei(p),[y,w]=At({prop:c,defaultProp:s??null,onChange:m,caller:Ru}),[_,I]=x(null),R=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(bA,{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:R})})})},"RadioGroup")),SA="RadioGroupItemProvider",CA="RadioGroupItemTrigger";function _y(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:i,internal_do_not_use_render:o}=e,s=_A(SA,t),c=ec(t),l=s.disabled||r;return a(vy,{...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(_y,"RadioGroupItemProvider");var IA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=by(r),s=ec(r),{checked:c,disabled:l}=Zs(CA,s.__scopeRadio),d=q(null),u=Se(n,d),p=q(!1);return K(()=>{const f=ht(v=>{vA.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(pA,{...s,...i,ref:u,onKeyDown:ne(i.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:ne(i.onFocus,()=>{p.current&&d.current?.click()})})})},"RadioGroupItemTrigger")),RA=J(ht(function(t,n){const{__scopeRadioGroup:r,value:i,disabled:o,...s}=t;return a(_y,{__scopeRadioGroup:r,value:i,disabled:o,internal_do_not_use_render:({isFormControl:c})=>a(z,{children:[a(IA,{...s,ref:n,__scopeRadioGroup:r}),c&&a(PA,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),PA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=ec(r);return a(gA,{...o,...i,ref:n})},"RadioGroupItemBubbleInput")),kA=J(ht(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=ec(r);return a(mA,{...o,...i,ref:n})},"RadioGroupIndicator"));function TA({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(wA,{"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(RA,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(kA,{className:r})}),a("span",{className:o,id:v,children:p.label})]},p.value)})})}var NA=Object.defineProperty,EA=(e,t)=>NA(e,"name",{value:t,configurable:!0});function Pu(e,[t,n]){return Math.min(n,Math.max(t,e))}EA(Pu,"clamp");var AA=Object.defineProperty,xA=(e,t)=>AA(e,"name",{value:t,configurable:!0});function wy(e){const t=q({value:e,previous:e});return Pe(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}xA(wy,"usePrevious");var DA=Object.defineProperty,Me=(e,t)=>DA(e,"name",{value:t,configurable:!0}),$A=[" ","Enter","ArrowUp","ArrowDown"],LA=[" ","Enter"],Fi="Select",[tc,ku,jA]=$o(Fi),[Or,$U]=lt(Fi,[jA,Qn]),Tu=Qn(),[OA,nr]=Or(Fi),[MA,FA]=Or(Fi);function Sy(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),[R,k]=x(!1),A=Ei(d),[L,F]=At({prop:r,defaultProp:i??!1,onChange:o,caller:Fi}),[T,M]=At({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=Et(),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:R,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(OA,{scope:t,...oe,children:a(tc.Provider,{scope:t,children:a(MA,{scope:t,onNativeOptionAdd:H,onNativeOptionRemove:G,children:ky(g)?g(oe):n})})})})}Me(Sy,"SelectProvider");var BA=Me(e=>{const{__scopeSelect:t,children:n,...r}=e;return a(Sy,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:i})=>a(z,{children:[n,i?a(lx,{__scopeSelect:t}):null]})})},"Select"),UA="SelectTrigger",qA=J(Me(function(t,n){const{__scopeSelect:r,disabled:i=!1,...o}=t,s=Tu(r),c=nr(UA,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===" ")&&$A.includes(h.key)&&(g(),h.preventDefault())})})})},"SelectTrigger")),GA="SelectValue",HA=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,children:s,placeholder:c="",...l}=t,d=nr(GA,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")),KA=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")),[VA,zA]=Or("SelectPortal",{forceMount:void 0}),WA=Me(e=>{const{__scopeSelect:t,forceMount:n,...r}=e;return a(VA,{scope:e.__scopeSelect,forceMount:n,children:a(gi,{asChild:!0,...r})})},"SelectPortal"),Mr="SelectContent",JA=J(Me(function(t,n){const r=zA(Mr,t.__scopeSelect),{forceMount:i=r.forceMount,...o}=t,s=nr(Mr,t.__scopeSelect),[c,l]=x();return Xe(()=>{l(new DocumentFragment)},[]),a(Rt,{present:i||s.open,children:({present:d})=>d?a(QA,{...o,ref:n}):a(YA,{...o,fragment:c})})},"SelectContent")),YA=J(Me(function(t,n){const{__scopeSelect:r,children:i,fragment:o}=t;return o?rn(a(Cy,{scope:r,children:a(tc.Slot,{scope:r,children:a("div",{ref:n,children:i})})}),o):null},"SelectContentFragment")),Jt=10,[Cy,nc]=Or(Mr),XA=on("SelectContent.RemoveScroll"),QA=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,_=nr(Mr,r),[I,R]=x(null),[k,A]=x(null),L=Se(n,R),[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"?Iy:ZA,Ne=Ie===Iy?{side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:y}:{};return a(Cy,{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:XA,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")),ZA=J(Me(function(t,n){const{__scopeSelect:r,onPlaced:i,...o}=t,s=nr(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,Re=Pu(ge,[Jt,Math.max(Jt,W-de)]);l.style.minWidth=He+"px",l.style.left=Re+"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,Re=Pu(ge,[Jt,Math.max(Jt,W-de)]);l.style.minWidth=He+"px",l.style.right=Re+"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[R,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(ex,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:v,onScrollButtonChange:A,children:a("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R},children:a(ve.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})},"SelectItemAlignedPosition")),Iy=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")),[ex,tx]=Or(Mr,{}),Ry="SelectViewport",nx=J(Me(function(t,n){const{__scopeSelect:r,nonce:i,...o}=t,s=nc(Ry,r),c=tx(Ry,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,_),R=_-I;f.style.height=I+"px",f.style.bottom==="0px"&&(p.scrollTop=R>0?R:0,f.style.justifyContent="flex-end")}}}d.current=p.scrollTop})})})]})},"SelectViewport")),[LU,jU]=Or("SelectGroup"),Nu="SelectItem",[rx,Py]=Or(Nu),ix=J(Me(function(t,n){const{__scopeSelect:r,value:i,disabled:o=!1,textValue:s,...c}=t,l=nr(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=Et(),w=q("touch"),_=Me(()=>{o||(l.onValueChange(i),l.onOpenChange(!1))},"handleSelect");return a(rx,{scope:r,value:i,disabled:o,textId:y,isSelected:u,onItemTextChange:se(I=>{f(R=>R||(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===" "||(LA.includes(I.key)&&_(),I.key===" "&&I.preventDefault())})})})})},"SelectItem")),rc="SelectItemText",ox=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,...s}=t,c=nr(rc,r),l=nc(rc,r),d=Py(rc,r),u=FA(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=Pe(()=>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")),ax="SelectItemIndicator",sx=J(Me(function(t,n){const{__scopeSelect:r,...i}=t;return Py(ax,r).isSelected?a(ve.span,{"aria-hidden":!0,...i,ref:n}):null},"SelectItemIndicator")),cx="SelectBubbleInput",lx=J(Me(function({__scopeSelect:t,...n},r){const i=nr(cx,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=wy(h),w=Array.from(f).some(_=>(_.props.value??"")==="");return K(()=>{const _=v.current;if(!_)return;const I=window.HTMLSelectElement.prototype,R=Object.getOwnPropertyDescriptor(I,"value").set;if(y!==h&&R){const k=new Event("change",{bubbles:!0});R.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:{...Vg,...n.style},ref:g,defaultValue:h,children:[Wo(o)&&!w?a("option",{value:""}):null,Array.from(f)]},m)},"SelectBubbleInput"));function ky(e){return typeof e=="function"}Me(ky,"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=Ty(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 Ty(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Me(Ty,"wrapArray");var Ny="__codemem-empty-select__";function dx(){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 ux(){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===""?Ny:e}function px(e){return e===Ny?"":e}function rr({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(BA,{disabled:r,onValueChange:m=>s(px(m)),value:f,children:[a(qA,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(HA,{placeholder:l}),a(KA,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(dx,{})})]}),a(WA,{children:a(JA,{className:n,position:"popper",children:a(nx,{className:p,children:c.map(m=>a(ix,{className:o,disabled:m.disabled,value:xu(m.value),children:[a(ox,{children:m.label}),a(sx,{className:"sync-radix-select-indicator",children:a(ux,{})})]},xu(m.value)))})})})]})}function fx({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||tr({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:()=>tr({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>tr({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(TA,{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(rr,{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 mx({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"){tr(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}tr(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:()=>tr(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(sA,{"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(fx,{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:()=>tr(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${aA(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function hx(){const[e,t]=x(rA());K(()=>(my(t),()=>{iA(t)&&my(null)}),[]);const n=!!e,r=Pe(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Pe(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(Pr,{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||tr(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(mx,{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(hx,{}),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 gx(e){return ic(),Cu("duplicate-person")?new Promise(t=>{Su(n=>t(n||{action:"cancel"})),Qs({kind:"duplicate-person",...e})}):Promise.resolve(oA({kind:"duplicate-person",...e}))}function vx(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 yx(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Ey(e){const t=String(e.label||"").trim()||"Untitled Space",n=yx(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 bx(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 _x(e,t,n){return`Revoke ${t||"this device"} from ${Ey(e).title}?`}function wx(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 Sx(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 OU=8;function Cx(){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=Cx(),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 Ix(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([MS(e,n),Hf(e,!0)]);if(!o())return;const u=oc(l),p=oc(d),f=await Ix(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 Gf(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 Ay(e,t){N.groupScopeManagementOpen.delete(e),t()}async function Rx(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 Gf(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 Px(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 FS(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 kx(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 BS(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 Tx(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:_x(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 US(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 Nx(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=$t(N.devicesSnapshotTarget)?C.lastCoordinatorAdminDevices:[],c=Sx(n.devices,s,e,n.devicesLoaded),l=wx(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=bx(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:()=>{kx(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:()=>{Tx(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 Ex(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=Ey(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:()=>{Rx(e,o,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:Nx(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 Ax(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=N.groupScopeManagementDrafts.get(t);if(!o)return null;const s=vx(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&&Px(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=>Ex(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 xy(){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 xx(){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 Dy(e,t){const n=N.groupPreferencesDrafts.get(e)??xx(),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 VC(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 Dy(e,t)}function ac(e,t){N.groupPreferencesOpen.delete(e),t()}function $y(e,t){const n=N.groupPreferencesDrafts.get(e);n&&(N.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),Dy(e,t))}async function Dx(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 zC(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 $x(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:()=>$y(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:()=>$y(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(ly,{"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(ly,{"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:()=>{Dx(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 Lx(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 jx(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function Ox(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=er(),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,Lx(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,R=N.groupRenameDrafts.get(y.group_id)??y.display_name??"",k=R.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=jx(I,_&&N.groupActionPendingKind===F),M=nA({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:R})),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,R,"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(xy,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?Ay(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(xy,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?$x(y.group_id,o,n):null)),b(qo,{open:L,onOpenChange:j=>{j?Lu(y.group_id,o):Ay(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?Ax({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 Mx(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(rr,{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 Fx(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 Bx=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 Ux(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 qx(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function Gx(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function Hx(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function Kx(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 $S({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(!$t(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 LS(d,y),p==="archive"&&await jS(d),p==="unarchive"&&await OS(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(Gx(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 Kf({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(Ux(v),"warning")}finally{N.invitePending=!1,t()}}async function c(d,u){if(!$t(N.joinRequestsSnapshotTarget)||!r("status","joinRequests")||N.joinReviewPendingId)return;const p=N.joinRequestsSnapshotTarget;N.joinReviewPendingId=d,N.joinReviewPendingAction=u,t();try{const f=await GS(d,u);if(!$t(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(!$t(p))return;if(qx(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($t(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(!$t(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 HS(d,u,v)}f==="disable"&&await KS(d,u),f==="enable"&&await VS(d,u),f==="remove"&&await zS(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?Bx.get(m.message.trim()):void 0;if(Hx(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 Vx(){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 zx(){const e=Tv();return Bo(N.recovery,"status"),Wd(N.recovery,"groups"),Wd(N.recovery,"joinRequests"),Wd(N.recovery,"devices"),e}async function Ly(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)&&Vx(),C.lastCoordinatorAdminStatus=t,Ds(N.recovery,"status"),"fresh"}catch{return Yd(e)?(cn(N.recovery,"status"),"failed"):"superseded"}}function Wx(){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:Jx,runGroupAction:Yx,createInviteFromAdminPanel:Xx,reviewJoinRequestFromAdminPanel:Qx,runDeviceAction:Zx}=Kx({renderShell:()=>Ur(),reloadData:()=>sc()});function Ur(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=C.lastCoordinatorAdminStatus,n=Wx(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!JE()?.archived_at,c=Tn(N.recovery,"status","groups"),l=c&&!s,d=$t(N.joinRequestsSnapshotTarget),u=$t(N.devicesSnapshotTarget),p=Tn(N.recovery,"status","joinRequests")&&d,f=Tn(N.recovery,"status","devices")&&u,m=Ln(),v=er().filter(M=>!M.archived_at).length,g=er().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.":"",_=kv(N.recovery),I=Dr(N.recovery,"status"),R=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||R?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,R?`${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(Iv,{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},Ox({summary:n,fresh:c,createGroup:()=>{Jx()},runGroup:(M,j,B)=>{Yx(M,j,B)},renderShell:Ur,reloadData:()=>{sc()}}),Mx({summary:n,fresh:l,createInvite:()=>{Xx()},renderShell:Ur}),Fx({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(M,j)=>{Qx(M,j)}}),HT({summary:n,fresh:f,snapshotMatchesTarget:u,runDevice:(M,j,B,U)=>{Zx(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 e0(){Ur()}async function sc(){const e=Tv(),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 Ly(e)==="superseded")return;const n=String(C.lastCoordinatorAdminStatus?.active_group||"").trim();if(fy(),C.lastCoordinatorAdminStatus?.readiness==="ready"&&Tn(N.recovery,"status")){try{const o=await dm();if(!t())return;C.lastShareOperations=Array.isArray(o.items)?o.items:[]}catch{if(!t())return}try{const o=await qf(N.showArchivedGroups);if(!t())return;if(!Array.isArray(o?.items))throw new Error("Invalid groups payload");C.lastCoordinatorAdminGroups=o.items,Ds(N.recovery,"groups"),WE(),fy()}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 qS(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",$t(N.joinRequestsSnapshotTarget))}try{if(!i)throw new Error("Missing coordinator administration target");const o=await Hf(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"),YE()}catch{if(!t())return;cn(N.recovery,"devices",$t(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",$t(N.joinRequestsSnapshotTarget)),cn(N.recovery,"devices",$t(N.devicesSnapshotTarget)));t()&&(Rv([...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=kv(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,jy={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},t0={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},n0={available:"Available",offline:"Offline",unknown:"Availability unknown"};function r0(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function i0(e,t){return t.get(e)??t0}function o0(e){return e.reduce((t,n)=>!t||jy[n.state]>jy[t.state]?n:t,null)}function a0(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 s0(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=r0(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),m=_=>{const I=s.get(_);if(!I)return null;const R=i0(_,d);return{canonicalProjectIdentity:_,displayName:I,state:R.state,statusLabel:R.label,statusCopy:R.explanation,deliveredCopiesMayRemain:R.deliveredCopiesMayRemain}},v=f.flatMap(_=>{const I=m(_);return I?[I]:[]}),g=[],h=[...v,...g],y=o0(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:n0[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:a0(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 Oy({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 My="devices-commit-status";function jn(e){const t=document.getElementById(My);t&&(t.textContent=e)}function c0({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??om,I=r.commitBindings??am,R=Mu(r),k=d!==null&&lc(d.preview,d.request,n,"bind"),A=Pe(()=>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(R){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||R||!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||R||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||R,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:R,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||R||!p||!k,onClick:()=>{B()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function Fy({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),R=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??om)(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??am)({...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):"})," ",R]}),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 l0({intent:e,options:t,projection:n}){if(t.loading)return a(vg,{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=yg(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(Fy,{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(c0,{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(Oy,{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(Oy,{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(Fy,{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=s0(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(l0,{intent:t,options:o,projection:d}),a("p",{"aria-live":"polite",id:My,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 d0(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 u0(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 ir(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 By(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function p0(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 f0(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 Uy(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function m0(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function h0(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 qy(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function g0(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function v0(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 Gy(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 y0(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 b0(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 Hy(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 Ky(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function Pt(e){return`${String(e.kind||"").toLowerCase()}:${Ky(e)}`}function _0(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 w0(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function S0(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function C0(e){if(Gy(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 I0(e,t={}){if(Gy(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 Vy(e,t){const n=new Map;return e.forEach(r=>{n.set(Pt(r),r)}),t.forEach(r=>{n.set(Pt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function R0(e,t){const n=new Set(t.map(Pt));return Vy(e.filter(r=>!n.has(Pt(r))),t)}var MU=560;function P0(){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 k0(e,t){const n=new Set(t.map(Pt));return e.filter(r=>!n.has(Pt(r))).length}var T0=Object.defineProperty,nt=(e,t)=>T0(e,"name",{value:t,configurable:!0}),[Uu,FU]=lt("Tooltip",[Qn]),hc=Qn(),N0="TooltipProvider",E0=700,qu="tooltip.open",[A0,Gu]=Uu(N0),x0=nt(e=>{const{__scopeTooltip:t,delayDuration:n=E0,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(A0,{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",[D0,ea]=Uu(Hu),$0=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=Et(),g=q(0),h=s??l.disableHoverableContent,y=c??l.delayDuration,w=q(!1),[_,I]=At({prop:r,defaultProp:i??!1,onChange:nt(T=>{T?(l.onOpen(),document.dispatchEvent(new CustomEvent(qu))):l.onClose(),o?.(T)},"onChange"),caller:Hu}),R=Pe(()=>_?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(D0,{scope:t,contentId:f??v,setContentId:m,open:_,stateAttribute:R,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"),zy="TooltipTrigger",L0=J(nt(function(t,n){const{__scopeTooltip:r,...i}=t,o=ea(zy,r),s=Gu(zy,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")),Wy="TooltipPortal",[j0,O0]=Uu(Wy,{forceMount:void 0}),M0=nt(e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=ea(Wy,t);return a(j0,{scope:t,forceMount:n,children:a(Rt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),ta="TooltipContent",F0=J(nt(function(t,n){const r=O0(ta,t.__scopeTooltip),{forceMount:i=r.forceMount,side:o="top",...s}=t,c=ea(ta,t.__scopeTooltip);return a(Rt,{present:i||c.open,children:c.disableHoverableContent?a(Jy,{side:o,...s,ref:n}):a(B0,{side:o,...s,ref:n})})},"TooltipContent")),B0=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},_=Xy(w,Yy(w,y.getBoundingClientRect())),I=Qy(h.getBoundingClientRect()),R=eb([..._,...I]);l(R),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=!Zy(w,c);_?m():I&&(m(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[d,p,c,u,m]),a(Jy,{...t,ref:s})},"TooltipContentHoverable")),U0=Ih("TooltipContent"),Jy=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(U0,{children:i}),o?a(fk,{id:u.contentId,role:"tooltip",children:o}):null]})})},"TooltipContentImpl")),q0=J(nt(function(t,n){const{__scopeTooltip:r,...i}=t,o=hc(r);return a(bE,{...o,...i,ref:n})},"TooltipArrow"));function Yy(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(Yy,"getExitSideFromRect");function Xy(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(Xy,"getPaddedExitPoints");function Qy(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(Qy,"getPointsFromRect");function Zy(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(Zy,"isPointInPolygon");function eb(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),tb(t)}nt(eb,"getHull");function tb(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(tb,"getHullPresorted");var G0=x0,H0=$0,K0=L0,V0=M0,z0=F0,W0=q0;function Ku({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(G0,{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(H0,{children:[a(K0,{asChild:o,children:e}),a(V0,{children:a(z0,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(W0,{className:"tooltip-arrow"})]})})]})}function J0(e){e.dataset.feedRenderRoot="preact"}function Y0(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function X0(e,t){J0(e),We(b(Ku,null,t),e)}function Q0(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function Z0(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 eD(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:y0(r||n),d=l.length?l:b0(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function tD(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 nD(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function rD(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function iD(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function oD(e,t){const n=C.feedTypeFilter==="observations"?" · observations":C.feedTypeFilter==="summaries"?" · session summaries":"",r=w0(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 aD({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,R=Z0(c),k=Vu({project:I,query:_,workingSetFiles:R}),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(Q0({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const F=async()=>{const U=_,$=I,E=R,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 XS({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 sD={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=sD[e],o=t?`${i} ${t}`:i;return a("span",{className:o,title:n,children:r})}function nb(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 cD(e){if(Array.isArray(e))return e}function lD(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 dD(){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 uD(e,t){return cD(e)||lD(e,t)||pD(e,t)||dD()}function pD(e,t){if(e){if(typeof e=="string")return nb(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)?nb(e,t):void 0}}var rb=Object.entries,ib=Object.setPrototypeOf,fD=Object.isFrozen,mD=Object.getPrototypeOf,hD=Object.getOwnPropertyDescriptor,rt=Object.freeze,st=Object.seal,Gi=Object.create,ob=typeof Reflect<"u"&&Reflect,Wu=ob.apply,Ju=ob.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),gD=Qe(Array.prototype.lastIndexOf),ab=Qe(Array.prototype.pop),na=Qe(Array.prototype.push),vD=Qe(Array.prototype.splice),Hi=Array.isArray,ra=Qe(String.prototype.toLowerCase),Yu=Qe(String.prototype.toString),sb=Qe(String.prototype.match),ia=Qe(String.prototype.replace),cb=Qe(String.prototype.indexOf),yD=Qe(String.prototype.trim),bD=Qe(Number.prototype.toString),_D=Qe(Boolean.prototype.toString),lb=typeof BigInt>"u"?null:Qe(BigInt.prototype.toString),db=typeof Symbol>"u"?null:Qe(Symbol.prototype.toString),kt=Qe(Object.prototype.hasOwnProperty),oa=Qe(Object.prototype.toString),gt=Qe(RegExp.prototype.test),Hr=wD(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 wD(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(ib&&ib(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&&(fD(t)||(t[r]=o),i=o)}e[i]=!0}return e}function SD(e){for(let t=0;t<e.length;t++)kt(e,t)||(e[t]=null);return e}function Lt(e){const t=Gi(null);for(const r of rb(e)){var n=uD(r,2);const i=n[0],o=n[1];kt(e,i)&&(Hi(o)?t[i]=SD(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=Lt(o):t[i]=o)}return t}function CD(e){switch(typeof e){case"string":return e;case"number":return bD(e);case"boolean":return _D(e);case"bigint":return lb?lb(e):"0";case"symbol":return db?db(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=hD(e,t);if(r){if(r.get)return Qe(r.get);if(typeof r.value=="function")return Qe(r.value)}e=mD(e)}function n(){return null}return n}function ID(e){try{return gt(e,""),!0}catch{return!1}}var ub=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"]),RD=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"]),PD=rt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),pb=rt(["#text"]),fb=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"]),mb=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"]),kD=st(/{{[\w\W]*|^[\w\W]*}}/g),TD=st(/<%[\w\W]*|^[\w\W]*%>/g),ND=st(/\${[\w\W]*/g),ED=st(/^data-[\-\w.\u00B7-\uFFFF]+$/),AD=st(/^aria-[\-\w]+$/),hb=st(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),xD=st(/^(?:\w+script|data):/i),DD=st(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$D=st(/^html$/i),LD=st(/^[a-z][.\w]*(-[.\w]+)+$/i),gb=st(/<[/\w!]/g),vb=st(/<[/\w]/g),jD=st(/<\/no(script|embed|frames)/i),OD=st(/\/>/i),jt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},yb=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],MD=rt(Ae({},yb)),FD=(function(){const e={};return Gr(yb,t=>{e[t]=st(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),rt(e)})(),BD=function(){return typeof window>"u"?null:window},UD=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}},bb=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},or=function(t,n,r,i){return kt(t,n)&&Hi(t[n])?Ae(i.base?Lt(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"?Lt(i):r()};function _b(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:BD();const t=X=>_b(X);if(t.version="3.4.14",t.removed=[],!e||!e.document||e.document.nodeType!==jt.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,R=s&&s.prototype?Yt(s.prototype,"ownerDocument"):null,k=function(P){return _?_(P):P.nodeType},A=function(P){return I?I(P):P.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(P){B(),j++;try{return L.createHTML(P)}finally{j--}},$=function(P){B(),j++;try{return L.createScriptURL(P)}finally{j--}},E=function(){return M||(T=UD(u,i),M=!0),T},S=n,D=S.implementation,H=S.createNodeIterator,G=S.createDocumentFragment,oe=S.getElementsByTagName,ae=r.importNode;let ee=bb();t.isSupported=typeof rb=="function"&&typeof h=="function"&&D&&D.createHTMLDocument!==void 0;const ie=kD,Ce=TD,Ie=ND,Ne=ED,le=AD,ye=xD,Y=DD,ce=LD;let ge=hb,pe=null;const He=Ae({},[...ub,...Xu,...Qu,...Zu,...pb]);let de=null;const W=Ae({},[...fb,...ep,...mb,...yc]);let Re=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,qn=!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,cS=!1;const lS="user-content-";let Tf=!0,Nf=!1,lo={},uo=null;const dS=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 uS=null;const pS=Ae({},["audio","video","img","source","image","track"]);let fS=null;const mS=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,Ef=!1,Af=null;const dU=Ae({},[rl,il,bn],Yu),hS=rt(["mi","mo","mn","ms","mtext"]);let xf=Ae({},hS);const gS=rt(["annotation-xml"]);let Df=Ae({},gS);const uU=Ae({},["title","style","font","a","script"]);let Oa=null;const pU=["application/xhtml+xml","text/html"],fU="text/html";let Ye=null,fo=null;const mU=n.createElement("form"),vS=function(P){return P instanceof RegExp||P instanceof Function},$f=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(fo&&fo===P)return;(!P||typeof P!="object")&&(P={}),P=Lt(P),Oa=pU.indexOf(P.PARSER_MEDIA_TYPE)===-1?fU:P.PARSER_MEDIA_TYPE,Ye=Oa==="application/xhtml+xml"?Yu:ra,pe=or(P,"ALLOWED_TAGS",He,{transform:Ye}),de=or(P,"ALLOWED_ATTR",W,{transform:Ye}),Af=or(P,"ALLOWED_NAMESPACES",dU,{transform:Yu}),fS=or(P,"ADD_URI_SAFE_ATTR",mS,{transform:Ye,base:mS}),uS=or(P,"ADD_DATA_URI_TAGS",pS,{transform:Ye,base:pS}),uo=or(P,"FORBID_CONTENTS",dS,{transform:Ye}),re=or(P,"FORBID_TAGS",Lt({}),{transform:Ye}),je=or(P,"FORBID_ATTR",Lt({}),{transform:Ye}),lo=kt(P,"USE_PROFILES")?P.USE_PROFILES&&typeof P.USE_PROFILES=="object"?Lt(P.USE_PROFILES):P.USE_PROFILES:!1,hr=P.ALLOW_ARIA_ATTR!==!1,Zt=P.ALLOW_DATA_ATTR!==!1,qn=P.ALLOW_UNKNOWN_PROTOCOLS||!1,gr=P.ALLOW_SELF_CLOSE_IN_ATTR!==!1,me=P.SAFE_FOR_TEMPLATES||!1,ot=P.SAFE_FOR_XML!==!1,Ze=P.WHOLE_DOCUMENT||!1,vn=P.RETURN_DOM||!1,_t=P.RETURN_DOM_FRAGMENT||!1,yn=P.RETURN_TRUSTED_TYPE||!1,co=P.FORCE_BODY||!1,nl=P.SANITIZE_DOM!==!1,cS=P.SANITIZE_NAMED_PROPS||!1,Tf=P.KEEP_CONTENT!==!1,Nf=P.IN_PLACE||!1,ge=ID(P.ALLOWED_URI_REGEXP)?P.ALLOWED_URI_REGEXP:hb,po=typeof P.NAMESPACE=="string"?P.NAMESPACE:bn,xf=tp(P,"MATHML_TEXT_INTEGRATION_POINTS",()=>Ae({},hS)),Df=tp(P,"HTML_INTEGRATION_POINTS",()=>Ae({},gS));const O=tp(P,"CUSTOM_ELEMENT_HANDLING",()=>Gi(null));if(Re=Gi(null),kt(O,"tagNameCheck")&&vS(O.tagNameCheck)&&(Re.tagNameCheck=O.tagNameCheck),kt(O,"attributeNameCheck")&&vS(O.attributeNameCheck)&&(Re.attributeNameCheck=O.attributeNameCheck),kt(O,"allowCustomizedBuiltInElements")&&typeof O.allowCustomizedBuiltInElements=="boolean"&&(Re.allowCustomizedBuiltInElements=O.allowCustomizedBuiltInElements),st(Re),me&&(Zt=!1),_t&&(vn=!0),lo&&(pe=Ae({},pb),de=Gi(null),lo.html===!0&&(Ae(pe,ub),Ae(de,fb)),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,mb),Ae(de,yc))),it.tagCheck=null,it.attributeCheck=null,kt(P,"ADD_TAGS")&&(typeof P.ADD_TAGS=="function"?it.tagCheck=P.ADD_TAGS:Hi(P.ADD_TAGS)&&(pe===He&&(pe=Lt(pe)),Ae(pe,P.ADD_TAGS,Ye))),kt(P,"ADD_ATTR")&&(typeof P.ADD_ATTR=="function"?it.attributeCheck=P.ADD_ATTR:Hi(P.ADD_ATTR)&&(de===W&&(de=Lt(de)),Ae(de,P.ADD_ATTR,Ye))),kt(P,"ADD_FORBID_CONTENTS")&&Hi(P.ADD_FORBID_CONTENTS)&&(uo===dS&&(uo=Lt(uo)),Ae(uo,P.ADD_FORBID_CONTENTS,Ye)),Tf&&(pe["#text"]=!0),Ze&&Ae(pe,["html","head","body"]),pe.table&&(Ae(pe,["tbody"]),delete re.tbody),P.TRUSTED_TYPES_POLICY){if(typeof P.TRUSTED_TYPES_POLICY.createHTML!="function")throw Hr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof P.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Hr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const V=L;L=P.TRUSTED_TYPES_POLICY;try{F=U("")}catch(te){throw L=V,te}}else P.TRUSTED_TYPES_POLICY===null?(L=void 0,F=""):(L===void 0&&(L=E()),L&&typeof F=="string"&&(F=U("")));rt&&rt(P),fo=P},yS=Ae({},[...Xu,...Qu,...RD]),bS=Ae({},[...Zu,...PD]),hU=function(P,O,V){return O.namespaceURI===bn?P==="svg":O.namespaceURI===rl?P==="svg"&&(V==="annotation-xml"||xf[V]):!!yS[P]},gU=function(P,O,V){return O.namespaceURI===bn?P==="math":O.namespaceURI===il?P==="math"&&Df[V]:!!bS[P]},vU=function(P,O,V){return O.namespaceURI===il&&!Df[V]||O.namespaceURI===rl&&!xf[V]?!1:!bS[P]&&(uU[P]||!yS[P])},yU=function(P){let O=h(P);(!O||!O.tagName)&&(O={namespaceURI:po,tagName:"template"});const V=ra(P.tagName),te=ra(O.tagName);return Af[P.namespaceURI]?P.namespaceURI===il?hU(V,O,te):P.namespaceURI===rl?gU(V,O,te):P.namespaceURI===bn?vU(V,O,te):!!(Oa==="application/xhtml+xml"&&Af[P.namespaceURI]):!1},vr=function(P){na(t.removed,{element:P});try{h(P).removeChild(P)}catch{if(m(P),!h(P))throw Hr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},_S=function(P,O,V){try{P.removeAttributeNode(O)}catch{try{P.removeAttribute(V)}catch{}}},ol=function(P){al(P);const O=g(P);if(O){const te=[];Gr(O,ue=>{na(te,ue)}),Gr(te,ue=>{try{m(ue)}catch{}})}const V=w(P);if(V)for(let te=V.length-1;te>=0;--te){const ue=V[te],be=ue&&ue.name;typeof be=="string"&&_S(P,ue,be)}},si=function(P,O,V){if(!V)try{V=O.getAttributeNode(P)}catch{V=null}na(t.removed,{attribute:V||null,from:O});try{V?O.removeAttributeNode(V):O.removeAttribute(P)}catch{try{O.removeAttribute(P)}catch{}}if(P==="is")if(vn||_t)try{vr(O)}catch{}else try{O.setAttribute(P,"")}catch{}},bU=function(P){const O=w(P);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)]||_S(P,te,ue)}},al=function(P){const O=[P];for(;O.length>0;){const V=O.pop();k(V)===jt.element&&bU(V);const te=g(V);if(te)for(let ue=te.length-1;ue>=0;--ue)O.push(te[ue])}},wS=function(P,O){return ot?P==="patchsrc"?!0:P==="for"&&O!=="label"&&O!=="output":!1},_U=function(P){if(!ot)return;const O=[P];for(;O.length>0;){const V=O.pop(),te=k(V);if(te===jt.processingInstruction||te===jt.comment&>(vb,V.data)){try{m(V)}catch{}continue}if(te===jt.element){const be=V,xe=Ye(A(V));try{be.hasAttribute&&be.hasAttribute("patchsrc")&&be.removeAttribute("patchsrc"),be.hasAttribute&&be.hasAttribute("for")&&wS("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])}},SS=function(P){let O=null,V=null;if(co)P="<remove></remove>"+P;else{const be=sb(P,/^[\r\n\t ]+/);V=be&&be[0]}Oa==="application/xhtml+xml"&&po===bn&&(P='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+P+"</body></html>");const te=L?U(P):P;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=Ef?F:te}catch{}}const ue=O.body||O.documentElement;return P&&V&&ue.insertBefore(n.createTextNode(V),ue.childNodes[0]||null),po===bn?oe.call(O,Ze?"html":"body")[0]:Ze?O.documentElement:ue},CS=function(P){const O=R?R(P):P.ownerDocument;return H.call(O||P,P,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},sl=function(P){return P=ia(P,ie," "),P=ia(P,Ce," "),P=ia(P,Ie," "),P},Lf=function(P){var O;P.normalize();const V=R?R(P):P.ownerDocument,te=H.call(V||P,P,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=P.querySelectorAll)===null||O===void 0?void 0:O.call(P,"template");be&&Gr(be,xe=>{mo(xe.content)&&Lf(xe.content)})},cl=function(P){const O=I?I(P):null;return typeof O!="string"||Ye(O)!=="form"?!1:typeof P.nodeName!="string"||typeof P.textContent!="string"||typeof P.removeChild!="function"||P.attributes!==w(P)||typeof P.removeAttribute!="function"||typeof P.setAttribute!="function"||typeof P.namespaceURI!="string"||typeof P.insertBefore!="function"||typeof P.hasChildNodes!="function"||P.nodeType!==_(P)||P.childNodes!==g(P)},mo=function(P){if(!_||typeof P!="object"||P===null)return!1;try{return _(P)===jt.documentFragment}catch{return!1}},Ma=function(P){if(!_||typeof P!="object"||P===null)return!1;try{return typeof _(P)=="number"}catch{return!1}};function _n(X,P,O){X.length!==0&&Gr(X,V=>{V.call(t,P,O,fo)})}const wU=function(P,O){return!!(ot&&P.hasChildNodes()&&!Ma(P.firstElementChild)&>(gb,P.textContent)&>(gb,P.innerHTML)||ot&&P.namespaceURI===bn&&MD[O]&&(Ma(P.firstElementChild)||typeof P.textContent=="string"&>(FD[O],P.textContent))||P.nodeType===jt.processingInstruction||ot&&P.nodeType===jt.comment&>(vb,P.data))},ll=function(P,O){if(P instanceof RegExp)return gt(P,O);if(P 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!!P(O,...te)}return!1},SU=function(P,O,V){if(!re[O]&&TS(O)&&ll(Re.tagNameCheck,O))return!1;if(Tf&&!uo[O]){const te=h(P),ue=g(P);if(ue&&te){const be=ue.length;for(let xe=be-1;xe>=0;--xe){const St=P===V?f(ue[xe],!0):ue[xe];te.insertBefore(St,v(P))}}}return vr(P),!0},IS=function(P,O,V,te){return P.length===0?O:O===V||O===te?Lt(O):O},RS=function(P,O){return P===O||h(P)!==null?!1:(Nf&&al(P),!0)},PS=function(P,O){if(_n(ee.beforeSanitizeElements,P,null),RS(P,O))return!0;if(cl(P))return vr(P),!0;const V=Ye(A(P));if(pe=IS(ee.uponSanitizeElement,pe,He,so),_n(ee.uponSanitizeElement,P,{tagName:V,allowedTags:pe}),RS(P,O))return!0;if(wU(P,V))return vr(P),!0;if(re[V]||!(it.tagCheck instanceof Function&&it.tagCheck(V))&&!pe[V]){const te=SU(P,V,O);return te===!1&&_n(ee.afterSanitizeElements,P,null),te}if(k(P)===jt.element&&!yU(P)||(V==="noscript"||V==="noembed"||V==="noframes")&>(jD,P.innerHTML))return vr(P),!0;if(me&&P.nodeType===jt.text){const te=sl(P.textContent);P.textContent!==te&&(na(t.removed,{element:P.cloneNode()}),P.textContent=te)}return _n(ee.afterSanitizeElements,P,null),!1},kS=function(P,O,V){if(je[O]||wS(O,P)||nl&&(O==="id"||O==="name")&&(V in n||V in mU))return!1;const te=de[O]||it.attributeCheck instanceof Function&&it.attributeCheck(O,P);return Zt&>(Ne,O)||hr&>(le,O)?!0:te?fS[O]||gt(ge,ia(V,Y,""))||(O==="src"||O==="xlink:href"||O==="href")&&P!=="script"&&cb(V,"data:")===0&&uS[P]||qn&&!gt(ye,ia(V,Y,""))?!0:!V:TS(P)&&ll(Re.tagNameCheck,P)&&ll(Re.attributeNameCheck,O,P)||O==="is"&&Re.allowCustomizedBuiltInElements&&ll(Re.tagNameCheck,V)},CU=Ae({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),TS=function(P){return!CU[ra(P)]&>(ce,P)},IU=function(P,O,V,te){if(L&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!V)switch(u.getAttributeType(P,O)){case"TrustedHTML":return U(te);case"TrustedScriptURL":return $(te)}return te},RU=function(P,O,V,te){try{V?P.setAttributeNS(V,O,te):P.setAttribute(O,te),cl(P)?vr(P):ab(t.removed)}catch{si(O,P)}},NS=function(P){_n(ee.beforeSanitizeAttributes,P,null);const O=P.attributes;if(!O||cl(P))return;de=IS(ee.uponSanitizeAttribute,de,W,ai);const V={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:de,forceKeepAttr:void 0};let te=O.length;const ue=Ye(P.nodeName);for(;te--;){const be=O[te],xe=be.name,St=be.namespaceURI,en=be.value,Tt=Ye(xe),Of=en;let Ct=xe==="value"?Of:yD(Of);if(V.attrName=Tt,V.attrValue=Ct,V.keepAttr=!0,V.forceKeepAttr=void 0,_n(ee.uponSanitizeAttribute,P,V),Ct=V.attrValue,cS&&(Tt==="id"||Tt==="name")&&cb(Ct,lS)!==0&&(si(xe,P,be),Ct=lS+Ct),ot&>(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ct)){si(xe,P,be);continue}if(Tt==="attributename"&&sb(Ct,"href")){si(xe,P,be);continue}if(!V.forceKeepAttr){if(!V.keepAttr){si(xe,P,be);continue}if(!gr&>(OD,Ct)){si(xe,P,be);continue}if(me&&(Ct=sl(Ct)),!kS(ue,Tt,Ct)){si(xe,P,be);continue}Ct=IU(ue,Tt,St,Ct),Ct!==Of&&RU(P,xe,St,Ct)}}_n(ee.afterSanitizeAttributes,P,null)},dl=function(P){let O=null;const V=CS(P);for(_n(ee.beforeSanitizeShadowDOM,P,null);O=V.nextNode();)if(_n(ee.uponSanitizeShadowNode,O,null),PS(O,P),NS(O),mo(O.content)&&dl(O.content),k(O)===jt.element){const te=y(O);mo(te)&&(jf(te),dl(te))}_n(ee.afterSanitizeShadowDOM,P,null)},jf=function(P){const O=[{node:P,shadow:null}];for(;O.length>0;){const V=O.pop();if(V.shadow){dl(V.shadow);continue}const te=V.node,ue=k(te)===jt.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 P=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},O=null,V=null,te=null,ue=null;if(Ef=!X,Ef&&(X="<!-->"),typeof X!="string"&&!Ma(X)&&(X=CD(X),typeof X!="string"))throw Hr("dirty is not a string, aborting");if(!t.isSupported)return X;ao?(pe=so,de=ai):$f(P),(ee.uponSanitizeElement.length>0||ee.uponSanitizeAttribute.length>0)&&(pe=Lt(pe)),ee.uponSanitizeAttribute.length>0&&(de=Lt(de)),t.removed=[];const be=Nf&&typeof X!="string"&&Ma(X);if(be){_U(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{jf(X)}catch(Tt){throw ol(X),Tt}}else if(Ma(X))O=SS("<!---->"),V=O.ownerDocument.importNode(X,!0),V.nodeType===jt.element&&V.nodeName==="BODY"||V.nodeName==="HTML"?O=V:O.appendChild(V),jf(V);else{if(!vn&&!me&&!Ze&&X.indexOf("<")===-1)return L&&yn?U(X):X;if(O=SS(X),!O)return vn?null:yn?F:""}O&&co&&vr(O.firstChild);const xe=be?X:O;try{const en=CS(xe);for(;te=en.nextNode();)PS(te,xe),NS(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&&Lf(X),X;if(vn){if(me&&Lf(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&>($D,O.ownerDocument.doctype.name)&&(St="<!DOCTYPE "+O.ownerDocument.doctype.name+`>
|
|
44
|
-
`+
|
|
45
|
-
]`).replace("lheading",
|
|
46
|
-
`),n=t.length-1;for(;n>=0&&
|
|
47
|
-
`)}function
|
|
41
|
+
`)},Ik=0,Ii=[];function kk(e){var t=B([]),n=B([0,0]),r=B(),i=x(Ik++)[0],o=x(_g)[0],s=B(e);V(function(){s.current=e},[e]),V(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var g=zI([e.lockRef.current],(e.shards||[]).map(Tg),!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=ae(function(g,h){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!s.current.allowPinchZoom;var b=ps(g),w=n.current,_="deltaX"in g?g.deltaX:w[0]-b[0],R="deltaY"in g?g.deltaY:w[1]-b[1],I,T=g.target,A=Math.abs(_)>Math.abs(R)?"h":"v";if("touches"in g&&A==="h"&&T.type==="range")return!1;var O=window.getSelection(),F=O&&O.anchorNode;if(F&&(F===T||F.contains(T)))return!1;var N=Cg(A,T);if(!N)return!0;if(N?I=A:(I=A==="v"?"h":"v",N=Cg(A,T)),!N)return!1;if(!r.current&&"changedTouches"in g&&(_||R)&&(r.current=I),!I)return!0;var L=r.current||I;return Sk(L,h,g,L==="h"?_:R,!0)},[]),l=ae(function(g){var h=g;if(!(!Ii.length||Ii[Ii.length-1]!==o)){var b="deltaY"in h?kg(h):ps(h),w=t.current.filter(function(R){return R.name===h.type&&(R.target===h.target||h.target===R.shadowParent)&&Ck(R.delta,b)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(Tg).filter(Boolean).filter(function(R){return R.contains(h.target)});(_.length>0?c(h,_[0]):!s.current.noIsolation)&&h.cancelable&&h.preventDefault()}}},[]),d=ae(function(g,h,b,w){var _={name:g,delta:h,target:b,should:w,shadowParent:Tk(b)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(R){return R!==_})},1)},[]),u=ae(function(g){n.current=ps(g),r.current=void 0},[]),p=ae(function(g){d(g.type,kg(g),g.target,c(g,e.lockRef.current))},[]),f=ae(function(g){d(g.type,ps(g),g.target,c(g,e.lockRef.current))},[]);V(function(){return Ii.push(o),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Ri),document.addEventListener("touchmove",l,Ri),document.addEventListener("touchstart",u,Ri),function(){Ii=Ii.filter(function(g){return g!==o}),document.removeEventListener("wheel",l,Ri),document.removeEventListener("touchmove",l,Ri),document.removeEventListener("touchstart",u,Ri)}},[]);var m=e.removeScrollBar,v=e.inert;return y(z,null,v?y(o,{styles:Rk(i)}):null,m?y(hk,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Tk(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Pk=nk(yg,kk),To=J(function(e,t){return y(ds,ln({},e,{ref:t,sideCar:Pk}))});To.classNames=ds.classNames;var Nk=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},ki=new WeakMap,fs=new WeakMap,ms={},bd=0,Pg=function(e){return e&&(e.host||Pg(e.parentNode))},Ek=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Pg(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})},Ak=function(e,t,n,r){var i=Ek(t,Array.isArray(e)?e:[e]);ms[n]||(ms[n]=new WeakMap);var o=ms[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=(ki.get(f)||0)+1,h=(o.get(f)||0)+1;ki.set(f,g),o.set(f,h),s.push(f),g===1&&v&&fs.set(f,!0),h===1&&f.setAttribute(n,"true"),v||f.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",f,b)}})};return u(t),c.clear(),bd++,function(){s.forEach(function(p){var f=ki.get(p)-1,m=o.get(p)-1;ki.set(p,f),o.set(p,m),f||(fs.has(p)||p.removeAttribute(r),fs.delete(p)),m||p.removeAttribute(n)}),bd--,bd||(ki=new WeakMap,ki=new WeakMap,fs=new WeakMap,ms={})}},hs=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||Nk(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),Ak(r,i,n,"aria-hidden")):function(){return null}},xk=Object.defineProperty,dn=(e,t)=>xk(e,"name",{value:t,configurable:!0}),_d="Dialog",[Ng,F2]=dt(_d),[Dk,Xn]=Ng(_d),Lk=dn(e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!0}=e,c=B(null),l=B(null),[d,u]=At({prop:r,defaultProp:i??!1,onChange:o,caller:_d}),[p,f]=x(0),[m,v]=x(0);return a(Dk,{scope:t,triggerRef:c,contentRef:l,contentId:Et(),titleId:Et(),descriptionId:Et(),titlePresent:p>0,descriptionPresent:m>0,setTitleCount:f,setDescriptionCount:v,open:d,onOpenChange:u,onOpenToggle:ae(()=>u(g=>!g),[u]),modal:s,children:n})},"Dialog"),Eg="DialogPortal",[$k,Ag]=Ng(Eg,{forceMount:void 0}),Ok=dn(e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,o=Xn(Eg,t);return a($k,{scope:t,forceMount:n,children:Tr.map(r,s=>a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:s})}))})},"DialogPortal"),wd="DialogOverlay",jk=J(dn(function(t,n){const r=Ag(wd,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Xn(wd,t.__scopeDialog);return s.modal?a(kt,{present:i||s.open,children:a(Fk,{...o,ref:n})}):null},"DialogOverlay")),Mk=cn("DialogOverlay.RemoveScroll"),Fk=J(dn(function(t,n){const{__scopeDialog:r,...i}=t,o=Xn(wd,r),s=eg(),c=Re(n,s);return a(To,{as:Mk,allowPinchZoom:!0,shards:[o.contentRef],children:a(ye.div,{"data-state":Sd(o.open),...i,ref:c,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),Po="DialogContent",Bk=J(dn(function(t,n){const r=Ag(Po,t.__scopeDialog),{forceMount:i=r.forceMount,...o}=t,s=Xn(Po,t.__scopeDialog);return a(kt,{present:i||s.open,children:s.modal?a(qk,{...o,ref:n}):a(Uk,{...o,ref:n})})},"DialogContent")),qk=J(dn(function(t,n){const r=Xn(Po,t.__scopeDialog),i=B(null),o=Re(n,r.contentRef,i);return V(()=>{const s=i.current;if(s)return hs(s)},[]),a(xg,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:te(t.onCloseAutoFocus,s=>{s.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:te(t.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;(c.button===2||l)&&s.preventDefault()}),onFocusOutside:te(t.onFocusOutside,s=>s.preventDefault())})},"DialogContentModal")),Uk=J(dn(function(t,n){const r=Xn(Po,t.__scopeDialog),i=B(!1),o=B(!1);return a(xg,{...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")),xg=J(dn(function(t,n){const{__scopeDialog:r,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:s,...c}=t,l=Xn(Po,r);return Ci(),a(z,{children:a(as,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(bi,{role:"dialog",id:l.contentId,"aria-describedby":l.descriptionPresent?l.descriptionId:void 0,"aria-labelledby":l.titlePresent?l.titleId:void 0,"data-state":Sd(l.open),...c,ref:n,deferPointerDownOutside:!0,onDismiss:()=>l.onOpenChange(!1)})})})},"DialogContentImpl")),Gk="DialogTitle",Hk=J(dn(function(t,n){const{__scopeDialog:r,...i}=t,o=Xn(Gk,r),{setTitleCount:s}=o;return Ze(()=>(s(c=>c+1),()=>s(c=>c-1)),[s]),a(ye.h2,{id:o.titleId,...i,ref:n})},"DialogTitle"));function Sd(e){return e?"open":"closed"}dn(Sd,"getState");function Qn({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(Lk,{modal:o,open:p,onOpenChange:u,children:p?a(Ok,{children:[a(jk,{asChild:!0,children:a("div",{className:f,id:m})}),a(Bk,{"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 Dg(e){return a(Hk,{...e})}function Vk(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function No(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function Lg(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(Vk)}function Nr(e){const t=new Map;for(const r of Lg(e)){const i=No(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 Kk(e){const t=new Map;for(const n of Lg(e)){const r=No(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=No(n.displayName).localeCompare(No(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 $g=500,gs=null,Eo=null,Ao=null;function xo(e){return Eo?Eo(e)?(Ao=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Ao=document.activeElement instanceof HTMLElement?document.activeElement:null,gs=e,!0)}function ut(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Og(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 Do(e){return e.recipientKind==="identity"?ut({recipientKind:"identity",identityId:e.identityId}):ut({recipientKind:"team",teamId:e.teamId})}function zk(e,t){return Do(e)===ut(t)}function Cd(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 Wk(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)?[Do(c)]:[]),s=i.flatMap(c=>c.recipientKind==="identity"&&!r.has(c.identityId)?[Do(c)]:[]);return new Map([...Cd(o,"Unavailable Team"),...Cd(s,"Unavailable Identity")])}function Jk(e,t,n){if(t?.mode!=="recipient-manage")return new Map;const r=new Set(e.map(i=>i.canonicalProjectIdentity));return Cd(n.filter(i=>!r.has(i)),"Unavailable Project")}function jg(e,t){return e instanceof Nl?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Mg({checked:e,description:t,disabled:n,label:r,onChange:i}){const o=`recipient-policy-choice-${Ir()}`;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 Yk(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:ut({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:ut({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=Do(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 Xk(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(Do):n.filter(r=>zk(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function Qk(e,t,n,r){const i=Nr(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 Zk(e,t,n){return e.mode==="project-add"?Fg(e).flatMap(r=>t.flatMap(i=>{const o=Og(i);return o?[{canonicalProjectIdentity:r,recipient:o,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Og(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 eT(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 Bg(e,t){let n=!1,r=!1,i=!1,o=!1;const s=ut(t);for(const c of e){const{change:l,outcome:d}=c;ut(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 tT(e){const t=new Set(e.selectedRecipients.map(ut)),n=new Map;for(const r of e.normalizedChanges){const i=ut(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function nT(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function Rd(e,t){const n=t.get(e.canonicalProjectIdentity);return n||(e.displayName!==e.canonicalProjectIdentity?e.displayName:"Unavailable Project")}function rT({preview:e,projectLabels:t,recipientLabels:n}){const r=nT(e.effectiveDevices),i=tT(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:Rd(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:["— ",Bg(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."]})]},ut(o))),i.map(o=>a("li",{children:[a("strong",{className:"recipient-policy-management-name",children:n.get(ut(o))??(o.recipientKind==="team"?"Unavailable Team":"Unavailable Identity")})," ",a("span",{children:["— ",Bg(e.outcomes,o)," ·"," ",o.recipientKind==="team"?"Team":"Identity"]})]},ut(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:Rd(o,t)},o.canonicalProjectIdentity))})]}):null]})]})}function iT({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?Rd(s,t):t.get(o.change.canonicalProjectIdentity)??"Unavailable Project",l=e.selectedRecipients.find(d=>ut(d)===ut(o.change.recipient))?.displayName??n.get(ut(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}:${ut(o.change.recipient)}`)})}):null]})})}function oT({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(""),[b,w]=x(!1),_=B(!1),R=B(new Map),I=B(new Map),T=ke(()=>Wk(e,r),[e,r]),A=ke(()=>Yk(e,r,T),[e,r,T]),O=ke(()=>new Map([...e.teams.map(X=>[`team:${X.teamId}`,X.displayName]),...e.identities.map(X=>[`identity:${X.identityId}`,X.displayName]),...T]),[e,T]),F=ke(()=>Jk(n,r,c),[c,n,r]),N=ke(()=>new Set(n.map(X=>X.canonicalProjectIdentity)),[n]),L=ke(()=>{const X=Nr(n.map(ce=>({canonicalId:ce.canonicalProjectIdentity,displayName:ce.displayName})));return new Map([...X,...F])},[n,F]);if(V(()=>{if(Eo=X=>{if(_.current)return!1;const ce=Xk(X,e);return i(X),l(ce),s(X.mode==="recipient-add"?[]:ce),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""),w(!1),_.current=!1,!0},gs){const X=gs;gs=null,Eo(X)}return()=>{Eo=null}},[e]),V(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const D=eT(r),G=Fg(r),q=r.mode==="recipient-manage"?!1:G.some(X=>!N.has(X)),$=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!A.some(X=>X.key===ut(r.recipient)),E=t.loading||t.loadError||q||$,S=Zk(r,o,c),M=S.length>$g,H=(r.mode==="project-add"||r.mode==="recipient-add")&&o.length===0,U=r.mode!=="project-add"&&r.mode!=="recipient-add"&&S.length===0,re=Qk(n,r,c,F),oe=p?.status==="applied",ie=p?oe?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":D.title,se=p?oe?"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.":D.description,ue=()=>{_.current||(i(null),u(null),f(null),R.current=new Map,I.current=new Map,v(null),h(""))},Pe=X=>{s(ce=>ce.includes(X)?ce.filter(be=>be!==X):[...ce,X]),v(null),h("")},Ie=async()=>{if(!(E||H||U||M||_.current)){_.current=!0,w(!0),v(null),h("Reviewing exact recipient access changes.");try{const X=await yR({version:1,changes:S});R.current=new Map(O),I.current=new Map(L),u(X),h("Review ready. Confirm the exact changes.")}catch(X){v(jg(X,"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 X=await bR({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});f(X),h("");try{await t.onCommitted?.(X)}catch{v("Recipient access was saved, but this view could not refresh.")}}catch(X){X instanceof Nl&&(u(null),R.current=new Map,I.current=new Map,h("")),v(jg(X,"Unable to save recipient access changes."))}finally{_.current=!1,w(!1)}}};let ve=null;return t.loading?ve="Loading the complete recipient access inventory…":t.loadError?ve="The complete recipient access inventory is unavailable. Refresh and try again.":q?ve="One selected Project is no longer available. Refresh and try again.":$&&(ve="This recipient is no longer available. Refresh and try again."),a(Qn,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:X=>{X.preventDefault();const ce=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",be=Ao?.isConnected?Ao:document.getElementById(ce);be instanceof HTMLElement&&be.focus(),Ao=null},onOpenAutoFocus:X=>{const ce=document.getElementById("recipient-policy-management-title");ce&&(X.preventDefault(),ce.focus())},onOpenChange:X=>{X||ue()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:a("div",{"aria-busy":b||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:ie}),a(kr,{ariaLabel:`Close ${ie}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:ue})]}),a("div",{className:"modal-body recipient-policy-management-selection",children:[a("p",{className:"small",id:"recipient-policy-management-description",children:se}),ve?a("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:ve}):p&&d?a(iT,{preview:d,projectLabels:I.current,recipientLabels:R.current,result:p}):d?a(rT,{preview:d,projectLabels:I.current,recipientLabels:R.current}):r.mode==="recipient-add"||r.mode==="recipient-manage"?a("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[a("legend",{children:D.legend}),re.length?re.map(X=>a(Mg,{checked:o.includes(X.canonicalProjectIdentity),description:X.description,disabled:b,label:X.displayName,onChange:()=>Pe(X.canonicalProjectIdentity)},X.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:b,children:[a("legend",{children:D.legend}),A.length?A.map(X=>a(Mg,{checked:o.includes(X.key),description:X.description,disabled:b,label:X.label,onChange:()=>Pe(X.key)},X.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,M?a("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",S.length.toLocaleString()," access changes. Review at most ",$g.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:b,onClick:d&&!p?()=>{u(null),R.current=new Map,I.current=new Map,h("")}:ue,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!ve?a("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(H||U||M),onClick:()=>{d?le():Ie()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function qg(e,t,n,r={}){Ue(a(oT,{intent:n,options:r,projects:t}),e)}function vs(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function aT(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 ys(e){const t=new Map;for(const n of e)vs(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 Ug({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 sT(e){return e.state!=="configured"}function Gg(e){return e?.items.filter(sT)??[]}function bs(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 cT=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,lT=/^(?:actor|device|identity|local):\S+$/iu,dT=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,uT=/^pending[_-]\S+$/iu,pT=/^[a-f0-9]{12,64}$/iu,fT=/^(?=.{1,253}$)(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.){2,}[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.local)$/iu;function Id(e){return[cT,lT,dT,uT,pT,fT].some(t=>t.test(e))}function Ti(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||Id(t)?"":t}var Pi=null,Ni=null;function _s(e=[],t=""){if(Ni){const n=Ni(e,t);return n||(Pi=null),n}return Pi={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Hg(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Vg(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 mT(e){const t=`share-project-${Ir()}`,n=Hg(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 hT({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 gT({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,b]=x(null),[w,_]=x(!1),R=ke(()=>e.filter(Hg),[e]);V(()=>{if(Ni=(N,L="")=>{if(t)return!1;const D=[...new Set(N)],G=D.some(q=>!R.some($=>$.workspace_identity===q));return o(L.trim()),c(G?[]:D),_(G),d(null),p(null),m(G?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},Pi){const N=Pi;Pi=null,Ni(N.projectIds,N.teammateName)}return()=>{Ni=null}},[R,t]),V(()=>{t&&(Pi=null,r(!1),o(""),c([]),d(null),p(null),m(null),b(null),_(!1))},[t]);const I=()=>{v||r(!1)},T=N=>{c(L=>L.includes(N)?L.filter(D=>D!==N):[...L,N])},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 RR({teammate_name:i.trim(),project_ids:s}))}catch(N){m(Vg(N,"Unable to review this invitation."))}finally{g(!1)}},O=async()=>{if(l){m(null),g(!0);try{p(await IR({teammate_name:l.teammate.display_name,project_ids:l.projects.map(N=>N.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(N){N instanceof Error&&N.message==="reviewed_project_set_changed"&&d(null),m(Vg(N,"Unable to create this invitation."))}finally{g(!1)}}},F=async()=>{if(u){m(null),b(null);try{if(!navigator.clipboard)throw new Error("Clipboard access is unavailable.");await navigator.clipboard.writeText(u.invite.link),b("Invite copied.")}catch(N){m(N instanceof Error?N.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||R.length===0,onClick:()=>Ni?.([]),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(Qn,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:N=>{N||I()},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:I,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(N=>N.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(hT,{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:N=>o(N.currentTarget.value),type:"text",value:i})]}),a("fieldset",{className:"sync-dialog-radio-list",children:[a("legend",{children:"Select exact projects"}),e.map(N=>a(mT,{onToggle:T,project:N,selected:s.includes(N.workspace_identity)},N.workspace_identity))]})]}),f?a("p",{role:"alert",children:f}):null]}),a("div",{className:"modal-footer",children:[a("button",{className:"settings-button",disabled:v,onClick:I,type:"button",children:u?"Done":"Cancel"}),u?null:a("button",{className:"settings-button sync-dialog-confirm",disabled:v||w,onClick:()=>{l?O():A()},type:"button",children:v?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Kg(e,t,n={}){Ue(a(gT,{inventoryError:n.inventoryError===!0,projects:t}),e)}function kd(e){return Ti(String(e??"").trim())}function Ei(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.`:Id(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function vT(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 ws(e,t){return e instanceof Error?e instanceof ym?{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 Lo(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function yT({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})," — ",Lo(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function bT({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(yT,{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 _T({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," — ",Lo(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," — ",Lo(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," — ",Lo(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 zg({preview:e}){return e.journey==="team"?a(bT,{preview:e}):a(_T,{preview:e})}function wT({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 ST({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})," —"," ",Lo(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 CT({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 RT({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 Wg(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function IT({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),[b,w]=x(null),[_,R]=x(""),[I,T]=x(""),[A,O]=x(""),[F,N]=x(null),[L,D]=x(!1),[G,q]=x(""),[$,E]=x(""),S=B(null),M=B(0),H=B(""),U=B(!1);V(()=>{if(b){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,b]);const re=()=>{M.current+=1,H.current="",U.current=!1,u(""),f(null),v(null),h(null),w(null),R(""),T(""),O(""),N(null),q(""),E("")},oe=(W,de)=>{re(),S.current=de,i(W)},ie=()=>{L||(i(null),re())},se=W=>{M.current+=1,H.current=W,u(W)},ue=W=>{s(W),l(W==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),re()},Pe=async()=>{if(c){D(!0),E(""),q("Reviewing invitation…");try{const W=await _R(Wg(o,c));f(W.preview),q("Review ready. Confirm the invitation details.")}catch(W){E(ws(W,"Unable to review this invitation.")),q("")}finally{D(!1)}}},Ie=async()=>{if(p){D(!0),E(""),q("Creating invitation…");try{const W=await wR({...Wg(o,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest});N(W),q("Invitation created.")}catch(W){W instanceof Error&&W.message==="reviewed_onboarding_stale"&&f(null),E(ws(W,"Unable to create this invitation.")),q("")}finally{D(!1)}}},le=async()=>{const W=H.current.trim(),de=M.current;if(!W){E("Paste an invitation first.");return}const ne=()=>M.current===de&&H.current.trim()===W;D(!0),E(""),q("Reviewing invitation…");try{const xe=await bm(W);if(!ne())return;v(xe),xe.kind==="team_member"?R(kd(xe.recipient_name)):xe.kind==="project_share_invite"&&(T(kd(xe.recipient_name)),O(kd(xe.device_name))),q(xe.kind==="add_device"?(xe.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.":xe.kind==="team_member"?"Review ready. Confirm before accepting.":xe.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced, then Sync, to review and import this legacy invitation.")}catch(xe){if(!ne())return;E(ws(xe,"Unable to review this invitation.")),q("")}finally{D(!1)}},ve=async()=>{if(!(L||U.current||b)&&!(!m||m.kind==="legacy_team_invite")&&!(m.kind==="project_share_invite"&&!(m.projects?.length??0))&&!(m.kind==="project_share_invite"&&(Ei(I,"Identity display name")||Ei(A,"Device display name")))&&!(m.kind==="team_member"&&Ei(_,"Identity display name"))){U.current=!0,D(!0),E(""),q("Accepting invitation…");try{const W=m.kind==="project_share_invite"?await kl(d.trim(),{recipient_name:I.trim(),device_name:A.trim()},m.kind):await kl(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(vT(W)),q("");else{const de=m.kind,ne=W.restart_required===!0||W.setup_state==="restart_required";w({kind:de,restartRequired:ne,detail:de==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:de==="add_device"&&(m.onboarding?.projects?.length??0)>0}),q("")}}catch(W){U.current=!1;const de=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(ws(W,de)),q("")}finally{D(!1)}}},X=async()=>{const W=F?.invite.link||F?.invite.encoded||"";if(!W){E("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(W),q("Invitation copied.")}catch{E("Unable to copy the invitation.")}},ce=m?.kind==="team_member"||m?.kind==="add_device"?m.onboarding:null,be=m?.kind==="project_share_invite"?m:null,fe=m?.kind==="team_member"?Ei(_,"Identity display name"):"",We=be?Ei(I,"Identity display name"):"",he=be?Ei(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=>{ue("team_member"),oe("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=>{ue("add_device"),oe("create",W.currentTarget)},type:"button",children:"Add a device"}),a("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>_s(),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=>oe("accept",W.currentTarget),type:"button",children:"Review invitation"}),a("p",{className:"small",children:"Legacy invitation import remains under Advanced, in Sync."})]}),r?a(Qn,{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||ie()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:a("div",{"aria-busy":L,className:"modal-card sync-dialog-card",children:[a("div",{className:"modal-header",children:[a("h2",{id:"recipient-invitation-title",tabIndex:-1,children:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),a(kr,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:L,onClick:ie})]}),a("div",{className:"modal-body",children:[a("p",{className:"small",id:"recipient-invitation-description",children:b?"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&&!b?a("label",{className:"field",htmlFor:"recipient-invitation-value",children:[a("span",{children:"Invitation"}),a("textarea",{id:"recipient-invitation-value",onInput:W=>{se(W.currentTarget.value),v(null),h(null),q(""),E("")},rows:5,value:d})]}):null,p?a(zg,{preview:p}):null,ce&&!b?a(zg,{preview:ce}):null,m?.kind==="team_member"&&!b?a(wT,{error:fe,name:_,onChange:W=>{R(W),E("")}}):null,be&&!g?a(ST,{deviceName:A,deviceNameError:he,invite:be,onDeviceNameChange:W=>{O(W),E("")},onRecipientNameChange:W=>{T(W),E("")},recipientName:I,recipientNameError:We}):null,g?a(CT,{result:g}):null,b?a(RT,{result:b}):null,F?a("div",{children:[a("p",{children:"Share the invitation with the recipient."}),a("button",{className:"settings-button",onClick:()=>{X()},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:G}),$?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:L,onClick:ie,type:"button",children:F||g||b?"Done":"Cancel"}),r==="create"&&!F?a("button",{className:"settings-button sync-dialog-confirm",disabled:L||!c,onClick:()=>{p?Ie():Pe()},type:"button",children:L?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!m&&!b?a("button",{className:"settings-button sync-dialog-confirm",disabled:L,onClick:()=>{le()},type:"button",children:L?"Reviewing…":"Review invitation"}):ce&&!b||be&&!g?a("button",{className:"settings-button sync-dialog-confirm",disabled:L||!!(m?.kind==="team_member"&&fe)||!!(be&&(!be.projects?.length||We||he)),onClick:()=>{ve()},type:"button",children:L?"Accepting…":be?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}function kT(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.":Id(t)?"Enter a human-readable Team name.":"":"Team name is required."}function TT(e){return e instanceof Ka?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 PT({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=zC,teamId:o}){const[s,c]=x(!1),[l,d]=x(n),[u,p]=x(!1),[f,m]=x(""),[v,g]=x(""),h=B(null),b=B(null),w=B(null);V(()=>{v&&!u&&w.current?.focus()},[u,v]);const _=()=>{u||(c(!1),m(""),g(""))},R=async()=>{const I=kT(l);if(I){m(I);return}if(!u){p(!0),m(""),g("");try{const T=await i({teamId:o,displayName:l,expectedDisplayName:n});d(T.displayName),g(`Team renamed to ${T.displayName}.`);try{await r?.()===!1&&g(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}catch{g(`Team renamed to ${T.displayName}, but Sharing could not refresh.`)}}catch(T){m(TT(T))}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(Qn,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:I=>{I.preventDefault(),h.current?.focus()},onEscapeKeyDown:I=>{u&&I.preventDefault()},onInteractOutside:I=>{u&&I.preventDefault()},onOpenAutoFocus:I=>{I.preventDefault(),b.current?.focus(),b.current?.select()},onOpenChange:I=>{I||_()},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(kr,{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:I=>{d(I.currentTarget.value),m("")},ref:b,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:()=>{R()},type:"button",children:u?"Saving…":f?"Try again":"Save"})]})]})})]})}var Jg={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Yg={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},Td={role:"list"},Pd={role:"listitem"};function NT(e){return typeof e=="string"&&Object.hasOwn(Jg,e)?Jg[e]:"Ready to review"}function ET(e){return typeof e=="string"&&Object.hasOwn(Yg,e)?Yg[e]:"needs_attention"}function AT(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 xT({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=AT(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",{...Td,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:n.map(r=>y("li",{...Pd,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=`${Jt(i.deviceCount,"device")}, ${Jt(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 ${ET(i.status)}`.trim(),children:NT(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 Er=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Jt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function DT(e,t){return e.length?e.join(", "):t}var Xg=3;function Nd({empty:e,label:t,names:n}){return n.length===0?a(z,{children:e}):n.length<=Xg?a(z,{children:DT(n,e)}):a(z,{children:[n.slice(0,Xg).join(", "),a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-name-details",children:[a("summary",{children:["View all ",Jt(n.length,t)]}),a("ul",{...Td,"aria-label":`All ${t}s`,children:n.map((r,i)=>y("li",{...Pd,key:`${i}-${r}`},r))})]})]})}function Qg(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var Zg=3;function ev({empty:e,identities:t,qualifier:n}){if(t.length===0)return a(z,{children:e});const r=Kk(t),i=s=>s.identityCount>1?`${s.displayName} (${Jt(s.identityCount,"identity","identities")})`:s.displayName,o=r.slice(0,Zg);return a(z,{children:[Jt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",o.map(i).join(", "),r.length>Zg?a(z,{children:[a("span",{"aria-hidden":"true",children:", …"}),a("details",{className:"recipient-policy-sharing-project-details",children:[a("summary",{children:["View all ",Jt(r.length,"Project name group")]}),a("ul",{...Td,"aria-label":`All ${n} Project identity groups`,children:r.map(s=>y("li",{...Pd,key:s.displayName},i(s)))})]})]}):null]})}function tv({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{xo({mode:"recipient-manage",recipient:r})},o=()=>{xo({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 LT({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=Qg(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:[Jt(p.length,"active member")," —"," ",a(Nd,{empty:"No active members",label:"member",names:p})]})]}),a("div",{children:[a("dt",{children:"Registered devices"}),a("dd",{children:Jt(f,"active registered device")})]}),a("div",{children:[a("dt",{children:"Shared projects"}),a("dd",{children:a(ev,{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(tv,{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(PT,{descriptionId:g,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function $T({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=Qg(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:[Jt(l.length,"active registered device")," —"," ",a(Nd,{empty:"No active devices",label:"device",names:l.map(m=>m.displayName)})]})]}),a("div",{children:[a("dt",{children:"Team memberships"}),a("dd",{children:[Jt(d.length,"active Team membership")," —"," ",a(Nd,{empty:"No active Team memberships",label:"Team membership",names:d})]})]}),a("div",{children:[a("dt",{children:"Directly shared projects"}),a("dd",{children:a(ev,{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(tv,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function OT({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:Jt(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 jT({intent:e,options:t,projects:n}){const[r,i]=x(()=>e.teams.some(m=>m.status==="active")?"teams":"identities"),o=B(t.loading===!0||t.loadError===!0),s=B([]),c=Gg(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(m=>m.status==="active");V(()=>{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=Er[m];v&&(i(v.id),s.current[m]?.focus())},f=(m,v)=>{let g=null;m.key==="ArrowRight"?g=(v+1)%Er.length:m.key==="ArrowLeft"?g=(v-1+Er.length)%Er.length:m.key==="Home"?g=0:m.key==="End"&&(g=Er.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(xT,{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:Er.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))}),Er.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(Ug,{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(LT,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):m.id==="identities"?a($T,{disableMutations:t.refreshError===!0,intent:e,projects:n}):m.id==="received"?a(OT,{received:t.received??[]}):a(IT,{intent:e})})},m.id))]})}function MT(e,t,n,r={}){Ue(a(jT,{intent:n,options:r,projects:t}),e)}var Ed={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function FT(){const e=[];let t=0;for(;;){const n=await bo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:ys(e),received:aT(e)}}var BT={loadDeviceInventory:Al,loadIntent:El,loadProjects:FT,loadSyncStatus:Il,loadTeamSetupSummary:Tm,mountManagement:qg,mountSharing:MT};function qT(e={},t={}){const n={...BT,...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 b=document.getElementById("recipientPolicySharingMount");if(!b){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(b,E?.inventory.manageable??[],E?.intent??Ed,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 R=Promise.resolve().then(()=>n.loadTeamSetupSummary()).then(E=>(g!==r||(c=E,l=!1,d=!1,_()),!0),()=>(g!==r||(l=!1,d=!0,_()),!1)),[I,T,A,O]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(g!==r)return h.requireTeamSetupSummary?(await R,!1):i??!1;const F=A.status==="rejected";A.status==="fulfilled"&&(s=A.value),O.status==="fulfilled"&&(o=Om(O.value));let N,L,D;const G=I.status==="fulfilled"&&T.status==="fulfilled";if(u=!G,p=F,G){const E=I.value,S=T.value;f={intent:S,inventory:E},N=E.manageable,L=S,D={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;N=E.inventory.manageable,L=E.intent,D={coordinatorEnrollmentIssueCount:o,deviceInventory:s,deviceInventoryUnavailable:F,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>m({requireTeamSetupSummary:!0}),received:E.inventory.received,refreshError:!0}}else N=[],L=Ed,D={deviceInventoryUnavailable:F,loadError:!0};const q=()=>{n.mountSharing(b,N,L,{...D,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if(q(),_=q,!G&&w&&n.mountManagement(w,[],Ed,{loadError:!0}),!h.requireTeamSetupSummary)return G;const $=await R;return g!==r?!1:G&&$}return m}var nv=["info","warning","error"],rv=["viewer","observer","capture","sync","storage","maintenance"],UT=["#health","#advanced/sync/diagnostics"],GT=100,HT=128,VT=64,KT=128,zT=2e3,iv=256,WT=2e3,JT=2e3,YT=2048,ov=class extends Error{status;constructor(e,t){super(`Diagnostics request failed: ${e} ${t}`),this.status=e,this.name="DiagnosticEventsRequestError"}};function XT(e){const t=new URLSearchParams;return typeof e.limit=="number"&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.severity?.length&&t.set("severity",e.severity.join(",")),e.subsystem?.length&&t.set("subsystem",e.subsystem.join(",")),t.set("includeTechnical",e.includeTechnical?"1":"0"),t.toString()}function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ss(e,t){return Object.keys(e).every(n=>t.includes(n))}function En(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function av(e){return En(e,VT)&&Number.isFinite(Date.parse(e))}function Ad(e){return typeof e=="string"&&UT.includes(e)}function QT(e){return!$o(e)||!Ss(e,["label","href","command"])||!En(e.label,iv)||e.href!==void 0&&!Ad(e.href)?!1:e.command===void 0||En(e.command,WT)}function ZT(e){return!$o(e)||!Ss(e,["kind","label"])||!En(e.label,iv)?!1:e.kind==="session"||e.kind==="device"||e.kind==="operation"}function eP(e){return!$o(e)||!Ss(e,["available","text"])||typeof e.available!="boolean"?!1:e.text===void 0?!0:e.available&&En(e.text,JT)}function tP(e){return!$o(e)||!Ss(e,["id","occurred_at","severity","subsystem","code","message","recovery","correlation","technical_detail"])||!En(e.id,HT)||!av(e.occurred_at)||!nv.includes(e.severity)||!rv.includes(e.subsystem)||!En(e.code,KT)||!En(e.message,zT)||e.recovery!==void 0&&!QT(e.recovery)||e.correlation!==void 0&&!ZT(e.correlation)?!1:e.technical_detail===void 0||eP(e.technical_detail)}function nP(e){if(!$o(e)||e.contract_version!==1||!Array.isArray(e.items)||e.items.length>GT)return null;let t=null;if(e.next_cursor!==null){if(!En(e.next_cursor,YT))return null;t=e.next_cursor}return e.redacted!==!0||!av(e.generated_at)?null:{contract_version:1,items:e.items.filter(tP),next_cursor:t,redacted:e.redacted,generated_at:e.generated_at}}async function rP(e={}){const t=XT(e),n=await fetch(`/api/diagnostics/events?${t}`,{cache:"no-store",method:"GET",signal:e.signal});if(!n.ok)throw new ov(n.status,n.statusText);const r=nP(await n.json());if(!r)throw new Error("Unsupported diagnostics response");return r}var B2=20,sv={connection_lost:{code:"viewer_connection_lost",message:"The viewer connection was interrupted. Automatic recovery started.",severity:"warning",subsystem:"viewer"},reconnect_requested:{code:"viewer_reconnect_requested",message:"A viewer reconnection check was requested.",severity:"info",subsystem:"viewer"},connection_restored:{code:"viewer_connection_restored",message:"The viewer connection and page data were restored.",severity:"info",subsystem:"viewer"}},Cs=!1,iP=0,Rs=[],xd=new Set;function Dd(){return[...Rs]}function Ld(e){if(!Object.hasOwn(sv,e))return;const t=sv[e];if(e==="connection_lost"&&Cs||e==="reconnect_requested"&&Rs[0]?.code===t.code||e==="connection_restored"&&!Cs)return;const n=new Date().toISOString(),r={id:`viewer-session-${Date.now()}-${++iP}`,occurred_at:n,...t};Rs=[r,...Rs].slice(0,20),e==="connection_lost"&&(Cs=!0),e==="connection_restored"&&(Cs=!1);for(const i of xd)i(r)}function oP(e){return xd.add(e),()=>xd.delete(e)}var q2=200;function $d(){return{open:!1,severity:"",subsystem:"",includeTechnical:!1,paused:!1,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",hiddenSessionIds:[],queryRevision:0,pollRevision:0}}function Od(e){return xt([...e.sessionRows,...e.rows].filter(t=>cv(e,t)).sort((t,n)=>Date.parse(n.occurred_at)-Date.parse(t.occurred_at)))}function cv(e,t){return e.severity&&t.severity!==e.severity?!1:!e.subsystem||t.subsystem===e.subsystem}function aP(e){const t=e.queuedSessionRows.filter(n=>cv(e,n));return e.queuedRows.length+t.length}function xt(e,t=200){const n=new Set;return e.filter(r=>n.has(r.id)||n.size>=t?!1:(n.add(r.id),!0))}function sP(e,t,n){const r=t==="older"&&n;return{...e,includeTechnical:t==="technical"?!1:e.includeTechnical,nextCursor:r?null:e.nextCursor,loading:!1,error:!0,announcement:"",queryRevision:r?e.queryRevision+1:e.queryRevision}}function jd(e,t){return{...e,...t,rows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"",copyStatus:"",queryRevision:e.queryRevision+1}}function Md(e,t,n){return t?n?{...t,occurred_at:e.occurred_at}:t:e}function cP(e,t,n){const r=new Map(t.items.map(p=>[p.id,p])),i=new Map(e.rows.map(p=>[p.id,p])),o=t.items.filter(p=>!i.has(p.id));if(!e.rows.length)return{...e,rows:t.items.slice(0,200),queuedNextCursor:void 0,nextCursor:t.next_cursor};if(!n){const p=xt([...t.items,...e.rows]);return{...e,rows:p,queuedRows:[],queuedNextCursor:void 0,nextCursor:t.next_cursor}}const s=t.items.filter(p=>{const f=i.get(p.id);return f!==void 0&&f.occurred_at!==p.occurred_at}),c=xt([...o,...s]),l=new Set(c.map(p=>p.id)),d=e.rows.map(p=>Md(p,r.get(p.id),l.has(p.id))),u=xt([...c,...e.queuedRows]);return{...e,rows:d,queuedRows:u,queuedNextCursor:t.next_cursor,announcement:u.length>0?`${u.length} new diagnostic events are waiting.`:""}}function lP(e,t){const n={...e,generatedAt:t.response.generated_at,loading:!1,error:!1,announcement:""};if(t.mode==="replace")return{...n,rows:t.response.items.slice(0,200),queuedRows:[],queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="older")return{...n,rows:xt([...e.rows,...t.response.items]),queuedNextCursor:e.queuedRows.length?e.queuedNextCursor:void 0,nextCursor:t.response.next_cursor};if(t.mode==="technical"){const r=new Map(t.response.items.map(i=>[i.id,i]));return{...n,rows:e.rows.map(i=>Md(i,r.get(i.id),!0)),queuedRows:e.queuedRows.map(i=>Md(i,r.get(i.id),!0)),nextCursor:e.nextCursor}}return cP(n,t.response,t.readingOlder)}function dP(e,t){return t.type==="open"?{...$d(),open:!0,severity:t.severity,subsystem:t.subsystem,sessionRows:t.sessionRows,queryRevision:e.queryRevision+1}:t.type==="close"?$d():t.type==="set_severity"?jd(e,{severity:t.severity}):t.type==="set_subsystem"?jd(e,{subsystem:t.subsystem}):t.type==="reset_filters"?jd(e,{severity:"",subsystem:""}):t.type==="set_paused"?{...e,loading:t.paused?!1:e.loading,paused:t.paused,pollRevision:t.paused?e.pollRevision:e.pollRevision+1}:t.type==="reveal_technical"?{...e,includeTechnical:!0}:null}function uP(e,t){return t.type==="request_started"?{...e,loading:t.mode!=="poll"}:t.type==="request_succeeded"?lP(e,t):t.type==="request_failed"?sP(e,t.mode,t.restartQuery):null}function lv(e,t,n=!1){if(e.paused||!e.open)return e;const r=t.filter(s=>!e.hiddenSessionIds.includes(s.id));if(!n)return{...e,sessionRows:xt([...r,...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[]};const i=new Set(e.sessionRows.map(s=>s.id)),o=xt([...r.filter(s=>!i.has(s.id)),...e.queuedSessionRows],20);return{...e,queuedSessionRows:o}}function pP(e,t){if(t.type==="session_event_recorded")return lv(e,[t.event],t.readingOlder);if(t.type==="refresh_session_rows")return lv(e,t.events,t.readingOlder);if(t.type==="clear_view"){const n=[...new Set([...t.sessionEvents.map(r=>r.id),...e.queuedSessionRows.map(r=>r.id),...e.sessionRows.map(r=>r.id),...e.hiddenSessionIds])].slice(0,20);return{...e,rows:[],sessionRows:[],queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:null,generatedAt:null,loading:!1,error:!1,announcement:"Diagnostics view cleared.",copyStatus:"",hiddenSessionIds:n}}return t.type==="set_copy_status"?{...e,copyStatus:t.status}:t.type!=="show_queued"?null:fP(e)}function fP(e){const t=xt([...e.queuedRows,...e.rows],201),n=t.length>200&&e.queuedNextCursor!==void 0;return{...e,rows:t.slice(0,200),sessionRows:xt([...e.queuedSessionRows,...e.sessionRows],20),queuedSessionRows:[],queuedRows:[],queuedNextCursor:void 0,nextCursor:n?e.queuedNextCursor:e.nextCursor,announcement:""}}function mP(e,t){const n=dP(e,t);if(n)return n;const r=uP(e,t);return r||(pP(e,t)??e)}var hP=Math.ceil(200/50);async function gP(e){const t=new Map(e.existingRows.map(o=>[o.id,o.occurred_at]));let n=e.request,r=null,i=0;for(;;){const o=await e.loadEvents(n);i+=1;const s=xt([...r?.items??[],...o.items]);r={...o,items:s};const c=o.items.some(l=>t.get(l.id)===l.occurred_at);if(t.size===0||c){const l=xt([...s,...e.existingRows],201),d=c&&l.length<=200;return{...r,next_cursor:d?e.existingNextCursor:o.next_cursor}}if(!o.next_cursor||s.length>=200||i>=hP)return r;n={...e.request,cursor:o.next_cursor,limit:Math.min(50,200-s.length)}}}async function vP(e){const t=new Set(e.existingRows.map(o=>o.id));let n=e.request,r=null,i=0;for(;;){const o=await e.loadEvents(n);i+=1;const s=xt([...r?.items??[],...o.items]);r={...o,items:s};const c=new Set(s.map(l=>l.id));if([...t].every(l=>c.has(l)))return r;if(!o.next_cursor||s.length>=200||i*50>=200)throw new Error("Technical diagnostic history could not be refreshed completely.");n={...e.request,cursor:o.next_cursor,limit:Math.min(50,200-s.length)}}}function yP(e,t,n){const r=200-Od(t).length;return{limit:e==="older"?Math.max(1,Math.min(50,r)):50,cursor:e==="older"?t.nextCursor??void 0:void 0,severity:t.severity?[t.severity]:void 0,subsystem:t.subsystem?[t.subsystem]:void 0,includeTechnical:t.includeTechnical,signal:n}}function bP(e,t,n,r){const i=yP(t,n,r);return t==="technical"?vP({loadEvents:e,request:i,existingRows:xt([...n.queuedRows,...n.rows],n.queuedRows.length+n.rows.length)}):t!=="poll"?e(i):gP({loadEvents:e,request:i,existingRows:n.rows,existingNextCursor:n.nextCursor})}function _P(e,t){return e==="older"&&t instanceof ov&&t.status===400}function Fd(e){return e.current!==null&&e.current.scrollTop>24}function wP(e){return e instanceof DOMException&&e.name==="AbortError"}var SP=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function dv(e){if(!e?.isConnected||!e.matches(SP)||e.matches(':disabled, [aria-disabled="true"]'))return!1;let t=e;for(;t;){if(t.hidden||t.inert||t.hasAttribute("inert")||t.getAttribute("aria-hidden")==="true")return!1;const n=getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse"||n.opacity==="0")return!1;t=t.parentElement}return!0}function CP(){const e=document.querySelector('.tab-btn[aria-current="page"]');return dv(e)?e:null}function RP(e){const t=e==="#health"?"health":"advanced";return document.getElementById(`tabBtn-${t}`)}function IP(e,t,n){if(e.preventDefault(),n.current){n.current=!1,t.current=null;return}const r=t.current;dv(r)?r.focus():CP()?.focus(),t.current=null}function kP(e){const{dispatch:t,abortRequest:n,openerRef:r,recoveryNavigationRef:i}=e;return{open(o={}){n(),i.current=!1,r.current=o.trigger??document.activeElement,t({type:"open",severity:o.severity??"",subsystem:o.subsystem??"",sessionRows:Dd()})},close(){n(),t({type:"close"})},navigateToRecovery(o){n(),i.current=!0,t({type:"close"}),queueMicrotask(()=>{window.location.hash=o,setTimeout(()=>RP(o)?.focus(),0)})},restoreFocus(o){IP(o,r,i)}}}function TP(e){const{state:t,dispatch:n,abortRequest:r}=e;return{setSeverity(i){r(),n({type:"set_severity",severity:i})},setSubsystem(i){r(),n({type:"set_subsystem",subsystem:i})},resetFilters(){r(),n({type:"reset_filters"})},togglePaused(){t.paused||r(),n({type:"set_paused",paused:!t.paused})},revealTechnical(){r(),n({type:"reveal_technical"})}}}async function PP(e,t){if(!globalThis.confirm("Copied diagnostics may contain sensitive operational context. Copy the visible redacted events?"))return;const n=AP(Od(e));try{await navigator.clipboard.writeText(n),t({type:"set_copy_status",status:"Visible redacted events copied."})}catch{t({type:"set_copy_status",status:"Visible events could not be copied. Check clipboard permission and try again."})}}function NP(e){const{state:t,dispatch:n,abortRequest:r,listRef:i}=e;return{showQueued(){n({type:"show_queued"}),i.current&&(i.current.scrollTop=0)},clearView(){r(),n({type:"clear_view",sessionEvents:Dd()})},copyVisibleEvents:()=>PP(t,n)}}function EP(e){return{...kP(e),refresh:()=>e.runRequest("poll"),retry:()=>e.runRequest(e.state.rows.length>0?"poll":"replace","retry"),loadOlder:()=>e.runRequest("older"),...TP(e),...NP(e)}}function AP(e){return JSON.stringify(e.map(t=>{const n=Ad(t.recovery?.href)||!!t.recovery?.command;return{occurred_at:t.occurred_at,severity:t.severity,subsystem:t.subsystem,code:t.code,message:t.message,...n?{recovery_label:t.recovery?.label}:{},...t.correlation?.label?{correlation_label:t.correlation.label}:{}}}),null,2)}function xP(e){const t=B(e),n=B(null),r=B(0);return t.current=e,{stateRef:t,requestRef:n,generationRef:r}}function DP(e,t){const n=B(t);n.current=t,V(()=>{e.open&&n.current("replace")},[e.open,e.queryRevision]),V(()=>{!e.open||e.pollRevision===0||n.current("poll")},[e.open,e.pollRevision]),V(()=>{!e.open||!e.includeTechnical||n.current("technical")},[e.includeTechnical,e.open])}function LP(e){const{state:t,dispatch:n,loadEvents:r,listRef:i}=e,{stateRef:o,requestRef:s,generationRef:c}=xP(t);function l(){c.current+=1,s.current?.controller.abort(),s.current=null}function d(p,f){const m=o.current;return m.open?p!=="poll"?!1:s.current!==null?!0:f==="retry"?!1:m.paused||document.visibilityState==="hidden":!0}async function u(p,f="routine"){if(d(p,f))return;n({type:"refresh_session_rows",events:Dd(),readingOlder:Fd(i)});const m=new AbortController;s.current?.controller.abort();const v=++c.current;s.current={controller:m,generation:v},n({type:"request_started",mode:p});try{const g=o.current,h=await bP(r,p,g,m.signal);if(v!==c.current)return;n({type:"request_succeeded",mode:p,response:h,readingOlder:Fd(i)})}catch(g){if(v!==c.current||wP(g))return;n({type:"request_failed",mode:p,restartQuery:_P(p,g)})}finally{v===c.current&&(s.current=null)}}return DP(t,u),{abortRequest:l,runRequest:u}}function $P(e){const[t,n]=In(mP,$d()),r=B(null),i=B(!1),o=B(null),{abortRequest:s,runRequest:c}=LP({state:t,dispatch:n,loadEvents:e,listRef:o});V(()=>oP(d=>{n({type:"session_event_recorded",event:d,readingOlder:Fd(o)})}),[]);const l=EP({state:t,dispatch:n,abortRequest:s,runRequest:c,openerRef:r,recoveryNavigationRef:i,listRef:o});return{state:t,visibleRows:Od(t),listRef:o,...l}}function Bd(e){return e==="error"?{icon:"×",label:"Error"}:e==="warning"?{icon:"!",label:"Warning"}:{icon:"i",label:"Info"}}function OP({event:e,includeTechnical:t,onRecoveryNavigation:n}){const r=Bd(e.severity),i=e.recovery?.href;return a("li",{className:`diagnostics-event diagnostics-event--${e.severity}`,children:[a("div",{className:"diagnostics-event-heading",children:[a("span",{className:"diagnostics-severity",children:[a("span",{"aria-hidden":"true",className:"diagnostics-severity-icon",children:r.icon}),r.label]}),a("time",{dateTime:e.occurred_at,children:new Date(e.occurred_at).toLocaleString()})]}),a("div",{className:"diagnostics-event-context",children:[a("span",{children:e.subsystem}),a("code",{children:e.code})]}),a("p",{children:e.message}),e.correlation?a("div",{className:"diagnostics-event-meta",children:[e.correlation.kind,": ",e.correlation.label]}):null,t&&e.technical_detail?.text?a("details",{className:"diagnostics-technical-detail",children:[a("summary",{children:"Technical detail"}),a("pre",{children:e.technical_detail.text})]}):null,Ad(i)?a("a",{className:"diagnostics-recovery",href:i,onClick:o=>{o.preventDefault(),n(i)},children:e.recovery?.label}):null,e.recovery?.command?a("div",{className:"diagnostics-recovery-command",children:[a("span",{children:e.recovery.label}),a("code",{children:e.recovery.command})]}):null]})}function jP(){return a("div",{"aria-busy":"true","aria-label":"Loading diagnostics",className:"diagnostics-loading",role:"status",children:["first","second","third"].map(e=>a("div",{className:"diagnostics-loading-row",children:[a("span",{}),a("span",{}),a("span",{})]},e))})}function MP({controller:e}){const{state:t}=e;return a(z,{children:[a("div",{className:"diagnostics-controls",children:[a("label",{children:[a("span",{children:"Severity"}),a("select",{"aria-label":"Diagnostic severity",onChange:n=>e.setSeverity(n.currentTarget.value),value:t.severity,children:[a("option",{value:"",children:"All severities"}),nv.map(n=>a("option",{value:n,children:Bd(n).label},n))]})]}),a("label",{children:[a("span",{children:"Subsystem"}),a("select",{"aria-label":"Diagnostic subsystem",onChange:n=>e.setSubsystem(n.currentTarget.value),value:t.subsystem,children:[a("option",{value:"",children:"All subsystems"}),rv.map(n=>a("option",{value:n,children:n},n))]})]}),a("button",{className:"settings-button",onClick:e.togglePaused,type:"button",children:t.paused?"Resume updates":"Pause updates"})]}),a("div",{className:"diagnostics-secondary-controls",children:[a("div",{className:"diagnostics-secondary-actions",children:[a("button",{className:"settings-button",disabled:t.includeTechnical||t.loading,onClick:e.revealTechnical,type:"button",children:t.includeTechnical?"Technical details shown":"Reveal technical details"}),a("button",{className:"settings-button",onClick:e.clearView,type:"button",children:"Clear view"}),a("button",{className:"settings-button",disabled:!e.visibleRows.length,onClick:()=>{e.copyVisibleEvents()},type:"button",children:"Copy visible redacted events"})]}),a("span",{className:"diagnostics-generated-at",children:t.generatedAt?`Generated ${new Date(t.generatedAt).toLocaleTimeString()}`:"Not loaded yet"})]})]})}function FP({controller:e}){const{state:t}=e,n=aP(t),r=t.error&&t.rows.length?"Showing stale events.":"";return a(z,{children:[a("div",{"aria-atomic":"true","aria-live":"polite",className:"sr-only",children:t.announcement}),a("div",{"aria-atomic":"true","aria-live":"polite",className:"diagnostics-copy-status",children:t.copyStatus}),t.subsystem||t.severity?a("div",{className:"diagnostics-filter-context",children:["Showing"," ",t.severity?`${Bd(t.severity).label.toLowerCase()} `:"",t.subsystem?`${t.subsystem} `:"","events from the recent retained window."]}):null,t.paused?a("div",{className:"diagnostics-notice",role:"status",children:"Updates are paused. Resume when you are ready to fetch newer events."}):null,t.error?a("div",{className:"diagnostics-notice diagnostics-notice--error",role:"alert",children:[a("span",{children:["Diagnostics could not be refreshed. ",r]}),a("button",{className:"settings-button",onClick:()=>{e.retry()},type:"button",children:"Retry"})]}):null,n?a("button",{className:"diagnostics-new-events",onClick:e.showQueued,type:"button",children:["Show ",n," new ",n===1?"event":"events"]}):null]})}function BP({controller:e}){const{state:t}=e,n=e.visibleRows,r=!!(t.severity||t.subsystem),i=!!t.nextCursor&&n.length<200&&!t.loading;return a("div",{className:"diagnostics-event-list",ref:e.listRef,children:[t.loading&&!n.length?a(jP,{}):null,!t.loading&&!t.error&&!n.length?a("div",{className:"diagnostics-empty",children:[a("p",{children:"No events match the recent retained window."}),r?a("button",{className:"settings-button",onClick:e.resetFilters,type:"button",children:"Reset filters"}):null]}):null,n.length?a("ul",{"aria-label":"Diagnostic events",children:n.map(o=>a(OP,{event:o,includeTechnical:t.includeTechnical,onRecoveryNavigation:e.navigateToRecovery},o.id))}):null,i?a("button",{className:"settings-button diagnostics-load-older",onClick:()=>{e.loadOlder()},type:"button",children:"Load older"}):null,n.length>=200?a("div",{className:"diagnostics-limit-note",children:["Showing the newest ",200," events."]}):null]})}function qP({controller:e}){return a(Qn,{ariaDescribedby:"diagnosticsDrawerDescription",ariaLabelledby:"diagnosticsDrawerTitle",contentClassName:"diagnostics-drawer",contentId:"diagnosticsDrawer",onCloseAutoFocus:e.restoreFocus,onOpenAutoFocus:t=>{t.preventDefault(),document.getElementById("diagnosticsDrawerTitle")?.focus()},onOpenChange:t=>{t||e.close()},open:e.state.open,overlayClassName:"diagnostics-drawer-overlay",overlayId:"diagnosticsDrawerOverlay",children:[a("header",{className:"diagnostics-drawer-header",children:[a("div",{children:[a(Dg,{id:"diagnosticsDrawerTitle",tabIndex:-1,children:"Diagnostics"}),a("p",{id:"diagnosticsDrawerDescription",children:"Recent redacted operational events. Filters apply only to this drawer."})]}),a(kr,{ariaLabel:"Close diagnostics",onClick:e.close})]}),a(MP,{controller:e}),a(FP,{controller:e}),a(BP,{controller:e})]})}var Ai=null;function UP({dependencies:e}){const t=$P(e.loadEvents??rP);return V(()=>{const n={open:t.open,refresh:t.refresh,close:t.close};return Ai=n,()=>{Ai===n&&(Ai=null)}},[t.open,t.refresh,t.close]),a(qP,{controller:t})}function GP(e,t={}){Ue(a(UP,{dependencies:t}),e)}function Ar(e={}){Ai?.open(e)}function uv(e){Ai?.close(),e&&queueMicrotask(e)}async function HP(){await Ai?.refresh()}function VP(){document.getElementById("healthOpenDiagnostics")?.addEventListener("click",e=>{Ar({trigger:e.currentTarget})}),document.getElementById("syncOpenDiagnostics")?.addEventListener("click",e=>{Ar({subsystem:"sync",trigger:e.currentTarget})}),document.getElementById("viewerReconnectDiagnostics")?.addEventListener("click",e=>{Ar({subsystem:"viewer",trigger:e.currentTarget})})}var KP=Symbol.for("preact-signals");function Is(){if(An>1)An--;else{var e,t=!1;for((function(){var i=Ps;for(Ps=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}})();jo!==void 0;){var n=jo;for(jo=void 0,Ts++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&fv(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(Ts=0,An--,t)throw e}}function zP(e){if(An>0)return e();qd=++WP,An++;try{return e()}finally{Is()}}var Oo,Ve=void 0;function ks(e){var t=Ve,n=Oo;Ve=void 0,Oo=void 0;try{return e()}finally{Ve=t,Oo=n}}var jo=void 0,An=0,Ts=0,WP=0,qd=0,Ps=void 0,Ns=0;function pv(e){if(Ve!==void 0){var t=e.n;if(t===void 0||t.t!==Ve)return t={i:0,S:e,p:Ve.s,n:void 0,t:Ve,e:void 0,x:void 0,r:t},Ve.s!==void 0&&(Ve.s.n=t),Ve.s=t,e.n=t,32&Ve.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=Ve.s,t.n=void 0,Ve.s.n=t,Ve.s=t),t}}function pt(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}pt.prototype.brand=KP,pt.prototype.h=function(){return!0},pt.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:ks(function(){var r;(r=t.W)==null||r.call(t)}))},pt.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&&ks(function(){var i;(i=t.Z)==null||i.call(t)}))}},pt.prototype.subscribe=function(e){var t=this;return Mo(function(){var n=t.value;ks(function(){return e(n)})},{name:"sub"})},pt.prototype.valueOf=function(){return this.value},pt.prototype.toString=function(){return this.value+""},pt.prototype.toJSON=function(){return this.value},pt.prototype.peek=function(){var e=this;return ks(function(){return e.value})},Object.defineProperty(pt.prototype,"value",{get:function(){var e=pv(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(Ts>100)throw new Error("Cycle detected");(function(n){An!==0&&Ts===0&&n.l!==qd&&(n.l=qd,Ps={S:n,v:n.v,i:n.i,o:Ps})})(this),this.v=e,this.i++,Ns++,An++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Is()}}}});function Ud(e,t){return new pt(e,t)}function fv(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 mv(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 hv(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 xr(e,t){pt.call(this,void 0,t),this.x=e,this.s=void 0,this.g=Ns-1,this.f=4}xr.prototype=new pt,xr.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Ns))return!0;if(this.g=Ns,this.f|=1,this.i>0&&!fv(this))return this.f&=-2,!0;var e=Ve;try{mv(this),Ve=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 Ve=e,hv(this),this.f&=-2,!0},xr.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)}pt.prototype.S.call(this,e)},xr.prototype.U=function(e){if(this.t!==void 0&&(pt.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)}},xr.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(xr.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=pv(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function gv(e,t){return new xr(e,t)}function vv(e){var t=e.m;if(e.m=void 0,typeof t=="function"){An++;var n=Ve;Ve=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Gd(e),r}finally{Ve=n,Is()}}}function Gd(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,vv(e)}function JP(e){if(Ve!==this)throw new Error("Out-of-order effect");hv(this),Ve=e,this.f&=-2,8&this.f&&Gd(this),Is()}function xi(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Oo&&Oo.push(this)}xi.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()}},xi.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,vv(this),mv(this),An++;var e=Ve;return Ve=this,JP.bind(this,e)},xi.prototype.N=function(){2&this.f||(this.f|=2,this.u=jo,jo=this)},xi.prototype.d=function(){this.f|=8,1&this.f||Gd(this)},xi.prototype.dispose=function(){this.d()};function Mo(e,t){var n=new xi(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var yv,Hd,Es,YP=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bv=[];Mo(function(){yv=this.N})();function Di(e,t){ge[e]=t.bind(null,ge[e]||function(){})}function As(e){if(Es){var t=Es;Es=void 0,t()}Es=e&&e.S()}function _v(e){var t=this,n=e.data,r=QP(n);r.name="ReactiveDom",r.value=n;var i=ke(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=gv(function(){var m=r.value.value;return m===0?0:m===!0?"":m||""}),u=gv(function(){return!Array.isArray(d.value)&&!Mm(d.value)}),p=Mo(function(){if(this.N=wv,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}_v.displayName="ReactiveTextNode",Object.defineProperties(pt.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:_v},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Di("__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 pt&&(n||(t.__np=n={}),n[i]=o,r[i]=o.peek())}}e(t)}),Di("__r",function(e,t){if(e(t),t.type!==z){As();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,o){var s;return Mo(function(){s=this},{name:o}),s.c=i,s})((function(i){return function(){var o;YP&&((o=this.y)==null||o.call(this)),i.__$f|=1,i.setState({})}})(r),typeof t.type=="function"?t.type.displayName||t.type.name:""))),Hd=r,As(n)}}),Di("__e",function(e,t,n,r){As(),Hd=void 0,e(t,n,r)}),Di("diffed",function(e,t){As(),Hd=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=XP(n,l,u,i),o[l]=d):d.o(u,i)}}}e(t)});function XP(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,o=Ud(n);return{o:function(s,c){o.value=s,r=c},d:Mo(function(){this.N=wv;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))})}}Di("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)}),Di("__h",function(e,t,n,r){r<3&&(t.__$f|=2),e(t,n,r)}),Mt.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 QP(e,t){return ke(function(){return Ud(e,t)},[])}var ZP=function(e){queueMicrotask(function(){queueMicrotask(e)})};function eN(){zP(function(){for(var e;e=bv.shift();)yv.call(e)})}function wv(){bv.push(this)===1&&(ge.requestAnimationFrame||ZP)(eN)}var tN=Object.defineProperty,at=(e,t)=>tN(e,"name",{value:t,configurable:!0});function Fo(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,o]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=at(g=>{const{scope:h,children:b}=g,w=B(null),_=B(new Map).current;return a(i,{scope:h,itemMap:_,collectionRef:w,children:b})},"CollectionProvider");s.displayName=t;const c=e+"CollectionSlot",l=cn(c),d=J((g,h)=>{const{scope:b,children:w}=g,_=o(c,b),R=Re(h,_.collectionRef);return a(l,{ref:R,children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",f=cn(u),m=J((g,h)=>{const{scope:b,children:w,..._}=g,R=B(null),I=Re(h,R),T=o(u,b);return V(()=>(T.itemMap.set(R,{ref:R,..._}),()=>{T.itemMap.delete(R)})),a(f,{[p]:"",ref:I,children:w})});m.displayName=u;function v(g){const h=o(e+"CollectionConsumer",g);return ae(()=>{const b=h.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(h.itemMap.values()).sort((_,R)=>w.indexOf(_.ref.current)-w.indexOf(R.ref.current))},[h.collectionRef,h.itemMap])}return at(v,"useCollection"),[{Provider:s,Slot:d,ItemSlot:m},v,r]}at(Fo,"createCollection");var Sv=new WeakMap,Vd=class _r extends Map{static{at(this,"OrderedDict")}#e;constructor(t){super(t),this.#e=[...super.keys()],Sv.set(this,!0)}set(t,n){return Sv.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=Kd(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 _r(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=xs(this.#e,t);if(n!==void 0)return this.get(n)}entryAt(t){const n=xs(this.#e,t);if(n!==void 0)return[n,this.get(n)]}indexOf(t){return this.#e.indexOf(t)}keyAt(t){return xs(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 _r(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 _r(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 _r(n)}toReversed(){const t=new _r;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 _r(n)}slice(t,n){const r=new _r;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 xs(e,t){if("at"in Array.prototype)return Array.prototype.at.call(e,t);const n=Cv(e,t);return n===-1?void 0:e[n]}at(xs,"at");function Cv(e,t){const n=e.length,r=Kd(t),i=r>=0?r:n+r;return i<0||i>=n?-1:i}at(Cv,"toSafeIndex");function Kd(e){return e!==e||e===0?0:Math.trunc(e)}at(Kd,"toSafeInteger");function nN(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,o]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new Vd,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:R,state:I}=w,T=B(null),[A,O]=x(null),F=Re(T,O),[N,L]=I;return V(()=>{if(!A)return;const D=kv(()=>{});return D.observe(A,{childList:!0,subtree:!0}),()=>{D.disconnect()}},[A]),a(i,{scope:_,itemMap:N,setItemMap:L,collectionRef:F,collectionRefObject:T,collectionElement:A,children:R})},"CollectionProviderImpl");l.displayName=t+"Impl";const d=e+"CollectionSlot",u=cn(d),p=J((w,_)=>{const{scope:R,children:I}=w,T=o(d,R),A=Re(_,T.collectionRef);return a(u,{ref:A,children:I})});p.displayName=d;const f=e+"CollectionItemSlot",m="data-radix-collection-item",v=cn(f),g=J((w,_)=>{const{scope:R,children:I,...T}=w,A=B(null),[O,F]=x(null),N=Re(_,A,F),{setItemMap:L}=o(f,R),D=B(T);Rv(D.current,T)||(D.current=T);const G=D.current;return V(()=>{const q=G;return L($=>O?$.has(O)?$.set(O,{...q,element:O}).toSorted(zd):($.set(O,{...q,element:O}),$.toSorted(zd)):$),()=>{L($=>!O||!$.has(O)?$:($.delete(O),new Vd($)))}},[O,G,L]),a(v,{[m]:"",ref:N,children:I})});g.displayName=f;function h(){return x(new Vd)}at(h,"useInitCollection");function b(w){const{itemMap:_}=o(e+"CollectionConsumer",w);return _}return at(b,"useCollection"),[{Provider:s,Slot:p,ItemSlot:g},{createCollectionScope:r,useCollection:b,useInitCollection:h}]}at(nN,"createCollection");function Rv(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(Rv,"shallowEqual");function Iv(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}at(Iv,"isElementPreceding");function zd(e,t){return!e[1].element||!t[1].element?0:Iv(e[1].element,t[1].element)?-1:1}at(zd,"sortByDocumentPosition");function kv(e){return new MutationObserver(t=>{for(const n of t)if(n.type==="childList"){e();return}})}at(kv,"getChildListObserver");var rN=Object.defineProperty,iN=(e,t)=>rN(e,"name",{value:t,configurable:!0}),Tv=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"}),Wd=J(iN(function(t,n){return a(ye.span,{...t,ref:n,style:{...Tv,...t.style}})},"VisuallyHidden")),oN=Wd,aN=Object.defineProperty,Ge=(e,t)=>aN(e,"name",{value:t,configurable:!0}),Pv="ToastProvider",[Jd,Nv,sN]=Fo("Toast"),[Ev,U2]=dt("Toast",[sN]),[cN,Ds]=Ev(Pv),lN=Ge(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=B(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Pv}\`. Expected non-empty \`string\`.`),a(Jd.Provider,{scope:t,children:a(cN,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:o,toastCount:u,viewport:l,onViewportChange:d,onToastAdd:ae(()=>p(m=>m+1),[]),onToastRemove:ae(()=>p(m=>m-1),[]),isClosePausedRef:f,announcerContainer:s,children:c})})},"ToastProvider"),dN="ToastViewport",uN=["F8"],Yd="toast.viewportPause",Xd="toast.viewportResume",pN=J(Ge(function(t,n){const{__scopeToast:r,hotkey:i=uN,label:o="Notifications ({hotkey})",...s}=t,c=Ds(dN,r),l=Nv(r),d=B(null),u=B(null),p=B(null),f=B(null),m=Re(n,f,c.onViewportChange),v=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=c.toastCount>0;V(()=>{const b=Ge(w=>{i.length!==0&&i.every(_=>w[_]||w.code===_)&&f.current?.focus()},"handleKeyDown");return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[i]),V(()=>{const b=d.current,w=f.current;if(g&&b&&w){const _=Ge(()=>{if(!c.isClosePausedRef.current){const A=new CustomEvent(Yd);w.dispatchEvent(A),c.isClosePausedRef.current=!0}},"handlePause"),R=Ge(()=>{if(c.isClosePausedRef.current){const A=new CustomEvent(Xd);w.dispatchEvent(A),c.isClosePausedRef.current=!1}},"handleResume"),I=Ge(A=>{b.contains(A.relatedTarget)||R()},"handleFocusOutResume"),T=Ge(()=>{b.contains(document.activeElement)||R()},"handlePointerLeaveResume");return b.addEventListener("focusin",_),b.addEventListener("focusout",I),b.addEventListener("pointermove",_),b.addEventListener("pointerleave",T),window.addEventListener("blur",_),window.addEventListener("focus",R),()=>{b.removeEventListener("focusin",_),b.removeEventListener("focusout",I),b.removeEventListener("pointermove",_),b.removeEventListener("pointerleave",T),window.removeEventListener("blur",_),window.removeEventListener("focus",R)}}},[g,c.isClosePausedRef]);const h=ae(({tabbingDirection:b})=>{const w=l().map(_=>{const R=_.ref.current,I=[R,...$v(R)];return b==="forwards"?I:I.reverse()});return(b==="forwards"?w.reverse():w).flat()},[l]);return V(()=>{const b=f.current;if(b){const w=Ge(_=>{const R=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!R){const I=document.activeElement,T=_.shiftKey;if(_.target===b&&T){u.current?.focus();return}const A=h({tabbingDirection:T?"backwards":"forwards"}),O=A.findIndex(F=>F===I);$s(A.slice(O+1))?_.preventDefault():T?u.current?.focus():p.current?.focus()}},"handleKeyDown");return b.addEventListener("keydown",w),()=>b.removeEventListener("keydown",w)}},[l,h]),a(BI,{ref:d,role:"region","aria-label":o.replace("{hotkey}",v),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&a(Av,{ref:u,onFocusFromOutsideViewport:()=>{$s(h({tabbingDirection:"forwards"}))}}),a(Jd.Slot,{scope:r,children:a(ye.ol,{tabIndex:-1,...s,ref:m})}),g&&a(Av,{ref:p,onFocusFromOutsideViewport:()=>{$s(h({tabbingDirection:"backwards"}))}})]})},"ToastViewport")),fN="ToastFocusProxy",Av=J(Ge(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:i,...o}=t,s=Ds(fN,r);return a(Wd,{tabIndex:0,...o,ref:n,style:{position:"fixed"},onFocus:c=>{const l=c.relatedTarget;s.viewport?.contains(l)||i()}})},"ToastFocusProxy")),Ls="Toast",mN="toast.swipeStart",hN="toast.swipeMove",gN="toast.swipeCancel",vN="toast.swipeEnd",yN=J(Ge(function(t,n){const{forceMount:r,open:i,defaultOpen:o,onOpenChange:s,...c}=t,[l,d]=At({prop:i,defaultProp:o??!0,onChange:s,caller:Ls});return a(kt,{present:r||l,children:a(wN,{open:l,...c,ref:n,onClose:()=>d(!1),onPause:ht(t.onPause),onResume:ht(t.onResume),onSwipeStart:te(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:te(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:te(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:te(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")),[bN,_N]=Ev(Ls,{onClose(){}}),wN=J(Ge(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=Ds(Ls,r),b=Nv(r),[w,_]=x(null),R=Re(n,_),I=B(null),T=B(null),A=o||h.duration,O=B(0),F=B(A),N=B(0),{onToastAdd:L,onToastRemove:D}=h,G=ht(()=>{w?.contains(document.activeElement)&&h.viewport?.focus(),c()}),q=ae(E=>{!E||E===1/0||(window.clearTimeout(N.current),O.current=new Date().getTime(),N.current=window.setTimeout(G,E))},[G]);V(()=>{const E=h.viewport;if(E){const S=Ge(()=>{q(F.current),u?.()},"handleResume"),M=Ge(()=>{const H=new Date().getTime()-O.current;F.current=F.current-H,window.clearTimeout(N.current),d?.()},"handlePause");return E.addEventListener(Yd,M),E.addEventListener(Xd,S),()=>{E.removeEventListener(Yd,M),E.removeEventListener(Xd,S)}}},[h.viewport,A,d,u,q]),V(()=>{s&&!h.isClosePausedRef.current&&q(A)},[s,A,h.isClosePausedRef,q]),V(()=>()=>{window.clearTimeout(N.current)},[]),V(()=>(L(),()=>D()),[L,D]);const $=ke(()=>w?Qd(w):null,[w]);return h.viewport?a(z,{children:[$&&a(SN,{__scopeToast:r,role:"status","aria-live":i==="foreground"?"assertive":"polite",children:$}),a(bN,{scope:r,onClose:G,children:sn(a(Jd.ItemSlot,{scope:r,children:a(FI,{asChild:!0,onEscapeKeyDown:te(l,E=>{b().some(S=>S.ref.current?.contains(E.target))||G()}),children:a(ye.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":h.swipeDirection,...g,ref:R,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:te(t.onKeyDown,E=>{E.key==="Escape"&&(l?.(E.nativeEvent),E.nativeEvent.defaultPrevented||G())}),onPointerDown:te(t.onPointerDown,E=>{E.button===0&&(I.current={x:E.clientX,y:E.clientY})}),onPointerMove:te(t.onPointerMove,E=>{if(!I.current)return;const S=E.clientX-I.current.x,M=E.clientY-I.current.y,H=!!T.current,U=["left","right"].includes(h.swipeDirection),re=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,oe=U?re(0,S):0,ie=U?0:re(0,M),se=E.pointerType==="touch"?10:2,ue={x:oe,y:ie},Pe={originalEvent:E,delta:ue};H?(T.current=ue,Bo(hN,f,Pe,{discrete:!1})):xv(ue,h.swipeDirection,se)?(T.current=ue,Bo(mN,p,Pe,{discrete:!1}),E.target.setPointerCapture(E.pointerId)):(Math.abs(S)>se||Math.abs(M)>se)&&(I.current=null)}),onPointerUp:te(t.onPointerUp,E=>{const S=T.current,M=E.target;if(M.hasPointerCapture(E.pointerId)&&M.releasePointerCapture(E.pointerId),T.current=null,I.current=null,S){const H=E.currentTarget,U={originalEvent:E,delta:S};xv(S,h.swipeDirection,h.swipeThreshold)?Bo(vN,v,U,{discrete:!0}):Bo(gN,m,U,{discrete:!0}),H.addEventListener("click",re=>re.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null},"ToastImpl")),SN=Ge(e=>{const{__scopeToast:t,children:n,...r}=e,i=Ds(Ls,t),[o,s]=x(!1),[c,l]=x(!1);return Dv(()=>s(!0)),V(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:a(_i,{asChild:!0,container:i.announcerContainer||void 0,children:a(Wd,{...r,children:o&&a(z,{children:[i.label," ",n]})})})},"ToastAnnounce"),CN=J(Ge(function(t,n){const{__scopeToast:r,...i}=t;return a(ye.div,{...i,ref:n})},"ToastDescription")),RN="ToastClose",IN=J(Ge(function(t,n){const{__scopeToast:r,...i}=t,o=_N(RN,r);return a(kN,{asChild:!0,children:a(ye.button,{type:"button",...i,ref:n,onClick:te(t.onClick,o.onClose)})})},"ToastClose")),kN=J(Ge(function(t,n){const{__scopeToast:r,altText:i,...o}=t;return a(ye.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":i||void 0,...o,ref:n})},"ToastAnnounceExclude"));function Qd(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),Lv(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(...Qd(n))}}),t}Ge(Qd,"getAnnounceTextContent");function Bo(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?os(i,o):i.dispatchEvent(o)}Ge(Bo,"handleAndDispatchCustomEvent");var xv=Ge((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 Dv(e=()=>{}){const t=ht(e);Ze(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}Ge(Dv,"useNextFrame");function Lv(e){return e.nodeType===e.ELEMENT_NODE}Ge(Lv,"isHTMLElement");function $v(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:Ge(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}Ge($v,"getTabbableCandidates");function $s(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}Ge($s,"focusFirst");var TN=lN,PN=pN,NN=yN,EN=CN,AN=IN,qo=Ud([]),xN=1;function DN(e,t="success",n=8e3){if(!e)return;const r=xN++;qo.value=[...qo.value,{id:r,message:e,variant:t,durationMs:n}]}function LN(e){qo.value=qo.value.filter(t=>t.id!==e)}function $N(){const e=qo.value;return a(TN,{duration:8e3,swipeDirection:"right",children:[e.map(t=>a(NN,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||LN(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[a(EN,{className:"toast-message",children:t.message}),a(AN,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),a(PN,{className:"toast-viewport"})]})}function ON(e){Ue(a($N,{}),e)}function Os(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 Zd(e){return document.getElementById(e)}function js(e){return document.getElementById(e)}function Ov(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function jN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function MN(e,t){const n=t.trim();if(!n)return Ov(e);const r=Ov(e);try{const i=new RegExp(`(${jN(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Uo(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 FN=new Set(["BUTTON","A","SELECT"]),BN=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function qN(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function UN(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function GN(e){return e?FN.has(e.tagName)?!0:e instanceof HTMLInputElement&&BN.has(e.type):!1}function HN(e){return e.metaKey||e.ctrlKey}function Li(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(!qN(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}GN(n)||UN(n)&&!HN(e)||(e.preventDefault(),t.onSubmit())}}var Dr=["feed","projects","sharing","devices","health","advanced"],jv=["sync","coordinator-admin"],eu="codemem-tab",Mv="codemem-advanced-section",Fv="codemem-feed-filter",Bv="codemem-feed-scope",VN="codemem-sync-diagnostics",qv="codemem-sync-pairing",Uv="codemem-sync-redact",Gv=["all","observations","summaries"],Hv=["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 KN(e){return[...Dr]}function Go(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":Dr.includes(e)?e:"feed"}function tu(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return jv.includes(t)?"advanced":Dr.includes(t)?t:null}function nu(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 zN(){const e=tu();if(e)return Go(e,C.lastCoordinatorAdminStatus);const t=localStorage.getItem(eu);return t&&(Dr.includes(t)||jv.includes(t))?Go(t,C.lastCoordinatorAdminStatus):"feed"}function WN(){const e=nu();if(e)return e;const t=localStorage.getItem(eu);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(Mv)==="teams"?"teams":"sync"}function ru(e,t=!1){C.advancedSection=e,localStorage.setItem(Mv,e),t&&(window.location.hash=`advanced/${e}`)}function Vv(e,t={}){const n=Go(e,C.lastCoordinatorAdminStatus);C.activeTab=n,localStorage.setItem(eu,n);const r=tu();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${C.advancedSection}`:n)}function JN(){const e=localStorage.getItem(Fv)||"all";return Gv.includes(e)?e:"all"}function YN(){const e=localStorage.getItem(Bv)||"all";return Hv.includes(e)?e:"all"}function XN(e){C.feedTypeFilter=Gv.includes(e)?e:"all",localStorage.setItem(Fv,C.feedTypeFilter)}function Kv(e){C.feedScopeFilter=Hv.includes(e)?e:"all",localStorage.setItem(Bv,C.feedScopeFilter)}function QN(){return localStorage.getItem(VN)==="1"}function ZN(e){C.syncPairingOpen=e;try{localStorage.setItem(qv,e?"1":"0")}catch{}}function Ho(){return localStorage.getItem(Uv)!=="0"}function eE(e){localStorage.setItem(Uv,e?"1":"0")}function tE(){C.activeTab=zN(),C.advancedSection=WN(),C.feedTypeFilter=JN(),C.feedScopeFilter=YN(),C.syncDiagnosticsOpen=QN();try{C.syncPairingOpen=localStorage.getItem(qv)==="1"}catch{C.syncPairingOpen=!1}}function nE(e,t,n){t.left>=n.left&&t.right<=n.right||e.scrollIntoView({block:"nearest",inline:"nearest"})}function rE(){let e=null,t=null,n=null,r=null,i=null;return o=>{if(o.hidden)return;const s=o.closest(".tab-bar");if(!s)return;const c=o.getBoundingClientRect(),l=s.getBoundingClientRect(),d=c.left+s.scrollLeft,u=c.right+s.scrollLeft;o===e&&d===t&&u===n&&l.left===r&&l.right===i||(e=o,t=d,n=u,r=l.left,i=l.right,nE(o,c,l))}}var iu=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],zv="codemem-theme";function Wv(e){const t=iu.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return iu.find(r=>r.id===n)||iu[0]}function ou(){const e=localStorage.getItem(zv);return e?Wv(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Jv(e){const t=Wv(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(zv,t.id)}function iE(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(ou()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=ou()==="dark"?"light":"dark";Jv(n),t(n)})}var oE=Object.defineProperty,aE=(e,t)=>oE(e,"name",{value:t,configurable:!0}),sE=Cr(void 0);function $i(e){const t=kn(sE);return e||t||"ltr"}aE($i,"useDirection");var cE=Object.defineProperty,au=(e,t)=>cE(e,"name",{value:t,configurable:!0}),su=!1;function Yv(){const[e,t]=x(su);return V(()=>{su||(su=!0,t(!0))},[]),e}au(Yv,"useIsHydrated");var Xv=gi[" useSyncExternalStore ".trim().toString()];function Qv(){return()=>{}}au(Qv,"subscribe");function Zv(){return Xv(Qv,()=>!0,()=>!1)}au(Zv,"useIsHydratedModern");var lE=typeof Xv=="function"?Zv:Yv,dE=Object.defineProperty,Lr=(e,t)=>dE(e,"name",{value:t,configurable:!0}),cu="rovingFocusGroup.onEntryFocus",uE={bubbles:!1,cancelable:!0},Ms="RovingFocusGroup",[lu,ey,pE]=Fo(Ms),[fE,Oi]=dt(Ms,[pE]),[mE,hE]=fE(Ms),gE=J(Lr(function(t,n){return a(lu.Provider,{scope:t.__scopeRovingFocusGroup,children:a(lu.Slot,{scope:t.__scopeRovingFocusGroup,children:a(vE,{...t,ref:n})})})},"RovingFocusGroup")),vE=J(Lr(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=B(null),v=Re(n,m),g=$i(s),[h,b]=At({prop:c,defaultProp:l??null,onChange:d,caller:Ms}),[w,_]=x(!1),R=ht(u),I=ey(r),T=B(!1),[A,O]=x(0);return V(()=>{const F=m.current;if(F)return F.addEventListener(cu,R),()=>F.removeEventListener(cu,R)},[R]),a(mE,{scope:r,orientation:i,dir:g,loop:o,currentTabStopId:h,onItemFocus:ae(F=>b(F),[b]),onItemShiftTab:ae(()=>_(!0),[]),onFocusableItemAdd:ae(()=>O(F=>F+1),[]),onFocusableItemRemove:ae(()=>O(F=>F-1),[]),children:a(ye.div,{tabIndex:w||A===0?-1:0,"data-orientation":i,...f,ref:v,style:{outline:"none",...t.style},onMouseDown:te(t.onMouseDown,()=>{T.current=!0}),onFocus:te(t.onFocus,F=>{const N=!T.current;if(F.target===F.currentTarget&&N&&!w){const L=new CustomEvent(cu,uE);if(F.currentTarget.dispatchEvent(L),!L.defaultPrevented){const D=I().filter(G=>G.focusable);du([D.find(G=>G.active),D.find(G=>G.id===h),...D].filter(Boolean).map(G=>G.ref.current),p)}}T.current=!1}),onBlur:te(t.onBlur,()=>_(!1))})})},"RovingFocusGroupImpl")),yE="RovingFocusGroupItem",bE=J(Lr(function(t,n){const{__scopeRovingFocusGroup:r,focusable:i=!0,active:o=!1,tabStopId:s,children:c,...l}=t,d=Et(),u=s||d,p=hE(yE,r),f=p.currentTabStopId===u,m=ey(r),{onFocusableItemAdd:v,onFocusableItemRemove:g,currentTabStopId:h}=p,b=lE();return Ze(()=>{if(!(!b||!i))return v(),()=>g()},[b,i,v,g]),V(()=>{if(!(b||!i))return v(),()=>g()},[b,i,v,g]),a(lu.ItemSlot,{scope:r,id:u,focusable:i,active:o,children:a(ye.span,{tabIndex:f?0:-1,"data-orientation":p.orientation,...l,ref:n,onMouseDown:te(t.onMouseDown,w=>{i?p.onItemFocus(u):w.preventDefault()}),onFocus:te(t.onFocus,()=>p.onItemFocus(u)),onKeyDown:te(t.onKeyDown,w=>{if(w.key==="Tab"&&w.shiftKey){p.onItemShiftTab();return}if(w.target!==w.currentTarget)return;const _=ny(w,p.orientation,p.dir);if(_!==void 0){if(w.metaKey||w.ctrlKey||w.altKey||w.shiftKey)return;w.preventDefault();let R=m().filter(I=>I.focusable).map(I=>I.ref.current);if(_==="last")R.reverse();else if(_==="prev"||_==="next"){_==="prev"&&R.reverse();const I=R.indexOf(w.currentTarget);R=p.loop?ry(R,I+1):R.slice(I+1)}setTimeout(()=>du(R))}}),children:typeof c=="function"?c({isCurrentTabStop:f,hasTabStop:h!=null}):c})})},"RovingFocusGroupItem")),_E={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function ty(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Lr(ty,"getDirectionAwareKey");function ny(e,t,n){const r=ty(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return _E[r]}Lr(ny,"getFocusIntent");function du(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Lr(du,"focusFirst");function ry(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Lr(ry,"wrapArray");var uu=gE,pu=bE,wE=Object.defineProperty,ji=(e,t)=>wE(e,"name",{value:t,configurable:!0}),fu="Tabs",[SE,G2]=dt(fu,[Oi]),iy=Oi(),[CE,mu]=SE(fu),RE=J(ji(function(t,n){const{__scopeTabs:r,value:i,onValueChange:o,defaultValue:s,orientation:c="horizontal",dir:l,activationMode:d="automatic",...u}=t,p=$i(l),[f,m]=At({prop:i,onChange:o,defaultProp:s??"",caller:fu});return a(CE,{scope:r,baseId:Et(),value:f,onValueChange:m,orientation:c,dir:p,activationMode:d,children:a(ye.div,{dir:p,"data-orientation":c,...u,ref:n})})},"Tabs")),IE="TabsList",kE=J(ji(function(t,n){const{__scopeTabs:r,loop:i=!0,...o}=t,s=mu(IE,r),c=iy(r);return a(uu,{asChild:!0,...c,orientation:s.orientation,dir:s.dir,loop:i,children:a(ye.div,{role:"tablist","aria-orientation":s.orientation,...o,ref:n})})},"TabsList")),TE="TabsTrigger",PE=J(ji(function(t,n){const{__scopeTabs:r,value:i,disabled:o=!1,...s}=t,c=mu(TE,r),l=iy(r),d=hu(c.baseId,i),u=gu(c.baseId,i),p=i===c.value;return a(pu,{asChild:!0,...l,focusable:!o,active:p,children:a(ye.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:te(t.onMouseDown,f=>{!o&&f.button===0&&f.ctrlKey===!1?c.onValueChange(i):f.preventDefault()}),onKeyDown:te(t.onKeyDown,f=>{o||f.target!==f.currentTarget||[" ","Enter"].includes(f.key)&&c.onValueChange(i)}),onFocus:te(t.onFocus,()=>{const f=c.activationMode!=="manual";!p&&!o&&f&&c.onValueChange(i)})})})},"TabsTrigger")),NE="TabsContent",EE=J(ji(function(t,n){const{__scopeTabs:r,value:i,forceMount:o,children:s,...c}=t,l=mu(NE,r),d=hu(l.baseId,i),u=gu(l.baseId,i),p=i===l.value,f=B(p);return V(()=>{const m=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(m)},[]),a(kt,{present:o||p,children:({present:m})=>a(ye.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 hu(e,t){return`${e}-trigger-${t}`}ji(hu,"makeTriggerId");function gu(e,t){return`${e}-content-${t}`}ji(gu,"makeContentId");var AE=RE,xE=kE,DE=PE,LE=EE;function oy({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:o,value:s}){return a(AE,{onValueChange:r,value:s,children:[a(xE,{"aria-label":e,className:n,children:i.map(c=>a(DE,{className:o,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function $r({children:e,className:t,forceMount:n=!1,value:r}){return a(LE,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Te(e){return a("input",{...e})}function Fs(){return{aliases:new Map,duplicateDisplayNames:new Map,reservedDisplayNames:new Set}}function ay(e,t=Fs()){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 Bs(e,t=Fs()){const n=ay(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 $E(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 sy={status:"coordinator status",groups:"coordinator groups",joinRequests:"join requests",devices:"devices"};function qs(){return{availability:"unknown",retrying:!1}}function OE(){return{status:qs(),groups:qs(),joinRequests:qs(),devices:qs()}}function Vo(e,t){e[t]={...e[t],retrying:!0}}function vu(e,t){e[t]={...e[t],retrying:!1}}function Us(e,t){e[t]={availability:"fresh",retrying:!1}}function un(e,t,n){e[t]={availability:n??(e[t].availability==="fresh"||e[t].availability==="stale")?"stale":"unavailable",retrying:!1}}function yu(e,t){e[t]={availability:"not_applicable",retrying:!1}}function Or(e,t){return e[t].availability==="fresh"||e[t].availability==="stale"}function xn(e,...t){return t.every(n=>e[n].availability==="fresh"&&!e[n].retrying)}function Mi(e,t){return e[t].availability==="not_applicable"}function bu(e){const t=Object.entries(e),n=t.filter(([,i])=>i.availability==="stale").map(([i])=>sy[i]),r=t.filter(([,i])=>i.availability==="unavailable").map(([i])=>sy[i]);return n.length===0&&r.length===0?null:{stale:n,unavailable:r,retrying:t.some(([,i])=>i.retrying)}}var jE="codemem-coordinator-admin-target-group",P={recovery:OE(),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:Fs(),groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function cy(){return P.loadGeneration+=1,P.loadGeneration}function _u(e){return P.loadGeneration===e}function ME(e){const{summary:t,fresh:n,runDevice:r,snapshotMatchesTarget:i}=e,o=i&&Or(P.recovery,"devices"),s=Mi(P.recovery,"devices"),c=o&&Array.isArray(C.lastCoordinatorAdminDevices)?C.lastCoordinatorAdminDevices:[],l=Bs(c,P.unnamedDeviceAliases);return y($r,{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 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?y("div",{class:"peer-meta"},"Complete legacy coordinator setup to load enrolled devices. No device data is expected yet."):o?c.length?y("div",{class:"peer-list"},c.map(d=>{const u=$E(d,String(C.lastCoordinatorAdminStatus?.active_group||""),l.get(String(d.device_id||"").trim())),{deviceId:p,displayName:f,teamId:m}=u,v=P.deviceActionPendingId===p,g=P.deviceRenameDrafts.get(p)??String(d.display_name||""),h=d.enabled!==!1&&d.enabled!==0,b=!n||!p||v;return y("div",{class:"peer-card peer-card--padded",key:p||String(d.fingerprint||"unknown")},y("div",{class:"peer-title"},y("strong",null,f)),y("div",{class:"peer-submeta"},u.statusLabel),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},u.advancedDetail)),y("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r(p,m,f,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Te,{class:"peer-scope-input",disabled:!n||v,onInput:w=>{P.deviceRenameDrafts.set(p,String(w.currentTarget.value||""))},type:"text",value:g}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:b,type:"submit"},v&&P.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),h?y("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,m,f,"disable"),type:"button"},v&&P.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:b,onClick:()=>r(p,m,f,"enable"),type:"button"},v&&P.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,m,f,"remove"),type:"button"},v&&P.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."):y("div",{class:"peer-meta"},"Enrolled devices are unavailable. Retry to load current devices; no empty result is being assumed."))}var FE=Object.defineProperty,Ko=(e,t)=>FE(e,"name",{value:t,configurable:!0}),wu="Collapsible",[BE,H2]=dt(wu),[qE,Su]=BE(wu),UE=J(Ko(function(t,n){const{__scopeCollapsible:r,open:i,defaultOpen:o,disabled:s,onOpenChange:c,...l}=t,[d,u]=At({prop:i,defaultProp:o??!1,onChange:c,caller:wu});return a(qE,{scope:r,disabled:s,contentId:Et(),open:d,onOpenToggle:ae(()=>u(p=>!p),[u]),children:a(ye.div,{"data-state":Gs(d),"data-disabled":s?"":void 0,...l,ref:n})})},"Collapsible")),GE="CollapsibleTrigger",HE=J(Ko(function(t,n){const{__scopeCollapsible:r,...i}=t,o=Su(GE,r);return a(ye.button,{type:"button","aria-controls":o.open?o.contentId:void 0,"aria-expanded":o.open||!1,"data-state":Gs(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...i,ref:n,onClick:te(t.onClick,o.onOpenToggle)})},"CollapsibleTrigger")),ly="CollapsibleContent",VE=J(Ko(function(t,n){const{forceMount:r,...i}=t,o=Su(ly,t.__scopeCollapsible);return a(kt,{present:r||o.open,children:({present:s})=>a(KE,{...i,ref:n,present:s})})},"CollapsibleContent")),KE=J(Ko(function(t,n){const{__scopeCollapsible:r,present:i,children:o,...s}=t,c=Su(ly,r),[l,d]=x(i),u=B(null),p=Re(n,u),f=B(0),m=f.current,v=B(0),g=v.current,h=c.open||l,b=B(h),w=B(void 0);return V(()=>{const _=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(_)},[]),Ze(()=>{const _=u.current;if(_){w.current=w.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const R=_.getBoundingClientRect();f.current=R.height,v.current=R.width,b.current||(_.style.transitionDuration=w.current.transitionDuration,_.style.animationName=w.current.animationName),d(i)}},[c.open,i]),a(ye.div,{"data-state":Gs(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 Gs(e){return e?"open":"closed"}Ko(Gs,"getState");var zo=UE,Cu=HE,Wo=VE,zE=["top","right","bottom","left"],Zn=Math.min,Dt=Math.max,Hs=Math.round,Vs=Math.floor,pn=e=>({x:e,y:e}),WE={left:"right",right:"left",bottom:"top",top:"bottom"};function Ru(e,t,n){return Dt(e,Zn(t,n))}function Dn(e,t){return typeof e=="function"?e(t):e}function Ln(e){return e.split("-")[0]}function Fi(e){return e.split("-")[1]}function Iu(e){return e==="x"?"y":"x"}function ku(e){return e==="y"?"height":"width"}function fn(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Tu(e){return Iu(fn(e))}function JE(e,t,n){n===void 0&&(n=!1);const r=Fi(e),i=Tu(e),o=ku(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[o]>t.floating[o]&&(s=Ks(s)),[s,Ks(s)]}function YE(e){const t=Ks(e);return[Pu(e),t,Pu(t)]}function Pu(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var dy=["left","right"],uy=["right","left"],XE=["top","bottom"],QE=["bottom","top"];function ZE(e,t,n){switch(e){case"top":case"bottom":return n?t?uy:dy:t?dy:uy;case"left":case"right":return t?XE:QE;default:return[]}}function eA(e,t,n,r){const i=Fi(e);let o=ZE(Ln(e),n==="start",r);return i&&(o=o.map(s=>s+"-"+i),t&&(o=o.concat(o.map(Pu)))),o}function Ks(e){const t=Ln(e);return WE[t]+e.slice(t.length)}function tA(e){return{top:0,right:0,bottom:0,left:0,...e}}function py(e){return typeof e!="number"?tA(e):{top:e,right:e,bottom:e,left:e}}function zs(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 fy(e,t,n){let{reference:r,floating:i}=e;const o=fn(t),s=Tu(t),c=ku(s),l=Ln(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(Fi(t)){case"start":m[s]-=f*(n&&d?-1:1);break;case"end":m[s]+=f*(n&&d?-1:1)}return m}async function nA(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}=Dn(t,e),v=py(m),g=c[f?p==="floating"?"reference":"floating":p],h=zs(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})),b=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},R=zs(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:w,strategy:l}):b);return{top:(h.top-R.top+v.top)/_.y,bottom:(R.bottom-h.bottom+v.bottom)/_.y,left:(h.left-R.left+v.left)/_.x,right:(R.right-h.right+v.right)/_.x}}var rA=50,iA=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:o=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:nA},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}=fy(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:b,fn:w}=h,{x:_,y:R,data:I,reset:T}=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=R??p,v[b]={...v[b],...I},T&&m<rA&&(m++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:u,y:p}=fy(d,f,l)),g=-1)}return{x:u,y:p,placement:f,strategy:i,middlewareData:v}},oA=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}=Dn(e,t)||{};if(d==null)return{};const p=py(u),f={x:n,y:r},m=Tu(i),v=ku(m),g=await s.getDimensions(d),h=m==="y",b=h?"top":"left",w=h?"bottom":"right",_=h?"clientHeight":"clientWidth",R=o.reference[v]+o.reference[m]-f[m]-o.floating[v],I=f[m]-o.reference[m],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=T?T[_]:0;(!A||!await(s.isElement==null?void 0:s.isElement(T)))&&(A=c.floating[_]||o.floating[v]);const O=R/2-I/2,F=A/2-g[v]/2-1,N=Zn(p[b],F),L=Zn(p[w],F),D=N,G=A-g[v]-L,q=A/2-g[v]/2+O,$=Ru(D,q,G),E=!l.arrow&&Fi(i)!=null&&q!==$&&o.reference[v]/2-(q<D?N:L)-g[v]/2<0,S=E?q<D?q-D:q-G:0;return{[m]:f[m]+S,data:{[m]:$,centerOffset:q-$-S,...E&&{alignmentOffset:S}},reset:E}}}),aA=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}=Dn(e,t);if((n=o.arrow)!=null&&n.alignmentOffset)return{};const b=Ln(i),w=fn(c),_=Ln(c)===c,R=await(l.isRTL==null?void 0:l.isRTL(d.floating)),I=f||(_||!g?[Ks(c)]:YE(c)),T=v!=="none";!f&&T&&I.push(...eA(c,g,v,R));const A=[c,...I],O=await l.detectOverflow(t,h),F=[];let N=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&F.push(O[b]),p){const q=JE(i,s,R);F.push(O[q[0]],O[q[1]])}if(N=[...N,{placement:i,overflows:F}],!F.every(q=>q<=0)){var L,D;const q=(((L=o.flip)==null?void 0:L.index)||0)+1,$=A[q];if($&&(!(p==="alignment"&&w!==fn($))||N.every(S=>fn(S.placement)===w?S.overflows[0]>0:!0)))return{data:{index:q,overflows:N},reset:{placement:$}};let E=(D=N.filter(S=>S.overflows[0]<=0).sort((S,M)=>S.overflows[1]-M.overflows[1])[0])==null?void 0:D.placement;if(!E)switch(m){case"bestFit":{var G;const S=(G=N.filter(M=>{if(T){const H=fn(M.placement);return H===w||H==="y"}return!0}).map(M=>[M.placement,M.overflows.filter(H=>H>0).reduce((H,U)=>H+U,0)]).sort((M,H)=>M[1]-H[1])[0])==null?void 0:G[0];S&&(E=S);break}case"initialPlacement":E=c}if(i!==E)return{reset:{placement:E}}}return{}}}};function my(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function hy(e){return zE.some(t=>e[t]>=0)}var sA=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...o}=Dn(e,t);switch(i){case"referenceHidden":{const s=my(await r.detectOverflow(t,{...o,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:hy(s)}}}case"escaped":{const s=my(await r.detectOverflow(t,{...o,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:hy(s)}}}default:return{}}}}},gy=new Set(["left","top"]);async function cA(e,t){const{placement:n,platform:r,elements:i}=e,o=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=Ln(n),c=Fi(n),l=fn(n)==="y",d=gy.has(s)?-1:1,u=o&&l?-1:1,p=Dn(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 lA=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 cA(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}}}}},dA=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:b=>{let{x:w,y:_}=b;return{x:w,y:_}}},...d}=Dn(e,t),u={x:n,y:r},p=await o.detectOverflow(t,d),f=fn(Ln(i)),m=Iu(f);let v=u[m],g=u[f];if(s){const b=m==="y"?"top":"left",w=m==="y"?"bottom":"right",_=v+p[b],R=v-p[w];v=Ru(_,v,R)}if(c){const b=f==="y"?"top":"left",w=f==="y"?"bottom":"right",_=g+p[b],R=g-p[w];g=Ru(_,g,R)}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}}}}}},uA=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}=Dn(e,t),u={x:n,y:r},p=fn(i),f=Iu(p);let m=u[f],v=u[p];const g=Dn(c,t),h=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const _=f==="y"?"height":"width",R=o.reference[f]-o.floating[_]+h.mainAxis,I=o.reference[f]+o.reference[_]-h.mainAxis;m<R?m=R:m>I&&(m=I)}if(d){var b,w;const _=f==="y"?"width":"height",R=gy.has(Ln(i)),I=o.reference[p]-o.floating[_]+(R&&((b=s.offset)==null?void 0:b[p])||0)+(R?0:h.crossAxis),T=o.reference[p]+o.reference[_]+(R?0:((w=s.offset)==null?void 0:w[p])||0)-(R?h.crossAxis:0);v<I?v=I:v>T&&(v=T)}return{[f]:m,[p]:v}}}},pA=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}=Dn(e,t),u=await s.detectOverflow(t,d),p=Ln(i),f=Fi(i),m=fn(i)==="y",{width:v,height:g}=o.floating;let h,b;p==="top"||p==="bottom"?(h=p,b=f===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,h=f==="end"?"top":"bottom");const w=g-u.top-u.bottom,_=v-u.left-u.right,R=Zn(g-u[h],w),I=Zn(v-u[b],_),T=!t.middlewareData.shift;let A=R,O=I;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(O=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=w),T&&!f){const N=Dt(u.left,0),L=Dt(u.right,0),D=Dt(u.top,0),G=Dt(u.bottom,0);m?O=v-2*(N!==0||L!==0?N+L:Dt(u.left,u.right)):A=g-2*(D!==0||G!==0?D+G:Dt(u.top,u.bottom))}await l({...t,availableWidth:O,availableHeight:A});const F=await s.getDimensions(c.floating);return v!==F.width||g!==F.height?{reset:{rects:!0}}:{}}}};function Ws(){return typeof window<"u"}function Bi(e){return vy(e)?(e.nodeName||"").toLowerCase():"#document"}function Lt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(vy(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function vy(e){return Ws()?e instanceof Node||e instanceof Lt(e).Node:!1}function Yt(e){return Ws()?e instanceof Element||e instanceof Lt(e).Element:!1}function $n(e){return Ws()?e instanceof HTMLElement||e instanceof Lt(e).HTMLElement:!1}function yy(e){return!Ws()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Lt(e).ShadowRoot}function Jo(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Xt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function fA(e){return/^(table|td|th)$/.test(Bi(e))}function Js(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var mA=/transform|translate|scale|rotate|perspective|filter/,hA=/paint|layout|strict|content/,jr=e=>!!e&&e!=="none",Nu;function Eu(e){const t=Yt(e)?Xt(e):e;return jr(t.transform)||jr(t.translate)||jr(t.scale)||jr(t.rotate)||jr(t.perspective)||!Au()&&(jr(t.backdropFilter)||jr(t.filter))||mA.test(t.willChange||"")||hA.test(t.contain||"")}function gA(e){let t=er(e);for(;$n(t)&&!qi(t);){if(Eu(t))return t;if(Js(t))return null;t=er(t)}return null}function Au(){return Nu==null&&(Nu=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Nu}function qi(e){return/^(html|body|#document)$/.test(Bi(e))}function Xt(e){return Lt(e).getComputedStyle(e)}function Ys(e){return Yt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function er(e){if(Bi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||yy(e)&&e.host||mn(e);return yy(t)?t.host:t}function by(e){const t=er(e);return qi(t)?e.ownerDocument?e.ownerDocument.body:e.body:$n(t)&&Jo(t)?t:by(t)}function Yo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=by(e),o=i===((r=e.ownerDocument)==null?void 0:r.body),s=Lt(i);if(o){const c=xu(s);return t.concat(s,s.visualViewport||[],Jo(i)?i:[],c&&n?Yo(c):[])}else return t.concat(i,Yo(i,[],n))}function xu(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _y(e){const t=Xt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=$n(e),o=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=Hs(n)!==o||Hs(r)!==s;return c&&(n=o,r=s),{width:n,height:r,$:c}}function Du(e){return Yt(e)?e:e.contextElement}function Ui(e){const t=Du(e);if(!$n(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:o}=_y(t);let s=(o?Hs(n.width):n.width)/r,c=(o?Hs(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var vA=pn(0);function wy(e){const t=Lt(e);return!Au()||!t.visualViewport?vA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function yA(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Lt(e)?!1:t}function Mr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),o=Du(e);let s=pn(1);t&&(r?Yt(r)&&(s=Ui(r)):s=Ui(e));const c=yA(o,n,r)?wy(o):pn(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=Lt(o),m=r&&Yt(r)?Lt(r):r;let v=f,g=xu(v);for(;g&&r&&m!==v;){const h=Ui(g),b=g.getBoundingClientRect(),w=Xt(g),_=b.left+(g.clientLeft+parseFloat(w.paddingLeft))*h.x,R=b.top+(g.clientTop+parseFloat(w.paddingTop))*h.y;l*=h.x,d*=h.y,u*=h.x,p*=h.y,l+=_,d+=R,v=Lt(g),g=xu(v)}}return zs({width:u,height:p,x:l,y:d})}function Xs(e,t){const n=Ys(e).scrollLeft;return t?t.left+n:Mr(mn(e)).left+n}function Sy(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xs(e,n),y:n.top+t.scrollTop}}function bA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const o=i==="fixed",s=mn(r),c=t?Js(t.floating):!1;if(r===s||c&&o)return n;let l={scrollLeft:0,scrollTop:0},d=pn(1);const u=pn(0),p=$n(r);if((p||!p&&!o)&&((Bi(r)!=="body"||Jo(s))&&(l=Ys(r)),p)){const m=Mr(r);d=Ui(r),u.x=m.x+r.clientLeft,u.y=m.y+r.clientTop}const f=s&&!p&&!o?Sy(s,l):pn(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 _A(e){return Array.from(e.getClientRects())}function wA(e){const t=mn(e),n=Ys(e),r=e.ownerDocument.body,i=Dt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),o=Dt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+Xs(e);const c=-n.scrollTop;return Xt(r).direction==="rtl"&&(s+=Dt(t.clientWidth,r.clientWidth)-i),{width:i,height:o,x:s,y:c}}var Cy=25;function SA(e,t){const n=Lt(e),r=mn(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=Au();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=Xs(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<=Cy&&(o-=v)}else d<=Cy&&(o+=d);return{width:o,height:s,x:c,y:l}}function CA(e,t){const n=Mr(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,o=$n(e)?Ui(e):pn(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:i*o.x,y:r*o.y}}function Ry(e,t,n){let r;if(t==="viewport")r=SA(e,n);else if(t==="document")r=wA(mn(e));else if(Yt(t))r=CA(t,n);else{const i=wy(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return zs(r)}function Iy(e,t){const n=er(e);return n===t||!Yt(n)||qi(n)?!1:Xt(n).position==="fixed"||Iy(n,t)}function RA(e,t){const n=t.get(e);if(n)return n;let r=Yo(e,[],!1).filter(c=>Yt(c)&&Bi(c)!=="body"),i=null;const o=Xt(e).position==="fixed";let s=o?er(e):e;for(;Yt(s)&&!qi(s);){const c=Xt(s),l=Eu(s);!l&&c.position==="fixed"&&(i=null),(o?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||Jo(s)&&!l&&Iy(e,s))?r=r.filter(d=>d!==s):i=c,s=er(s)}return t.set(e,r),r}function IA(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?Js(t)?[]:RA(t,this._c):[].concat(n),r],s=Ry(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=Ry(t,o[p],i);c=Dt(f.top,c),l=Zn(f.right,l),d=Zn(f.bottom,d),u=Dt(f.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function kA(e){const{width:t,height:n}=_y(e);return{width:t,height:n}}function TA(e,t,n){const r=$n(t),i=mn(t),o=n==="fixed",s=Mr(e,!0,o,t);let c={scrollLeft:0,scrollTop:0};const l=pn(0);function d(){l.x=Xs(i)}if(r||!r&&!o)if((Bi(t)!=="body"||Jo(i))&&(c=Ys(t)),r){const p=Mr(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?Sy(i,c):pn(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 Lu(e){return Xt(e).position==="static"}function ky(e,t){if(!$n(e)||Xt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Ty(e,t){const n=Lt(e);if(Js(e))return n;if(!$n(e)){let i=er(e);for(;i&&!qi(i);){if(Yt(i)&&!Lu(i))return i;i=er(i)}return n}let r=ky(e,t);for(;r&&fA(r)&&Lu(r);)r=ky(r,t);return r&&qi(r)&&Lu(r)&&!Eu(r)?n:r||gA(e)||n}var PA=async function(e){const t=this.getOffsetParent||Ty,n=this.getDimensions,r=await n(e.floating);return{reference:TA(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function NA(e){return Xt(e).direction==="rtl"}var EA={convertOffsetParentRelativeRectToViewportRelativeRect:bA,getDocumentElement:mn,getClippingRect:IA,getOffsetParent:Ty,getElementRects:PA,getClientRects:_A,getDimensions:kA,getScale:Ui,isElement:Yt,isRTL:NA};function Py(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function AA(e,t){let n=null,r;const i=mn(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=Vs(p),g=Vs(i.clientWidth-(u+f)),h=Vs(i.clientHeight-(p+m)),b=Vs(u),w={rootMargin:-v+"px "+-g+"px "+-h+"px "+-b+"px",threshold:Dt(0,Zn(1,l))||1};let _=!0;function R(I){const T=I[0].intersectionRatio;if(T!==l){if(!_)return s();T?s(!1,T):r=setTimeout(()=>{s(!1,1e-7)},1e3)}T===1&&!Py(d,e.getBoundingClientRect())&&s(),_=!1}try{n=new IntersectionObserver(R,{...w,root:i.ownerDocument})}catch{n=new IntersectionObserver(R,w)}n.observe(e)}return s(!0),o}function xA(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=Du(e),u=i||o?[...d?Yo(d):[],...t?Yo(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),o&&b.addEventListener("resize",n)});const p=d&&c?AA(d,n):null;let f=-1,m=null;s&&(m=new ResizeObserver(b=>{let[w]=b;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?Mr(e):null;l&&h();function h(){const b=Mr(e);g&&!Py(g,b)&&n(),g=b,v=requestAnimationFrame(h)}return n(),()=>{var b;u.forEach(w=>{i&&w.removeEventListener("scroll",n),o&&w.removeEventListener("resize",n)}),p?.(),(b=m)==null||b.disconnect(),m=null,l&&cancelAnimationFrame(v)}}var DA=lA,LA=dA,$A=aA,OA=pA,jA=sA,Ny=oA,MA=uA,FA=(e,t,n)=>{const r=new Map,i={platform:EA,...n},o={...i.platform,_c:r};return iA(e,t,{...i,platform:o})},Qs=typeof document<"u"?It:function(){};function Zs(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(!Zs(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)&&!Zs(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}function Ey(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Ay(e,t){const n=Ey(e);return Math.round(t*n)/n}function $u(e){const t=B(e);return Qs(()=>{t.current=e}),t}function BA(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);Zs(f,r)||m(r);const[v,g]=x(null),[h,b]=x(null),w=ae(M=>{M!==T.current&&(T.current=M,g(M))},[]),_=ae(M=>{M!==A.current&&(A.current=M,b(M))},[]),R=o||v,I=s||h,T=B(null),A=B(null),O=B(u),F=l!=null,N=$u(l),L=$u(i),D=$u(d),G=ae(()=>{if(!T.current||!A.current)return;const M={placement:t,strategy:n,middleware:f};L.current&&(M.platform=L.current),FA(T.current,A.current,M).then(H=>{const U={...H,isPositioned:D.current!==!1};q.current&&!Zs(O.current,U)&&(O.current=U,rs(()=>{p(U)}))})},[f,t,n,L,D]);Qs(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,p(M=>({...M,isPositioned:!1})))},[d]);const q=B(!1);Qs(()=>(q.current=!0,()=>{q.current=!1}),[]),Qs(()=>{if(R&&(T.current=R),I&&(A.current=I),R&&I){if(N.current)return N.current(R,I,G);G()}},[R,I,G,N,F]);const $=ke(()=>({reference:T,floating:A,setReference:w,setFloating:_}),[w,_]),E=ke(()=>({reference:R,floating:I}),[R,I]),S=ke(()=>{const M={position:n,left:0,top:0};if(!E.floating)return M;const H=Ay(E.floating,u.x),U=Ay(E.floating,u.y);return c?{...M,transform:"translate("+H+"px, "+U+"px)",...Ey(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:U}},[n,c,E.floating,u.x,u.y]);return ke(()=>({...u,update:G,refs:$,elements:E,floatingStyles:S}),[u,G,$,E,S])}var qA=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?Ny({element:r.current,padding:i}).fn(n):{}:r?Ny({element:r,padding:i}).fn(n):{}}}},UA=(e,t)=>{const n=DA(e);return{name:n.name,fn:n.fn,options:[e,t]}},GA=(e,t)=>{const n=LA(e);return{name:n.name,fn:n.fn,options:[e,t]}},HA=(e,t)=>({fn:MA(e).fn,options:[e,t]}),VA=(e,t)=>{const n=$A(e);return{name:n.name,fn:n.fn,options:[e,t]}},KA=(e,t)=>{const n=OA(e);return{name:n.name,fn:n.fn,options:[e,t]}},zA=(e,t)=>{const n=jA(e);return{name:n.name,fn:n.fn,options:[e,t]}},WA=(e,t)=>{const n=qA(e);return{name:n.name,fn:n.fn,options:[e,t]}},JA=Object.defineProperty,YA=(e,t)=>JA(e,"name",{value:t,configurable:!0}),XA=J(YA(function(t,n){const{children:r,width:i=10,height:o=5,...s}=t;return a(ye.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")),QA=XA,ZA=Object.defineProperty,ex=(e,t)=>ZA(e,"name",{value:t,configurable:!0});function ec(e){const[t,n]=x(void 0);return Ze(()=>{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}ex(ec,"useSize");var tx=Object.defineProperty,On=(e,t)=>tx(e,"name",{value:t,configurable:!0}),xy="Popper",[Dy,tr]=dt(xy),[nx,Ly]=Dy(xy),rx=On(e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null),[o,s]=x(void 0);return a(nx,{scope:t,anchor:r,onAnchorChange:i,placementState:o,setPlacementState:s,children:n})},"Popper"),ix="PopperAnchor",ox=J(On(function(t,n){const{__scopePopper:r,virtualRef:i,...o}=t,s=Ly(ix,r),c=B(null),l=s.onAnchorChange,d=ae(g=>{c.current=g,g&&l(g)},[l]),u=Re(n,d),p=B(null);V(()=>{if(!i)return;const g=p.current;p.current=i.current,g!==p.current&&l(p.current)});const f=s.placementState&&tc(s.placementState),m=f?.[0],v=f?.[1];return i?null:a(ye.div,{"data-radix-popper-side":m,"data-radix-popper-align":v,...o,ref:u})},"PopperAnchor")),$y="PopperContent",[ax,sx]=Dy($y),cx=J(On(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,b=Ly($y,r),[w,_]=x(null),R=Re(n,_),[I,T]=x(null),A=ec(I),O=A?.width??0,F=A?.height??0,N=i+(s!=="center"?"-"+s:""),L=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},D=Array.isArray(u)?u:[u],G=D.length>0,q={padding:L,boundary:D.filter(Oy),altBoundary:G},{refs:$,floatingStyles:E,placement:S,isPositioned:M,middlewareData:H}=BA({strategy:"fixed",placement:N,whileElementsMounted:On((...ve)=>xA(...ve,{animationFrame:v==="always"}),"whileElementsMounted"),elements:{reference:b.anchor},middleware:[UA({mainAxis:o+F,alignmentAxis:c}),d&&GA({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?HA():void 0,...q}),d&&VA({...q}),KA({...q,apply:On(({elements:ve,rects:X,availableWidth:ce,availableHeight:be})=>{const{width:fe,height:We}=X.reference,he=ve.floating.style;he.setProperty("--radix-popper-available-width",`${ce}px`),he.setProperty("--radix-popper-available-height",`${be}px`),he.setProperty("--radix-popper-anchor-width",`${fe}px`),he.setProperty("--radix-popper-anchor-height",`${We}px`)},"apply")}),I&&WA({element:I,padding:l}),px({arrowWidth:O,arrowHeight:F}),m&&zA({strategy:"referenceHidden",...q,boundary:G?q.boundary:void 0})]}),U=b.setPlacementState;Ze(()=>(U(S),()=>{U(void 0)}),[S,U]);const[re,oe]=tc(S),ie=ht(g);Ze(()=>{M&&ie?.()},[M,ie]);const se=H.arrow?.x,ue=H.arrow?.y,Pe=H.arrow?.centerOffset!==0,[Ie,le]=x();return Ze(()=>{w&&le(window.getComputedStyle(w).zIndex)},[w]),a("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...E,transform:M?E.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ie,"--radix-popper-transform-origin":[H.transformOrigin?.x,H.transformOrigin?.y].join(" "),...H.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:a(ax,{scope:r,placedSide:re,placedAlign:oe,onArrowChange:T,arrowX:se,arrowY:ue,shouldHideArrow:Pe,children:a(ye.div,{"data-side":re,"data-align":oe,...h,ref:R,style:{...h.style,animation:M?h.style?.animation:"none"}})})})},"PopperContent")),lx="PopperArrow",dx={top:"bottom",right:"left",bottom:"top",left:"right"},ux=J(On(function(t,n){const{__scopePopper:r,...i}=t,o=sx(lx,r),s=dx[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(QA,{...i,ref:n,style:{...i.style,display:"block"}})})},"PopperArrow"));function Oy(e){return e!==null}On(Oy,"isNotNull");var px=On(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]=tc(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 tc(e){const[t,n="center"]=e.split("-");return[t,n]}On(tc,"getSideAndAlignFromPlacement");var nc=rx,Xo=ox,rc=cx,fx=ux,mx=Object.defineProperty,jn=(e,t)=>mx(e,"name",{value:t,configurable:!0}),Ou="Popover",[jy,V2]=dt(Ou,[tr]),ic=tr(),[hx,Fr]=jy(Ou),gx=jn(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:o,modal:s=!1}=e,c=ic(t),l=B(null),[d,u]=x(!1),[p,f]=At({prop:r,defaultProp:i??!1,onChange:o,caller:Ou});return a(nc,{...c,children:a(hx,{scope:t,contentId:Et(),triggerRef:l,open:p,onOpenChange:f,onOpenToggle:ae(()=>f(m=>!m),[f]),hasCustomAnchor:d,onCustomAnchorAdd:ae(()=>u(!0),[]),onCustomAnchorRemove:ae(()=>u(!1),[]),modal:s,children:n})})},"Popover"),vx="PopoverAnchor",yx=J(jn(function(t,n){const{__scopePopover:r,...i}=t,o=Fr(vx,r),s=ic(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:l}=o;return V(()=>(c(),()=>l()),[c,l]),a(Xo,{...s,...i,ref:n})},"PopoverAnchor")),bx="PopoverTrigger",_x=J(jn(function(t,n){const{__scopePopover:r,...i}=t,o=Fr(bx,r),s=ic(r),c=Re(n,o.triggerRef),l=a(ye.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":ju(o.open),...i,ref:c,onClick:te(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?l:a(Xo,{asChild:!0,...s,children:l})},"PopoverTrigger")),My="PopoverPortal",[wx,Sx]=jy(My,{forceMount:void 0}),Cx=jn(e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,o=Fr(My,t);return a(wx,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"PopoverPortal"),Qo="PopoverContent",Rx=J(jn(function(t,n){const r=Sx(Qo,t.__scopePopover),{forceMount:i=r.forceMount,...o}=t,s=Fr(Qo,t.__scopePopover);return a(kt,{present:i||s.open,children:s.modal?a(kx,{...o,ref:n}):a(Tx,{...o,ref:n})})},"PopoverContent")),Ix=cn("PopoverContent.RemoveScroll"),kx=J(jn(function(t,n){const r=Fr(Qo,t.__scopePopover),i=B(null),o=Re(n,i),s=B(!1);return V(()=>{const c=i.current;if(c)return hs(c)},[]),a(To,{as:Ix,allowPinchZoom:!0,children:a(Fy,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:te(t.onCloseAutoFocus,c=>{c.preventDefault(),s.current||r.triggerRef.current?.focus()}),onPointerDownOutside:te(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:te(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Tx=J(jn(function(t,n){const r=Fr(Qo,t.__scopePopover),i=B(!1),o=B(!1);return a(Fy,{...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")),Fy=J(jn(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=Fr(Qo,r),v=ic(r);return Ci(),a(as,{asChild:!0,loop:!0,trapped:i,onMountAutoFocus:o,onUnmountAutoFocus:s,children:a(bi,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>m.onOpenChange(!1),deferPointerDownOutside:!0,children:a(rc,{"data-state":ju(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 ju(e){return e?"open":"closed"}jn(ju,"getState");var By=gx,Px=yx,Nx=_x,qy=Cx,Uy=Rx;function Mu(e){return e.trim()}function Gy({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=B(null),v=ke(()=>{const N=new Set,L=[];for(const D of[...n,...e]){const G=Mu(D);!G||N.has(G)||(N.add(G),L.push(G))}return L.sort((D,G)=>D.localeCompare(G))},[n,e]),g=Mu(d),h=g.toLowerCase(),b=ke(()=>h?v.filter(N=>N.toLowerCase().includes(h)):v,[v,h]),w=g?v.some(N=>N.toLowerCase()===h):!1,_=!!g&&!w,R=b.length+(_?1:0);V(()=>{p>=R&&f(Math.max(0,R-1))},[R,p]),V(()=>{if(!c)return;const N=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(N)},[c]);const I=N=>{e.includes(N)?t(e.filter(L=>L!==N)):t(Array.from(new Set([...e,N])))},T=N=>{const L=Mu(N);L&&(t(Array.from(new Set([...e,L]))),u(""),f(0))},A=N=>{if(N<b.length){const L=b[N];L&&I(L);return}_&&T(g)},O=N=>{if(N.key==="ArrowDown"){N.preventDefault(),f(L=>Math.min(R-1,L+1));return}if(N.key==="ArrowUp"){N.preventDefault(),f(L=>Math.max(0,L-1));return}if(N.key==="Enter"){N.preventDefault(),A(p);return}},F=N=>{t(e.filter(L=>L!==N))};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(N=>a("li",{class:"project-scope-picker-selected-chip",children:[a("span",{children:N}),o?null:a("button",{"aria-label":`Remove ${N}`,class:"project-scope-picker-selected-remove",onClick:()=>F(N),type:"button",children:"×"})]},N))}),a(By,{onOpenChange:N=>{l(N),N||(u(""),f(0))},open:c,children:[a(Nx,{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(qy,{children:a(Uy,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[a("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:N=>{u(N.currentTarget.value),f(0)},onKeyDown:O,placeholder:"Search or create…",ref:m,type:"text",value:d}),a("div",{class:"project-scope-picker-results",role:"listbox",children:[b.length===0&&!_?a("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((N,L)=>{const D=e.includes(N);return a("button",{"aria-selected":D,class:L===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{f(L),I(N)},onMouseEnter:()=>f(L),role:"option",type:"button",children:[a("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:D?"✓":""}),a("span",{class:"project-scope-picker-row-label",children:N})]},N)}),_?a("button",{"aria-selected":!1,class:p===b.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:()=>T(g),onMouseEnter:()=>f(b.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 Ex=Object.defineProperty,nr=(e,t)=>Ex(e,"name",{value:t,configurable:!0}),Fu="Switch",[Ax,K2]=dt(Fu),[xx,Bu]=Ax(Fu);function Hy(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]=At({prop:n,defaultProp:i??!1,onChange:l,caller:Fu}),[v,g]=x(null),[h,b]=x(null),w=B(!1),[_,R]=In(T=>T+1,0),I={checked:f,setChecked:m,disabled:o,control:v,setControl:g,name:c,form:s,value:u,hasConsumerStoppedPropagationRef:w,userInteractionCount:_,onUserInteraction:R,required:d,defaultChecked:i,isFormControl:v?!!s||!!v.closest("form"):!0,bubbleInput:h,setBubbleInput:b};return a(xx,{scope:t,...I,children:Vy(p)?p(I):r})}nr(Hy,"SwitchProvider");var Dx="SwitchTrigger",Lx=J(nr(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}=Bu(Dx,t),b=Re(i,p),w=B(d);return V(()=>{const _=s?o?.ownerDocument.getElementById(s):o?.form;if(_ instanceof HTMLFormElement){const R=nr(()=>f(w.current),"reset");return _.addEventListener("reset",R),()=>_.removeEventListener("reset",R)}},[o,s,f]),a(ye.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":qu(d),"data-disabled":l?"":void 0,disabled:l,value:c,...r,ref:b,onClick:te(n,_=>{v(),f(R=>!R),h&&g&&(m.current=_.isPropagationStopped(),m.current||_.stopPropagation())})})},"SwitchTrigger")),$x=J(nr(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(Hy,{__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(Lx,{...f,ref:n,__scopeSwitch:r}),m&&a(Fx,{__scopeSwitch:r})]})})},"Switch")),Ox="SwitchThumb",jx=J(nr(function(t,n){const{__scopeSwitch:r,...i}=t,o=Bu(Ox,r);return a(ye.span,{"data-state":qu(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n})},"SwitchThumb")),Mx="SwitchBubbleInput",Fx=J(nr(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}=Bu(Mx,t),b=Re(i,h),w=ec(o),_=B(!1),R=B(l),I=B(c);V(()=>{const A=g;if(!A)return;const O=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(O,"checked").set,N=c!==I.current;I.current=c;const L=R.current!==l;R.current=l;const D=!(N&&s.current);if(L&&F){_.current=!N;const G=new Event("click",{bubbles:D});F.call(A,l),A.dispatchEvent(G),_.current=!1}},[g,l,s,c]);const T=B(l);return a(ye.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??T.current,required:u,disabled:p,name:f,value:m,form:v,...r,tabIndex:-1,ref:b,onClick:te(n,A=>{_.current&&A.stopPropagation()}),style:{...r.style,...w,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Vy(e){return typeof e=="function"}nr(Vy,"isFunction");function qu(e){return e?"checked":"unchecked"}nr(qu,"getState");function Gi({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:o,onCheckedChange:s,thumbClassName:c}){return a($x,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:o,onCheckedChange:s,children:a(jx,{className:c})})}function Z(e,t="success"){DN(e,t)}function Mn(e){return String(e||"").trim().replace(/\/+$/u,"")}function Ky(e){return`${jE}:${Mn(e)}`}function Bx(e){try{return localStorage.getItem(Ky(e))||""}catch{return""}}function qx(e,t){try{localStorage.setItem(Ky(e),t)}catch{}}function Fn(){return String(C.coordinatorAdminTargetGroup||"").trim()}function oc(){const e=String(C.lastCoordinatorAdminStatus?.coordinator_url||"").trim(),t=Fn()||String(C.lastCoordinatorAdminStatus?.active_group||"").trim()||rr()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function $t(e){const t=oc();return!!(e&&t&&Mn(e.coordinatorUrl)===Mn(t.coordinatorUrl)&&e.groupId===t.groupId)}function Uu(e){C.coordinatorAdminTargetGroup=e,qx(C.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function rr(){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 Gu(e,t){const n=String(t||"").trim(),r=rr(),i=new Set(r.map(l=>String(l.display_name||"").trim()).filter(Boolean));n&&i.add(n);for(const[l,d]of P.groupPresentationAliases)i.has(d)&&P.groupPresentationAliases.delete(l);if(n)return n;const o=P.groupPresentationAliases.get(e);if(o)return o;for(const l of P.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 P.groupPresentationAliases.set(e,c),c}function Ux(){const e=new Map;for(const t of rr())e.set(t.group_id,t.display_name||"");P.groupRenameDrafts.clear();for(const[t,n]of e.entries())P.groupRenameDrafts.set(t,n)}function Gx(){const e=Fn();return rr().find(t=>t.group_id===e)||null}function zy(){const e=C.lastCoordinatorAdminStatus,t=rr(),n=String(e?.active_group||"").trim(),r=Bx(e?.coordinator_url||null),i=Fn(),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 Uu(c),c}function Hx(){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=P.deviceRenameDrafts.get(i),c=P.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:o),t.set(i,o)}P.deviceRenameDrafts.clear();for(const[r,i]of e.entries())P.deviceRenameDrafts.set(r,i);P.deviceRenameServerNames.clear();for(const[r,i]of t.entries())P.deviceRenameServerNames.set(r,i)}function Vx(e,t){return t&&t.groupId===e?t:null}function Kx(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 zx(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 Wx(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function Jx(e){const t=Wx(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function Yx(e){const t=Vx(e.groupId,e.setupGuide);return{autoGrant:zx(e.preferences,t),defaultSpace:Kx(e.preferences,t),spaces:Jx(e.scopeManagement)}}var Hu=null,ac=null,Vu=null;function Xx(){return Hu}function Ku(e){ac=e}function Wy(e){Vu=e}function Qx(e){return Vu===e}function Zx(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function zu(e){return!Hu||!ac?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function sc(e){Hu=e,Vu?.(e)}function ir(e){const t=ac;ac=null,sc(null),t?.(e)}function e0(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var t0=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=B(null);es(p,()=>f.current,[]);const[m,v]=x(!1),[g,h]=x(-1),b=ke(()=>{const I=t.trim().toLowerCase();return(I?r.filter(T=>T.toLowerCase().includes(I)):r).slice(0,o)},[t,r,o]);V(()=>{g>=b.length&&h(b.length-1)},[b.length,g]);const w=m&&b.length>0,_=I=>{n(I),v(!1),h(-1),f.current?.focus()};return a(By,{open:w,onOpenChange:v,children:[a(Px,{asChild:!0,children:a("input",{...u,ref:f,className:d,value:t,onInput:I=>{n(I.currentTarget.value),v(!0),h(-1)},onFocus:I=>{c?.(I)},onBlur:I=>{window.setTimeout(()=>v(!1),120),l?.(I)},onKeyDown:I=>{if(I.key==="ArrowDown"){I.preventDefault(),v(!0),h(T=>b.length===0?-1:Math.min(T+1,b.length-1));return}if(I.key==="ArrowUp"){I.preventDefault(),m||v(!0),h(T=>Math.max(T-1,-1));return}if(I.key==="Escape"&&w){I.preventDefault(),v(!1),h(-1);return}if((I.key==="Tab"||I.key==="Enter")&&g>=0){const T=b[g];if(T){I.preventDefault(),_(T);return}}if(I.key==="Enter"&&i){I.preventDefault(),i();return}s?.(I)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":g>=0?`autocomplete-option-${g}`:void 0})}),a(qy,{children:a(Uy,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:I=>I.preventDefault(),onCloseAutoFocus:I=>I.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:a("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((I,T)=>{const A=T===g;return a("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${T}`,onMouseDown:O=>{O.preventDefault(),_(I)},onMouseEnter:()=>h(T),role:"option",tabIndex:-1,children:I},I)})})})})]})}),n0=Object.defineProperty,gt=(e,t)=>n0(e,"name",{value:t,configurable:!0}),Jy="Radio",[r0,Yy]=dt(Jy),[i0,cc]=r0(Jy);function Xy(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=B(!1),[h,b]=In(_=>_+1,0),w={checked:n,disabled:i,required:l,name:s,form:o,value:d,control:p,setControl:f,hasConsumerStoppedPropagationRef:g,userInteractionCount:h,onUserInteraction:b,isFormControl:p?!!o||!!p.closest("form"):!0,bubbleInput:m,setBubbleInput:v,onCheck:gt(()=>c?.(),"onCheck")};return a(i0,{scope:t,...w,children:Qy(u)?u(w):r})}gt(Xy,"RadioProvider");var o0="RadioTrigger",a0=J(gt(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}=cc(o0,t),v=Re(i,l);return a(ye.button,{type:"button",role:"radio","aria-checked":o,"data-state":Wu(o),"data-disabled":s?"":void 0,disabled:s,value:c,...r,ref:v,onClick:te(n,g=>{o||(p(),d()),m&&f&&(u.current=g.isPropagationStopped(),u.current||g.stopPropagation())})})},"RadioTrigger")),s0="RadioIndicator",c0=J(gt(function(t,n){const{__scopeRadio:r,forceMount:i,...o}=t,s=cc(s0,r);return a(kt,{present:i||s.checked,children:a(ye.span,{"data-state":Wu(s.checked),"data-disabled":s.disabled?"":void 0,...o,ref:n})})},"RadioIndicator")),l0="RadioBubbleInput",d0=J(gt(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}=cc(l0,t),h=Re(i,m),b=ec(o),w=B(!1),_=B(s),R=B(g);V(()=>{const T=f;if(!T)return;const A=window.HTMLInputElement.prototype,O=Object.getOwnPropertyDescriptor(A,"checked").set,F=g!==R.current;R.current=g;const N=_.current!==s;_.current=s;const L=!(F&&v.current);if(N&&O){w.current=!F;const D=new Event("click",{bubbles:L});O.call(T,s),T.dispatchEvent(D),w.current=!1}},[f,s,v,g]);const I=B(s);return a(ye.input,{type:"radio","aria-hidden":!0,defaultChecked:I.current,required:c,disabled:l,name:d,value:u,form:p,...r,tabIndex:-1,ref:h,onClick:te(n,T=>{w.current&&T.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function Qy(e){return typeof e=="function"}gt(Qy,"isFunction");function Wu(e){return e?"checked":"unchecked"}gt(Wu,"getState");var u0=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ju="RadioGroup",[p0,z2]=dt(Ju,[Oi,Yy]),Zy=Oi(),lc=Yy(),[f0,m0]=p0(Ju),h0=J(gt(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=Zy(r),h=$i(p),[b,w]=At({prop:c,defaultProp:s??null,onChange:m,caller:Ju}),[_,R]=x(null),I=Re(n,R),T=B(b);return V(()=>{const A=o?_?.ownerDocument.getElementById(o):_?.closest("form");if(A instanceof HTMLFormElement){const O=gt(()=>w(T.current),"reset");return A.addEventListener("reset",O),()=>A.removeEventListener("reset",O)}},[_,o,w]),a(f0,{scope:r,name:i,form:o,required:l,disabled:d,value:b,onValueChange:w,children:a(uu,{asChild:!0,...g,orientation:u,dir:h,loop:f,children:a(ye.div,{role:"radiogroup","aria-required":l,"aria-orientation":u,"data-disabled":d?"":void 0,dir:h,...v,ref:I})})})},"RadioGroup")),g0="RadioGroupItemProvider",v0="RadioGroupItemTrigger";function eb(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:i,internal_do_not_use_render:o}=e,s=m0(g0,t),c=lc(t),l=s.disabled||r;return a(Xy,{...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})}gt(eb,"RadioGroupItemProvider");var y0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=Zy(r),s=lc(r),{checked:c,disabled:l}=cc(v0,s.__scopeRadio),d=B(null),u=Re(n,d),p=B(!1);return V(()=>{const f=gt(v=>{u0.includes(v.key)&&(p.current=!0)},"handleKeyDown"),m=gt(()=>p.current=!1,"handleKeyUp");return document.addEventListener("keydown",f),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",m)}},[]),a(pu,{asChild:!0,...o,focusable:!l,active:c,children:a(a0,{...s,...i,ref:u,onKeyDown:te(i.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:te(i.onFocus,()=>{p.current&&d.current?.click()})})})},"RadioGroupItemTrigger")),b0=J(gt(function(t,n){const{__scopeRadioGroup:r,value:i,disabled:o,...s}=t;return a(eb,{__scopeRadioGroup:r,value:i,disabled:o,internal_do_not_use_render:({isFormControl:c})=>a(z,{children:[a(y0,{...s,ref:n,__scopeRadioGroup:r}),c&&a(_0,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),_0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=lc(r);return a(d0,{...o,...i,ref:n})},"RadioGroupItemBubbleInput")),w0=J(gt(function(t,n){const{__scopeRadioGroup:r,...i}=t,o=lc(r);return a(c0,{...o,...i,ref:n})},"RadioGroupIndicator"));function S0({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:o,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return a(h0,{"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(b0,{id:m,"aria-labelledby":v,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:a(w0,{className:r})}),a("span",{className:o,id:v,children:p.label})]},p.value)})})}var C0=Object.defineProperty,R0=(e,t)=>C0(e,"name",{value:t,configurable:!0});function Yu(e,[t,n]){return Math.min(n,Math.max(t,e))}R0(Yu,"clamp");var I0=Object.defineProperty,k0=(e,t)=>I0(e,"name",{value:t,configurable:!0});function tb(e){const t=B({value:e,previous:e});return ke(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}k0(tb,"usePrevious");var T0=Object.defineProperty,Me=(e,t)=>T0(e,"name",{value:t,configurable:!0}),P0=[" ","Enter","ArrowUp","ArrowDown"],N0=[" ","Enter"],Hi="Select",[dc,Xu,E0]=Fo(Hi),[Br,W2]=dt(Hi,[E0,tr]),Qu=tr(),[A0,or]=Br(Hi),[x0,D0]=Br(Hi);function nb(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=Qu(t),[b,w]=x(null),[_,R]=x(null),[I,T]=x(!1),A=$i(d),[O,F]=At({prop:r,defaultProp:i??!1,onChange:o,caller:Hi}),[N,L]=At({prop:s,defaultProp:c,onChange:l,caller:Hi}),D=B(null),G=B(N);V(()=>{const oe=v?b?.ownerDocument.getElementById(v):b?.form;if(oe instanceof HTMLFormElement){const ie=Me(()=>L(G.current),"reset");return oe.addEventListener("reset",ie),()=>oe.removeEventListener("reset",ie)}},[v,b,L]);const q=b?!!v||!!b.closest("form"):!0,[$,E]=x(new Set),S=Et(),M=Array.from($).map(oe=>oe.props.value).join(";"),H=ae(oe=>{E(ie=>new Set(ie).add(oe))},[]),U=ae(oe=>{E(ie=>{const se=new Set(ie);return se.delete(oe),se})},[]),re={required:m,trigger:b,onTriggerChange:w,valueNode:_,onValueNodeChange:R,valueNodeHasChildren:I,onValueNodeHasChildrenChange:T,contentId:S,value:N,onValueChange:L,open:O,onOpenChange:F,dir:A,triggerPointerDownPosRef:D,disabled:f,name:u,autoComplete:p,form:v,nativeOptions:$,nativeSelectKey:M,isFormControl:q};return a(nc,{...h,children:a(A0,{scope:t,...re,children:a(dc.Provider,{scope:t,children:a(x0,{scope:t,onNativeOptionAdd:H,onNativeOptionRemove:U,children:sb(g)?g(re):n})})})})}Me(nb,"SelectProvider");var L0=Me(e=>{const{__scopeSelect:t,children:n,...r}=e;return a(nb,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:i})=>a(z,{children:[n,i?a(rD,{__scopeSelect:t}):null]})})},"Select"),$0="SelectTrigger",O0=J(Me(function(t,n){const{__scopeSelect:r,disabled:i=!1,...o}=t,s=Qu(r),c=or($0,r),l=c.disabled||i,d=Re(n,c.onTriggerChange),u=Xu(r),p=B("touch"),[f,m,v]=ep(h=>{const b=u().filter(_=>!_.disabled),w=tp(b,h,b.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(Xo,{asChild:!0,...s,children:a(ye.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":Zo(c.value)?"":void 0,...o,ref:d,onClick:te(o.onClick,h=>{h.currentTarget.focus(),p.current!=="mouse"&&g(h)}),onPointerDown:te(o.onPointerDown,h=>{p.current=h.pointerType;const b=h.target;b.hasPointerCapture(h.pointerId)&&b.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:te(o.onKeyDown,h=>{const b=f.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(b&&h.key===" ")&&P0.includes(h.key)&&(g(),h.preventDefault())})})})},"SelectTrigger")),j0="SelectValue",M0=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,children:s,placeholder:c="",...l}=t,d=or(j0,r),{onValueNodeHasChildrenChange:u}=d,p=s!==void 0,f=Re(n,d.onValueNodeChange);Ze(()=>{u(p)},[u,p]);const m=Zo(d.value);return a(ye.span,{...l,asChild:m?!1:l.asChild,ref:f,style:{pointerEvents:"none"},children:a(z,{children:m?c:s},m?"placeholder":"value")})},"SelectValue")),F0=J(Me(function(t,n){const{__scopeSelect:r,children:i,...o}=t;return a(ye.span,{"aria-hidden":!0,...o,ref:n,children:i||"▼"})},"SelectIcon")),[B0,q0]=Br("SelectPortal",{forceMount:void 0}),U0=Me(e=>{const{__scopeSelect:t,forceMount:n,...r}=e;return a(B0,{scope:e.__scopeSelect,forceMount:n,children:a(_i,{asChild:!0,...r})})},"SelectPortal"),qr="SelectContent",G0=J(Me(function(t,n){const r=q0(qr,t.__scopeSelect),{forceMount:i=r.forceMount,...o}=t,s=or(qr,t.__scopeSelect),[c,l]=x();return Ze(()=>{l(new DocumentFragment)},[]),a(kt,{present:i||s.open,children:({present:d})=>d?a(K0,{...o,ref:n}):a(H0,{...o,fragment:c})})},"SelectContent")),H0=J(Me(function(t,n){const{__scopeSelect:r,children:i,fragment:o}=t;return o?sn(a(rb,{scope:r,children:a(dc.Slot,{scope:r,children:a("div",{ref:n,children:i})})}),o):null},"SelectContentFragment")),Qt=10,[rb,uc]=Br(qr),V0=cn("SelectContent.RemoveScroll"),K0=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:b,...w}=t,_=or(qr,r),[R,I]=x(null),[T,A]=x(null),O=Re(n,I),[F,N]=x(null),[L,D]=x(null),G=Xu(r),[q,$]=x(!1),E=B(!1);V(()=>{if(R)return hs(R)},[R]),Ci();const S=ae(le=>{const[ve,...X]=G().map(fe=>fe.ref.current),[ce]=X.slice(-1),be=document.activeElement;for(const fe of le)if(fe===be||(fe?.scrollIntoView({block:"nearest"}),fe===ve&&T&&(T.scrollTop=0),fe===ce&&T&&(T.scrollTop=T.scrollHeight),fe?.focus(),document.activeElement!==be))return},[G,T]),M=ae(()=>S([F,R]),[S,F,R]);V(()=>{q&&M()},[q,M]);const{onOpenChange:H,triggerPointerDownPosRef:U}=_;V(()=>{if(R){let le={x:0,y:0};const ve=Me(ce=>{le={x:Math.abs(Math.round(ce.pageX)-(U.current?.x??0)),y:Math.abs(Math.round(ce.pageY)-(U.current?.y??0))}},"handlePointerMove"),X=Me(ce=>{le.x<=10&&le.y<=10?ce.preventDefault():ce.composedPath().includes(R)||H(!1),document.removeEventListener("pointermove",ve),U.current=null},"handlePointerUp");return U.current!==null&&(document.addEventListener("pointermove",ve),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ve),document.removeEventListener("pointerup",X,{capture:!0})}}},[R,H,U]),V(()=>{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[re,oe]=ep(le=>{const ve=G().filter(ce=>!ce.disabled),X=tp(ve,le,ve.find(ce=>ce.ref.current===document.activeElement));X&&setTimeout(()=>X.ref.current?.focus())}),ie=ae((le,ve,X)=>{const ce=!E.current&&!X;(_.value!==void 0&&_.value===ve||ce)&&(N(le),ce&&(E.current=!0))},[_.value]),se=ae(()=>R?.focus(),[R]),ue=ae((le,ve,X)=>{const ce=!E.current&&!X;(_.value!==void 0&&_.value===ve||ce)&&D(le)},[_.value]),Pe=i==="popper"?ib:z0,Ie=Pe===ib?{side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:f,collisionBoundary:m,collisionPadding:v,sticky:g,hideWhenDetached:h,avoidCollisions:b}:{};return a(rb,{scope:r,content:R,viewport:T,onViewportChange:A,itemRefCallback:ie,selectedItem:F,onItemLeave:se,itemTextRefCallback:ue,focusSelectedItem:M,selectedItemText:L,position:i,isPositioned:q,searchRef:re,children:a(To,{as:V0,allowPinchZoom:!0,children:a(as,{asChild:!0,trapped:_.open,onMountAutoFocus:le=>{le.preventDefault()},onUnmountAutoFocus:te(o,le=>{_.trigger?.focus({preventScroll:!0}),le.preventDefault()}),children:a(bi,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:c,onFocusOutside:le=>le.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:a(Pe,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:le=>le.preventDefault(),...w,...Ie,onPlaced:()=>$(!0),ref:O,style:{display:"flex",flexDirection:"column",outline:"none",...w.style},onKeyDown:te(w.onKeyDown,le=>{const ve=le.ctrlKey||le.altKey||le.metaKey;if(le.key==="Tab"&&le.preventDefault(),!ve&&le.key.length===1&&oe(le.key),["ArrowUp","ArrowDown","Home","End"].includes(le.key)){let X=G().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(le.key)&&(X=X.slice().reverse()),["ArrowUp","ArrowDown"].includes(le.key)){const ce=le.target,be=X.indexOf(ce);X=X.slice(be+1)}setTimeout(()=>S(X)),le.preventDefault()}})})})})})})},"SelectContentImpl")),z0=J(Me(function(t,n){const{__scopeSelect:r,onPlaced:i,...o}=t,s=or(qr,r),c=uc(qr,r),[l,d]=x(null),[u,p]=x(null),f=Re(n,p),m=Xu(r),v=B(!1),g=B(!0),{viewport:h,selectedItem:b,selectedItemText:w,focusSelectedItem:_}=c,R=ae(()=>{if(s.trigger&&s.valueNode&&l&&u&&h&&b&&w){const O=s.trigger.getBoundingClientRect(),F=u.getBoundingClientRect(),N=s.valueNode.getBoundingClientRect(),L=w.getBoundingClientRect();if(s.dir!=="rtl"){const ce=L.left-F.left,be=N.left-ce,fe=O.left-be,We=O.width+fe,he=Math.max(We,F.width),W=window.innerWidth-Qt,de=Yu(be,[Qt,Math.max(Qt,W-he)]);l.style.minWidth=We+"px",l.style.left=de+"px"}else{const ce=F.right-L.right,be=window.innerWidth-N.right-ce,fe=window.innerWidth-O.right-be,We=O.width+fe,he=Math.max(We,F.width),W=window.innerWidth-Qt,de=Yu(be,[Qt,Math.max(Qt,W-he)]);l.style.minWidth=We+"px",l.style.right=de+"px"}const D=m(),G=window.innerHeight-Qt*2,q=h.scrollHeight,$=window.getComputedStyle(u),E=parseInt($.borderTopWidth,10),S=parseInt($.paddingTop,10),M=parseInt($.borderBottomWidth,10),H=parseInt($.paddingBottom,10),U=E+S+q+H+M,re=Math.min(b.offsetHeight*5,U),oe=window.getComputedStyle(h),ie=parseInt(oe.paddingTop,10),se=parseInt(oe.paddingBottom,10),ue=O.top+O.height/2-Qt,Pe=G-ue,Ie=b.offsetHeight/2,le=b.offsetTop+Ie,ve=E+S+le,X=U-ve;if(ve<=ue){const ce=D.length>0&&b===D[D.length-1].ref.current;l.style.bottom="0px";const be=u.clientHeight-h.offsetTop-h.offsetHeight,fe=ve+Math.max(Pe,Ie+(ce?se:0)+be+M);l.style.height=fe+"px"}else{const ce=D.length>0&&b===D[0].ref.current;l.style.top="0px";const be=Math.max(ue,E+h.offsetTop+(ce?ie:0)+Ie)+X;l.style.height=be+"px",h.scrollTop=ve-ue+h.offsetTop}l.style.margin=`${Qt}px 0`,l.style.minHeight=re+"px",l.style.maxHeight=G+"px",i?.(),requestAnimationFrame(()=>v.current=!0)}},[m,s.trigger,s.valueNode,l,u,h,b,w,s.dir,i]);Ze(()=>R(),[R]);const[I,T]=x();Ze(()=>{u&&T(window.getComputedStyle(u).zIndex)},[u]);const A=ae(O=>{O&&g.current===!0&&(R(),_?.(),g.current=!1)},[R,_]);return a(W0,{scope:r,contentWrapper:l,shouldExpandOnScrollRef:v,onScrollButtonChange:A,children:a("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:I},children:a(ye.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})},"SelectItemAlignedPosition")),ib=J(Me(function(t,n){const{__scopeSelect:r,align:i="start",collisionPadding:o=Qt,...s}=t,c=Qu(r);return a(rc,{...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")),[W0,J0]=Br(qr,{}),ob="SelectViewport",Y0=J(Me(function(t,n){const{__scopeSelect:r,nonce:i,...o}=t,s=uc(ob,r),c=J0(ob,r),l=Re(n,s.onViewportChange),d=B(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(dc.Slot,{scope:r,children:a(ye.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:te(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-Qt*2,h=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),w=Math.max(h,b);if(w<g){const _=w+v,R=Math.min(g,_),I=_-R;f.style.height=R+"px",f.style.bottom==="0px"&&(p.scrollTop=I>0?I:0,f.style.justifyContent="flex-end")}}}d.current=p.scrollTop})})})]})},"SelectViewport")),[J2,Y2]=Br("SelectGroup"),Zu="SelectItem",[X0,ab]=Br(Zu),Q0=J(Me(function(t,n){const{__scopeSelect:r,value:i,disabled:o=!1,textValue:s,...c}=t,l=or(Zu,r),d=uc(Zu,r),u=l.value===i,[p,f]=x(s??""),[m,v]=x(!1),g=ht(R=>d.itemRefCallback?.(R,i,o)),h=Re(n,g),b=Et(),w=B("touch"),_=Me(()=>{o||(l.onValueChange(i),l.onOpenChange(!1))},"handleSelect");return a(X0,{scope:r,value:i,disabled:o,textId:b,isSelected:u,onItemTextChange:ae(R=>{f(I=>I||(R?.textContent??"").trim())},[]),children:a(dc.ItemSlot,{scope:r,value:i,disabled:o,textValue:p,children:a(ye.div,{role:"option","aria-labelledby":b,"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:te(c.onFocus,()=>v(!0)),onBlur:te(c.onBlur,()=>v(!1)),onClick:te(c.onClick,()=>{w.current!=="mouse"&&_()}),onPointerUp:te(c.onPointerUp,()=>{w.current==="mouse"&&_()}),onPointerDown:te(c.onPointerDown,R=>{w.current=R.pointerType}),onPointerMove:te(c.onPointerMove,R=>{w.current=R.pointerType,o?d.onItemLeave?.():w.current==="mouse"&&R.currentTarget.focus({preventScroll:!0})}),onPointerLeave:te(c.onPointerLeave,R=>{R.currentTarget===document.activeElement&&d.onItemLeave?.()}),onKeyDown:te(c.onKeyDown,R=>{o||R.target!==R.currentTarget||d.searchRef?.current!==""&&R.key===" "||(N0.includes(R.key)&&_(),R.key===" "&&R.preventDefault())})})})})},"SelectItem")),pc="SelectItemText",Z0=J(Me(function(t,n){const{__scopeSelect:r,className:i,style:o,...s}=t,c=or(pc,r),l=uc(pc,r),d=ab(pc,r),u=D0(pc,r),[p,f]=x(null),m=ht(_=>l.itemTextRefCallback?.(_,d.value,d.disabled)),v=Re(n,f,d.onItemTextChange,m),g=p?.textContent,h=ke(()=>a("option",{value:d.value,disabled:d.disabled,children:g},d.value),[d.disabled,d.value,g]),{onNativeOptionAdd:b,onNativeOptionRemove:w}=u;return Ze(()=>(b(h),()=>w(h)),[b,w,h]),a(z,{children:[a(ye.span,{id:d.textId,...s,ref:v}),d.isSelected&&c.valueNode&&!c.valueNodeHasChildren&&!Zo(c.value)?sn(s.children,c.valueNode):null]})},"SelectItemText")),eD="SelectItemIndicator",tD=J(Me(function(t,n){const{__scopeSelect:r,...i}=t;return ab(eD,r).isSelected?a(ye.span,{"aria-hidden":!0,...i,ref:n}):null},"SelectItemIndicator")),nD="SelectBubbleInput",rD=J(Me(function({__scopeSelect:t,...n},r){const i=or(nD,t),{value:o,onValueChange:s,required:c,disabled:l,name:d,autoComplete:u,form:p}=i,{nativeOptions:f,nativeSelectKey:m}=i,v=B(null),g=Re(r,v),h=o??"",b=tb(h),w=Array.from(f).some(_=>(_.props.value??"")==="");return V(()=>{const _=v.current;if(!_)return;const R=window.HTMLSelectElement.prototype,I=Object.getOwnPropertyDescriptor(R,"value").set;if(b!==h&&I){const T=new Event("change",{bubbles:!0});I.call(_,h),_.dispatchEvent(T)}},[b,h]),a(ye.select,{"aria-hidden":!0,required:c,tabIndex:-1,name:d,autoComplete:u,disabled:l,form:p,onChange:_=>s(_.target.value),...n,style:{...Tv,...n.style},ref:g,defaultValue:h,children:[Zo(o)&&!w?a("option",{value:""}):null,Array.from(f)]},m)},"SelectBubbleInput"));function sb(e){return typeof e=="function"}Me(sb,"isFunction");function Zo(e){return e===""||e===void 0}Me(Zo,"shouldShowPlaceholder");function ep(e){const t=ht(e),n=B(""),r=B(0),i=ae(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=ae(()=>{n.current="",window.clearTimeout(r.current)},[]);return V(()=>()=>window.clearTimeout(r.current),[]),[n,i,o]}Me(ep,"useTypeaheadSearch");function tp(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=cb(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(tp,"findNextItem");function cb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Me(cb,"wrapArray");var lb="__codemem-empty-select__";function iD(){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 oD(){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 np(e){return e===""?lb:e}function aD(e){return e===lb?"":e}function ar({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?np(u):void 0;return a(L0,{disabled:r,onValueChange:m=>s(aD(m)),value:f,children:[a(O0,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[a(M0,{placeholder:l}),a(F0,{className:"sync-radix-select-icon","aria-hidden":"true",children:a(iD,{})})]}),a(U0,{children:a(G0,{className:n,position:"popper",children:a(Y0,{className:p,children:c.map(m=>a(Q0,{className:o,disabled:m.disabled,value:np(m.value),children:[a(Z0,{children:m.label}),a(tD,{className:"sync-radix-select-indicator",children:a(oD,{})})]},np(m.value)))})})})]})}function sD({descriptionId:e,request:t}){const[n,r]=x("choice"),i=t.actors.find(b=>b.isLocal)?.actorId||t.actors[0]?.actorId||"",[o,s]=x(i),[c,l]=x("");V(()=>{r("choice");const b=t.actors.find(_=>_.isLocal)?.actorId||t.actors[0]?.actorId||"",w=t.actors.find(_=>_.actorId!==b)?.actorId||"";s(b),l(w)},[t]);const d=t.actors.find(b=>b.actorId===o)||t.actors[0],u=t.actors.filter(b=>b.actorId!==o),p=u.find(b=>b.actorId===c)||u[0],f=t.actors.map(b=>({label:a(z,{children:[b.label,b.isLocal?" (You)":""]}),value:b.actorId})),m=u.map(b=>({label:`${b.label}${b.isLocal?" (You)":""}`,value:b.actorId})),v=!!(d?.actorId&&p?.actorId),g=()=>{!d?.actorId||!p?.actorId||ir({action:"merge",primaryActorId:d.actorId,secondaryActorId:p.actorId})},h=b=>{const w=b.target instanceof HTMLElement?b.target:null;b.defaultPrevented||b.isComposing||b.key!=="Enter"||w?.closest(".sync-dialog-radio-list")&&v&&(b.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:()=>ir({action:"different-people"}),type:"button",children:"These are different people"})}),a("li",{children:a("button",{className:"settings-button",onClick:()=>ir({action:"cancel"}),type:"button",children:"Decide later"})})]})}):a("div",{className:"sync-dialog-stack",onKeyDown:b=>{h(b),Li(b,{onSubmit:g,disabled:!v})},children:[a("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),a(S0,{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(ar,{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 cD({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";V(()=>{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"){ir(!0);return}if(t.kind==="duplicate-person")return;const f=r.trim(),m=t.validate?.(f)||null;if(m){s(m);return}ir(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(kr,{ariaLabel:`Close ${t.title}`,onClick:()=>ir(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(t0,{"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(Te,{"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(sD,{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:()=>ir(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?a("button",{autoFocus:!0,className:`settings-button ${e0(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function lD(){const[e,t]=x(Xx());V(()=>(Wy(t),()=>{Qx(t)&&Wy(null)}),[]);const n=!!e,r=ke(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=ke(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?a(Qn,{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||ir(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?a(cD,{descriptionId:i,request:e,titleId:r}):null}):null}var Ur=null;function fc(){Ur?.isConnected||(Ur=document.getElementById("syncDialogMount"),Ur||(Ur=document.createElement("div"),Ur.id="syncDialogMount",document.body.appendChild(Ur)),Ue(a(lD,{}),Ur))}function hn(e){return fc(),zu("confirm")?new Promise(t=>{Ku(n=>t(!!n)),sc({kind:"confirm",...e})}):Promise.resolve(!1)}function rp(e){return fc(),zu("input")?new Promise(t=>{Ku(n=>t(typeof n=="string"?n:null)),sc({kind:"input",...e})}):Promise.resolve(null)}function dD(e){return fc(),zu("duplicate-person")?new Promise(t=>{Ku(n=>t(n||{action:"cancel"})),sc({kind:"duplicate-person",...e})}):Promise.resolve(Zx({kind:"duplicate-person",...e}))}function uD(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 pD(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function db(e){const t=String(e.label||"").trim()||"Untitled Space",n=pD(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 fD(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 mD(e,t,n){return`Revoke ${t||"this device"} from ${db(e).title}?`}function hD(e,t,n=Fs()){const r=Bs(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 gD(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 X2=8;function vD(){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 mc(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 qe(e){let t=P.groupScopeManagementDrafts.get(e);return t||(t=vD(),P.groupScopeManagementDrafts.set(e,t)),t}function Ke(e,t){P.groupScopeManagementDrafts.set(e,t)}function ip(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 ea(){Z("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning")}function Vi(e,t){return e.availability==="fresh"&&!e.loading&&(!t||e.memberAvailabilityByScope.get(t)==="fresh")&&xn(P.recovery,"status","groups")}async function yD(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 Gr(e,t,n=qe(e).includeInactive){const r=qe(e),i=r.loadGeneration+1;Ke(e,{...r,loading:!0,error:"",includeInactive:n,loadGeneration:i,recoveryAnnouncement:r.recoveryRetryRequested?r.recoveryAnnouncement:""});const o=()=>P.groupScopeManagementDrafts.get(e)?.loadGeneration===i;t();try{const[l,d]=await Promise.all([IC(e,n),mm(e,!0)]);if(!o())return;const u=mc(l),p=mc(d),f=await yD(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:mc(await fm(e,_,!0))}}catch{return{scopeId:_,attempted:!0}}});if(!o())return;const m=qe(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),R=m.memberAvailabilityByScope.get(w.scopeId);_&&(R==="fresh"||R==="stale")?(g.set(w.scopeId,_),h.set(w.scopeId,"stale")):h.set(w.scopeId,w.attempted?"unavailable":"deferred")}const b=v.filter(w=>w.attempted&&w.scopeId&&!w.members).length;Ke(e,{...m,loaded:!0,loading:!1,availability:"fresh",recoveryAnnouncement:b?"":m.recoveryAnnouncement,error:b?`Membership details could not be refreshed for ${b} ${b===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=qe(e),d=l.availability==="fresh"||l.availability==="stale";Ke(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=qe(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;Ke(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&&Ke(e,{...s,recoveryAnnouncement:"Retry finished, but some Space data still needs attention. Retained details remain unchanged.",recoveryFocusPending:!0,recoveryRetryRequested:!1});t();const c=qe(e);c.recoveryFocusPending&&(Ke(e,{...c,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coordinatorAdminSpacesStatus-${e}`)?.focus()))}function op(e,t){P.groupScopeManagementOpen.add(e),qe(e),t(),Gr(e,t)}function ub(e,t){P.groupScopeManagementOpen.delete(e),t()}async function bD(e,t,n){const r=qe(e);if(!Vi(r)){ea();return}if(r.actionPendingKey)return;const i=r.loadGeneration,o=P.loadGeneration;Ke(e,{...r,actionPendingKey:`load:${t}`,actionPendingKind:"load"}),n();try{const s=await fm(e,t,!0),c=qe(e);if(c.loadGeneration!==i||P.loadGeneration!==o||!Vi(c)){c.actionPendingKey===`load:${t}`&&(Ke(e,{...c,actionPendingKey:"",actionPendingKind:""}),n()),ea();return}const l=new Map(c.membersByScope);l.set(t,mc(s));const d=new Map(c.memberAvailabilityByScope);d.set(t,"fresh"),Ke(e,{...c,membersByScope:l,memberAvailabilityByScope:d,actionPendingKey:"",actionPendingKind:"",error:""})}catch{const s=qe(e);if(s.loadGeneration!==i)return;const c=new Map(s.memberAvailabilityByScope);c.set(t,s.membersByScope.has(t)?"stale":"unavailable"),Ke(e,{...s,memberAvailabilityByScope:c,actionPendingKey:"",actionPendingKind:"",error:"Membership details could not be loaded. Existing Space data is unchanged."})}n()}async function _D(e,t){const n=qe(e);if(!Vi(n)){ea();return}if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),o=n.createKind.trim()||"team";if(!r||!i){Z("Enter a Space ID and label before creating a Space.","warning");return}Ke(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await kC(e,{scope_id:r,label:i,kind:o});const s=qe(e);Ke(e,{...s,createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:""}),Z("Space created. Grant devices explicitly before data can sync."),await Gr(e,t,s.includeInactive),queueMicrotask(()=>document.getElementById(`coordinatorAdminCreateSpaceTrigger-${e}`)?.focus())}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(s,"Could not create the legacy Space. Sharing policy is unchanged; retry after coordinator recovery.")}),t()}}async function wD(e,t,n,r){const i=qe(e);if(!Vi(i,t)){ea();return}const o=`grant:${t}:${n}`;if(!i.actionPendingKey){Ke(e,{...i,actionPendingKey:o,actionPendingKind:"grant",error:""}),r();try{await TC(e,t,{device_id:n,role:"member"});const s=qe(e);Ke(e,{...s,actionPendingKey:"",actionPendingKind:""}),Z("Device granted access to the Space."),await Gr(e,r,s.includeInactive)}catch(s){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(s,"Could not grant legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),r()}}}async function SD(e,t,n,r,i){const o=String(t.scope_id||"").trim();if(!o)return;const s=qe(e);if(!Vi(s,o)){ea();return}const c=s.loadGeneration,l=P.loadGeneration;if(!await hn({title:mD(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=qe(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||P.loadGeneration!==l||!Vi(d,o)||!u||!p||d.actionPendingKey){Z("Space membership data changed while confirmation was open. Review current access and try again.","warning");return}const f=`revoke:${o}:${n}`;Ke(e,{...d,actionPendingKey:f,actionPendingKind:"revoke",error:""}),i();try{await PC(e,o,n);const m=qe(e);Ke(e,{...m,actionPendingKey:"",actionPendingKind:""}),Z("Space access revoked. Future sync is blocked for that device."),await Gr(e,i,m.includeInactive)}catch(m){Ke(e,{...qe(e),actionPendingKey:"",actionPendingKind:"",error:ip(m,"Could not revoke legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),i()}}function CD(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=$t(P.devicesSnapshotTarget)?C.lastCoordinatorAdminDevices:[],c=gD(n.devices,s,e,n.devicesLoaded),l=hD(c,n.membersByScope.get(o)??[],P.unnamedDeviceAliases);return l.length?y("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=fD(d);return y("div",{class:"coordinator-admin-scope-member-row",key:d.deviceId},y("div",{class:"coordinator-admin-scope-member-copy"},y("strong",null,d.displayName),y("span",null,v.detail),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("span",{class:"peer-meta"},v.advancedDetail)),d.enabled?null:y("span",null,"Device is disabled in this coordinator group.")),y("div",{class:"peer-actions"},f?y("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{wD(e,o,d.deviceId,i)},type:"button"},p&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,m?y("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{SD(e,t,d.deviceId,d.displayName,i)},type:"button"},p&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):y("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 RD(e,t,n,r,i){const o=String(t.scope_id||"").trim(),s=db(t),c=n.memberAvailabilityByScope.get(o),l=n.actionPendingKey===`load:${o}`,d=c==="stale"||c==="unavailable"||c==="deferred";return y("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:o||s.title},y("div",{class:"peer-title"},y("h5",{class:"coordinator-admin-card-title"},s.title),y("span",{class:"badge actor-badge"},"Legacy Space")),y("div",{class:"peer-submeta"},s.summary),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},s.advancedDetail)),y("div",{class:"peer-submeta"},"Devices below are enrolled in the coordinator group; only active Space members can sync this transport boundary."),c==="stale"?y("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"?y("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"?y("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?y("button",{class:"settings-button",disabled:!!n.actionPendingKey,onClick:()=>{bD(e,o,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:CD(e,t,n,r&&c==="fresh",i))}function ap(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=qe(e);s.loading||s.actionPendingKey||(Ke(e,{...s,recoveryAnnouncement:"Retrying Spaces and membership details…",recoveryRetryRequested:!0}),Gr(e,n,s.includeInactive))};return y("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?y(z,null,y("div",{class:"coordinator-admin-legacy-notice-copy"},y("h4",{class:"coordinator-admin-drawer-title"},"Spaces need attention"),t.recoveryAnnouncement?y("p",{class:"peer-submeta"},t.recoveryAnnouncement):null,y("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.`)),y("button",{class:"settings-button",disabled:t.loading||!!t.actionPendingKey,onClick:o,type:"button"},t.loading?"Retrying…":"Retry")):t.recoveryAnnouncement)}function ID(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,o=P.groupScopeManagementDrafts.get(t);if(!o)return null;const s=uD(r);if(s)return y("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(o.availability==="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("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."),ap(t,o,i));if(!o.loaded)return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("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."),ap(t,o,i),y("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 y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("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."),ap(t,o,i),y(zo,{onOpenChange:f=>{Ke(t,{...qe(t),createPanelOpen:f}),i(),f&&queueMicrotask(()=>document.getElementById(p)?.focus())},open:o.createPanelOpen},y(z,null,y("div",{class:"section-actions coordinator-admin-space-toolbar"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),y(Gi,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:o.includeInactive,className:"coordinator-admin-switch",disabled:l,onCheckedChange:f=>{qe(t).actionPendingKey||Gr(t,i,f)},thumbClassName:"coordinator-admin-switch-thumb"})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:l,onClick:()=>{qe(t).actionPendingKey||Gr(t,i,o.includeInactive)},type:"button"},o.loading?"Refreshing…":"Refresh"),y(Cu,{"aria-controls":d,"aria-expanded":o.createPanelOpen,class:"settings-button coordinator-admin-scope-trigger",id:u,type:"button"},"Create legacy Space"))),y(Wo,{"aria-busy":o.actionPendingKind==="create"?"true":"false","aria-labelledby":u,class:"coordinator-admin-create-space-panel",forceMount:!0,id:d},y("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!c&&_D(t,i)}},y("p",{class:"peer-submeta"},"Create a Space only for legacy transport or recovery. Team membership and Project access stay in Sharing."),y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Space ID"),y(Te,{class:"peer-scope-input",disabled:c,id:p,onInput:f=>{const m=qe(t);Ke(t,{...m,createScopeId:String(f.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:o.createScopeId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Te,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createLabel:String(f.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:o.createLabel})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Te,{class:"peer-scope-input",disabled:c,onInput:f=>{const m=qe(t);Ke(t,{...m,createKind:String(f.currentTarget.value||"")})},placeholder:"team",type:"text",value:o.createKind}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:c,type:"submit"},o.actionPendingKind==="create"?"Creating…":"Create Space")))))),o.error?y("div",{"aria-live":"assertive",class:"peer-submeta coordinator-admin-error",role:"alert"},o.error):null,o.scopes.length?y("div",{class:"coordinator-admin-scope-card-list"},o.scopes.map(f=>RD(t,f,o,n&&o.availability==="fresh"&&!o.loading,i))):y("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 pb(){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 kD(){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 fb(e,t){const n=P.groupPreferencesDrafts.get(e)??kD(),r=n.loadGeneration+1;P.groupPreferencesDrafts.set(e,{...n,loading:!0,error:"",loadGeneration:r,recoveryAnnouncement:n.recoveryRetryRequested?n.recoveryAnnouncement:""});const i=()=>P.groupPreferencesDrafts.get(e)?.loadGeneration===r;t();try{const s=await LR(e);if(!i())return;const c=P.groupPreferencesDrafts.get(e)??n;P.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=P.groupPreferencesDrafts.get(e)??n,c=s.availability==="fresh"||s.availability==="stale",l=s.recoveryRetryRequested;P.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=P.groupPreferencesDrafts.get(e);o?.recoveryFocusPending&&(P.groupPreferencesDrafts.set(e,{...o,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coord-admin-group-defaults-recovery-${e}`)?.focus()))}async function sp(e,t){P.groupPreferencesOpen.add(e),t(),await fb(e,t)}function hc(e,t){P.groupPreferencesOpen.delete(e),t()}function mb(e,t){const n=P.groupPreferencesDrafts.get(e);n&&(P.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),fb(e,t))}async function TD(e,t){const n=P.groupPreferencesDrafts.get(e);if(!n||n.availability!=="fresh"||n.loading||!xn(P.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};P.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await $R(e,r),Z("Legacy coordinator group defaults saved. Sharing policy and Project access are unchanged."),hc(e,t)}catch{const i=P.groupPreferencesDrafts.get(e);if(!i)return;P.groupPreferencesDrafts.set(e,{...i,saving:!1,error:"Could not save legacy group defaults. Sharing policy is unchanged; retry after coordinator recovery."}),t()}}function PD(e,t,n){const r=P.groupPreferencesDrafts.get(e);if(!r)return null;const i=`coord-admin-group-defaults-recovery-${e}`;if(!r.loaded&&r.availability!=="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("div",{"aria-atomic":"true","aria-live":"polite",id:i,role:"status",tabIndex:-1},"Loading project defaults…"));if(r.availability==="unavailable")return y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("div",{"aria-atomic":"true","aria-live":"polite",class:"coordinator-admin-inline-warning coordinator-admin-recovery-notice",id:i,role:"status",tabIndex:-1},y("div",{class:"coordinator-admin-legacy-notice-copy"},y("strong",null,"Group defaults are unavailable"),r.recoveryAnnouncement?y("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,y("span",{class:"peer-submeta"},"Current values could not be loaded. No defaults are being assumed or changed.")),y("button",{class:"settings-button",disabled:r.loading,onClick:()=>mb(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 y(z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),y("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"?y(z,null,y("span",{class:"peer-submeta"},"Previously loaded group defaults are shown. Saving is disabled until refresh succeeds."),r.recoveryAnnouncement?y("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,y("button",{class:"settings-button",disabled:r.loading,onClick:()=>mb(e,t),type:"button"},r.loading?"Retrying…":"Retry")):r.recoveryAnnouncement),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:o},"Auto-apply advanced rules to new devices"),y(Gi,{"aria-labelledby":o,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!d||r.saving,onCheckedChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_seed_scope:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:s},"Auto-grant default Space on coordinator join"),y(Gi,{"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=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,auto_grant_default_space_on_join:p}),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:c},"Include template"),y(Gy,{"aria-labelledby":c,availableProjects:P.availableProjects,disabled:u,emptyLabel:"All projects allowed.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_include:p}),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:l},"Exclude template"),y(Gy,{"aria-labelledby":l,availableProjects:P.availableProjects,disabled:u,emptyLabel:"Nothing excluded.",onValuesChange:p=>{const f=P.groupPreferencesDrafts.get(e)??r;P.groupPreferencesDrafts.set(e,{...f,projects_exclude:p}),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:!d||r.saving,onClick:()=>{TD(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>hc(e,t),type:"button"},"Cancel")))}function ND(e){const t=P.teamSetupGuide;if(!t)return null;const n=Gu(t.groupId,t.displayName),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 legacy group ${n}`),y("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?y("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.`):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 legacy group defaults and the auto-grant default Space setting."),y("li",null,"Use legacy enrollment only when compatibility or recovery requires it."),y("li",null,"Open Sharing for Team membership and Project access.")),y("div",{class:"peer-actions"},y("button",{class:"settings-button",onClick:()=>{P.groupPreferencesOpen.add(t.groupId),sp(t.groupId,e)},type:"button"},"Review legacy defaults"),y("button",{class:"settings-button",onClick:()=>{op(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{P.inviteGroup=t.groupId,P.activeSection="invites",e()},type:"button"},"Create legacy device invite"),y("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Open Projects"),y("button",{class:"settings-button",onClick:()=>{P.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function ED(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function AD(e){const{summary:t,fresh:n,createGroup:r,runGroup:i,renderShell:o,reloadData:s}=e,c=Or(P.recovery,"groups"),l=Mi(P.recovery,"groups"),d=String(C.lastCoordinatorAdminStatus?.active_group||"").trim(),u=Fn(),p=rr(),f=p.filter(b=>!b.archived_at),m=p.filter(b=>b.archived_at),v=P.showArchivedGroups?p:f,g=u?p.some(b=>b.group_id===u):!1,h=[`${f.length} active`];return m.length&&h.push(`${m.length} archived`),y($r,{className:"coordinator-admin-panel",value:"groups"},y("h3",null,"Coordinator groups"),y("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?y("p",{class:"peer-submeta"},h.join(" · ")):null,!g&&u?y("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,ND(o),(()=>{const b=!n||P.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r()}},y("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."),y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New coordinator group ID"),y(Te,{class:"peer-scope-input",disabled:b,onInput:w=>{P.createGroupId=String(w.currentTarget.value||"")},placeholder:"group-alpha",type:"text",value:P.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Legacy group display name"),y(Te,{class:"peer-scope-input",disabled:b,onInput:w=>{P.createGroupDisplayName=String(w.currentTarget.value||"")},placeholder:"Legacy group Alpha",type:"text",value:P.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:b,type:"submit"},P.groupActionPendingKind==="create"?"Creating…":"Create coordinator group")),y("div",{class:"coordinator-admin-secondary-actions"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),y(Gi,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:P.showArchivedGroups,className:"coordinator-admin-switch",onCheckedChange:w=>{P.showArchivedGroups=w,o()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),l?y("div",{class:"peer-meta"},"Complete legacy coordinator setup before loading coordinator groups. No group list is expected yet."):c?v.length?y("div",{class:"peer-list"},v.map(b=>{const w=b.group_id===u,_=P.groupActionPendingId===b.group_id,R=!!b.archived_at,I=P.groupRenameDrafts.get(b.group_id)??b.display_name??"",T=I.trim()||Gu(b.group_id,b.display_name),A=P.groupPreferencesOpen.has(b.group_id),O=P.groupScopeManagementOpen.has(b.group_id),F=R?"unarchive":"archive",N=ED(R,_&&P.groupActionPendingKind===F),L=Yx({groupId:b.group_id,preferences:P.groupPreferencesDrafts.get(b.group_id),scopeManagement:P.groupScopeManagementDrafts.get(b.group_id),setupGuide:P.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:b.group_id},y("div",{class:"peer-title"},y("strong",null,T)),y("div",{class:"peer-submeta"},R?"Archived coordinator group":"Active coordinator group"),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},`Group ID ${b.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,L.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,L.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,L.spaces))),d===b.group_id?y("div",{class:"peer-submeta"},"This node uses this coordinator group for discovery."):null,y("label",{class:"coordinator-admin-field"},y("span",null,"Legacy group display name"),y(Te,{class:"peer-scope-input",disabled:!n||_,onInput:D=>{P.groupRenameDrafts.set(b.group_id,String(D.currentTarget.value||""))},type:"text",value:I})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||w,onClick:()=>{Uu(b.group_id),s()},type:"button"},w?"Managing":"Manage group"),y("button",{class:"settings-button",disabled:!n||_,onClick:()=>i(b.group_id,I,"rename"),type:"button"},_&&P.groupActionPendingKind==="rename"?"Renaming…":"Rename group"),y("button",{"aria-expanded":A,"aria-controls":`coord-admin-project-defaults-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":A?"open":"closed",disabled:_,onClick:()=>{A?hc(b.group_id,o):sp(b.group_id,o)},type:"button"},y("span",null,"Legacy group defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(pb,null))),y("button",{"aria-expanded":O,"aria-controls":`coord-admin-spaces-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":O?"open":"closed",disabled:_,onClick:()=>{O?ub(b.group_id,o):op(b.group_id,o)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(pb,null))),y("button",{class:R?"settings-button":"settings-button danger",disabled:!n||_,onClick:()=>i(b.group_id,b.display_name||b.group_id,F),type:"button"},N)),y(zo,{open:A,onOpenChange:D=>{D?sp(b.group_id,o):hc(b.group_id,o)}},y(Wo,{"aria-label":`Project defaults for ${T}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${b.group_id}`},A?PD(b.group_id,o,n):null)),y(zo,{open:O,onOpenChange:D=>{D?op(b.group_id,o):ub(b.group_id,o)}},y(Wo,{"aria-label":`Spaces for ${T}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${b.group_id}`},O?ID({groupId:b.group_id,ready:n,renderShell:o,summary:t}):null)))})):y("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?P.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."):y("div",{class:"peer-meta coordinator-admin-empty-state"},"Coordinator groups are unavailable. Retry to load current groups; no empty result is being assumed."))}function Ki(e){return a("textarea",{...e})}function xD(e){const{summary:t,fresh:n,createInvite:r,renderShell:i}=e,o=C.lastCoordinatorAdminStatus,s=Fn()||String(o?.active_group||"").trim(),c=P.inviteGroup.trim()||s,l=String(C.lastTeamInvite?.encoded||"").trim(),d=Array.isArray(C.lastTeamInvite?.warnings)?C.lastTeamInvite?.warnings:[],u=!n||P.invitePending;return y($r,{className:"coordinator-admin-panel",value:"invites"},y("h3",null,"Legacy coordinator invites"),y("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."),y("form",{class:"coordinator-admin-form",onSubmit:p=>{p.preventDefault(),!u&&r()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Coordinator group"),y(Te,{class:"peer-scope-input",disabled:!n,onInput:p=>{P.inviteGroup=String(p.currentTarget.value||""),i()},placeholder:s||"group-alpha",type:"text",value:P.inviteGroup})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(ar,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:!n,id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:p=>{P.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:P.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Te,{class:"peer-scope-input",disabled:!n,min:"1",onInput:p=>{P.inviteTtlHours=String(p.currentTarget.value||"")},type:"number",value:P.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:u,type:"submit"},P.invitePending?"Creating…":"Create legacy coordinator invite"),c?y("span",{class:"peer-submeta"},"Using the selected coordinator group"):null)),l?y("label",{class:"coordinator-admin-field"},y("span",null,"Generated invite"),y(Ki,{class:"feed-search coordinator-admin-output",readOnly:!0,value:l}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:p=>Uo(l,p.currentTarget)},"Copy")):null,d?.length?y("div",{class:"peer-meta coordinator-admin-warning-list"},d.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."),C.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...C.lastShareOperations.map(p=>y("li",{key:p.operation_id},y("strong",null,p.person.display_name),y("span",null,` — ${p.projects.map(f=>f.display_name).join(", ")} — ${p.lifecycle.label}`)))):y("div",{class:"peer-meta"},"No project sharing operations yet."))}function DD(e){const{summary:t,fresh:n,reviewJoinRequest:r,snapshotMatchesTarget:i}=e,o=i&&Or(P.recovery,"joinRequests"),s=Mi(P.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=Bs(l,P.unnamedDeviceAliases);return y($r,{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 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?y("div",{class:"peer-meta"},"Complete legacy coordinator setup to load join requests. No join queue is expected yet."):o?c.length?y("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 b=P.joinReviewPendingId===p;return y("div",{class:"peer-card peer-card--padded",key:p||f},y("div",{class:"peer-title"},y("strong",null,v)),y("details",{class:"coordinator-admin-diagnostics"},y("summary",null,"Diagnostics"),y("div",{class:"peer-meta"},`Advanced: ${h.join(" · ")}`)),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||!p||b,onClick:()=>r(p,"approve"),type:"button"},b&&P.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!n||!p||b,onClick:()=>r(p,"deny"),type:"button"},b&&P.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."):y("div",{class:"peer-meta"},"Join requests are unavailable. Retry to load the current queue; no empty result is being assumed."))}var LD=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 $D(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 OD(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function jD(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function MD(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function FD(e){const{renderShell:t,reloadData:n}=e,r=(...d)=>xn(P.recovery,...d)?!0:(Z("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning"),!1);async function i(){if(!r("status","groups")||P.groupActionPendingKind)return;const d=Mn(C.lastCoordinatorAdminStatus?.coordinator_url),u=P.createGroupId.trim();if(!u){Z("Enter a coordinator group ID before creating a legacy group.","warning");return}const p=P.createGroupDisplayName.trim();P.groupActionPendingKind="create",t();try{const f=await wC({group_id:u,display_name:p||null});if(Mn(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||"");P.createGroupId="",P.createGroupDisplayName="",P.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(),Uu(u),await n()}catch{Z("Legacy coordinator group created, but coordinator data could not refresh. Check coordinator recovery status before retrying.","warning");return}f.setup_warning?Z("Legacy coordinator group created, but default Space setup needs repair. Sharing policy is unchanged.","warning"):h?Z("Legacy coordinator group created with a default Space. Sharing policy is unchanged.","success"):Z("Legacy coordinator group created, but default Space status is unknown. Sharing policy is unchanged.","warning")}catch{Z("Could not create the legacy coordinator group. No Sharing policy or Project access changed; check coordinator recovery status and retry.","warning")}finally{P.groupActionPendingKind="",t()}}async function o(d,u,p){if(!r("status","groups")||!d||P.groupActionPendingId)return;const f=u.trim();if(p==="rename"&&!f){Z("Enter a legacy group display name before renaming it.","warning");return}const m=C.lastCoordinatorAdminGroups.find(w=>w.group_id===d),v=Gu(d,m?.display_name),g=oc();if(!await hn({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(!$t(g)){Z("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}if(!xn(P.recovery,"status","groups")){Z("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||P.groupActionPendingId){Z("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const b=P.groupRenameDrafts.get(d)??String(h.display_name||"");P.groupActionPendingId=d,P.groupActionPendingKind=p,t();try{const w=p==="rename"?"renamed":p==="archive"?"archived":"unarchived";p==="rename"&&await SC(d,b),p==="archive"&&await CC(d),p==="unarchive"&&await RC(d);try{await n()}catch{Z(`Legacy coordinator group ${w}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Z(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(jD(w))try{await n(),Z("This legacy coordinator group changed or no longer exists. Coordinator groups were refreshed.","warning")}catch{Z("This legacy coordinator group changed or no longer exists. Refresh coordinator groups before trying another action.","warning")}else Z(`Could not ${p} the legacy coordinator group. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.groupActionPendingId="",P.groupActionPendingKind="",t()}}async function s(){if(!r("status","groups")||P.invitePending)return;const d=C.lastCoordinatorAdminStatus,u=Mn(d?.coordinator_url),p=Fn()||String(d?.active_group||"").trim(),f=P.inviteGroup.trim()||p,m=Number(P.inviteTtlHours);if(!f){Z("Choose a coordinator group before creating a legacy invite.","warning");return}if(!Number.isFinite(m)||m<1){Z("Invite lifetime must be at least 1 hour.","warning");return}P.invitePending=!0,t();try{const v=await hm({group_id:f,policy:P.invitePolicy,ttl_hours:m}),g=C.lastCoordinatorAdminStatus,h=Fn()||String(g?.active_group||"").trim(),b=P.inviteGroup.trim()||h;if(Mn(g?.coordinator_url)!==u||b!==f)return;C.lastTeamInvite=v,P.inviteGroup=f;const w=Array.isArray(v.warnings)?v.warnings:[];Z(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){Z($D(v),"warning")}finally{P.invitePending=!1,t()}}async function c(d,u){if(!$t(P.joinRequestsSnapshotTarget)||!r("status","joinRequests")||P.joinReviewPendingId)return;const p=P.joinRequestsSnapshotTarget;P.joinReviewPendingId=d,P.joinReviewPendingAction=u,t();try{const f=await EC(d,u);if(!$t(p))return;try{await n()}catch{Z(`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?Z("Join request approved, but default Space access needs repair.","warning"):Z(u==="approve"?"Join request approved.":"Join request denied.","success")}catch(f){if(!$t(p))return;if(OD(f))try{await n(),Z("This legacy coordinator join request no longer exists. Pending requests were refreshed.","warning")}catch{Z("This legacy coordinator join request no longer exists. Refresh pending requests before reviewing another request.","warning")}else Z("Could not review the legacy coordinator join request. Sharing policy is unchanged; check coordinator recovery status and retry.","warning")}finally{P.joinReviewPendingId="",P.joinReviewPendingAction="",t()}}async function l(d,u,p,f){if($t(P.devicesSnapshotTarget)&&r("status","devices")&&!(!d||P.deviceActionPendingId)){if(f==="disable"||f==="remove"){const m=oc();if(!await hn({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(!$t(m)){Z("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!xn(P.recovery,"status","devices")){Z("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)||P.deviceActionPendingId){Z("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}}P.deviceActionPendingId=d,P.deviceActionPendingKind=f,t();try{const m=f==="rename"?"renamed":f==="disable"?"disabled":f==="enable"?"enabled":"removed";if(f==="rename"){const v=String(P.deviceRenameDrafts.get(d)||"").trim();if(!v){Z("Enter a device name before renaming it.","warning");return}await AC(d,u,v)}f==="disable"&&await xC(d,u),f==="enable"&&await DC(d,u),f==="remove"&&await LC(d,u);try{await n()}catch{Z(`Device ${m}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}Z(`Device ${m}.`,"success")}catch(m){const v=f==="rename"&&m instanceof Error?LD.get(m.message.trim()):void 0;if(MD(m))try{await n(),Z("This legacy coordinator device no longer exists. Enrolled devices were refreshed.","warning")}catch{Z("This legacy coordinator device no longer exists. Refresh enrolled devices before trying another action.","warning")}else Z(v||`Could not ${f} the legacy coordinator device. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{P.deviceActionPendingId="",P.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:i,runGroupAction:o,createInviteFromAdminPanel:s,reviewJoinRequestFromAdminPanel:c,runDeviceAction:l}}function BD(){C.lastCoordinatorAdminGroups=[],C.lastCoordinatorAdminJoinRequests=[],C.lastCoordinatorAdminDevices=[],C.lastTeamInvite=null,C.coordinatorAdminTargetGroup="",un(P.recovery,"groups",!1),un(P.recovery,"joinRequests",!1),un(P.recovery,"devices",!1),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null,P.groupRenameDrafts.clear(),P.groupPresentationAliases.clear(),P.deviceRenameDrafts.clear(),P.deviceRenameServerNames.clear(),P.groupPreferencesOpen.clear(),P.groupPreferencesDrafts.clear(),P.groupScopeManagementOpen.clear(),P.groupScopeManagementDrafts.clear(),P.inviteGroup="",P.teamSetupGuide=null}function qD(){const e=cy();return Vo(P.recovery,"status"),vu(P.recovery,"groups"),vu(P.recovery,"joinRequests"),vu(P.recovery,"devices"),e}async function hb(e){try{const t=await Rl();if(!_u(e))return"superseded";if(!t||typeof t!="object")throw new Error("Invalid status payload");const n=C.lastCoordinatorAdminStatus;return Mn(n?.coordinator_url)!==Mn(t.coordinator_url)&&BD(),C.lastCoordinatorAdminStatus=t,Us(P.recovery,"status"),"fresh"}catch{return _u(e)?(un(P.recovery,"status"),"failed"):"superseded"}}function UD(){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."}:P.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:GD,runGroupAction:HD,createInviteFromAdminPanel:VD,reviewJoinRequestFromAdminPanel:KD,runDeviceAction:zD}=FD({renderShell:()=>Hr(),reloadData:async()=>{await gc()}});function Hr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=C.lastCoordinatorAdminStatus,n=UD(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!Gx()?.archived_at,c=xn(P.recovery,"status","groups"),l=c&&!s,d=$t(P.joinRequestsSnapshotTarget),u=$t(P.devicesSnapshotTarget),p=xn(P.recovery,"status","joinRequests")&&d,f=xn(P.recovery,"status","devices")&&u,m=Fn(),v=rr().filter(L=>!L.archived_at).length,g=rr().filter(L=>L.archived_at).length,h=d&&Array.isArray(C.lastCoordinatorAdminJoinRequests)?C.lastCoordinatorAdminJoinRequests.length:0,b=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.":"",_=bu(P.recovery),R=Or(P.recovery,"status"),I=Or(P.recovery,"groups"),T=d&&Or(P.recovery,"joinRequests"),A=u&&Or(P.recovery,"devices"),O=Mi(P.recovery,"groups"),F=Mi(P.recovery,"joinRequests"),N=Mi(P.recovery,"devices");Ue(y("div",{class:"coordinator-admin-shell"},y("div",{class:"card coordinator-admin-header"},y("div",{class:"section-header"},y("h2",null,"Legacy coordinator administration")),y("div",{"aria-atomic":"true","aria-live":"polite",class:_?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":P.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:"coordinatorAdminRecoveryStatus",role:"status",tabIndex:-1},_?y(z,null,y("div",{class:"coordinator-admin-legacy-notice-copy"},y("h3",null,"Advanced coordinator data needs attention"),P.recoveryAnnouncement?y("p",{class:"peer-submeta"},P.recoveryAnnouncement):null,_.stale.length?y("p",{class:"peer-submeta"},`Stale: ${_.stale.join(", ")}. Previously loaded data is still shown.`):null,_.unavailable.length?y("p",{class:"peer-submeta"},`Unavailable: ${_.unavailable.join(", ")}. No current data is shown for ${_.unavailable.length===1?"that surface":"those surfaces"}.`):null,y("p",{class:"peer-submeta"},"Actions that depend on current coordinator data are disabled. This does not mean coordinator data was deleted.")),y("button",{class:"settings-button",disabled:_.retrying,onClick:()=>{P.recoveryAnnouncement="Retrying coordinator data…",P.recoveryRetryRequested=!0,gc()},type:"button"},_.retrying?"Retrying…":"Retry")):P.recoveryAnnouncement),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Coordinator group target"),y("strong",null,R||I?m||"None selected":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Node discovery group"),y("strong",null,R?i||"None":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Coordinator groups"),y("strong",null,I?`${v} active${g?` · ${g} archived`:""}`:O?"Setup required":"Unavailable")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected group activity"),y("strong",null,`${T?h:F?"Setup required":"Unavailable"} join requests · ${A?b:N?"Setup required":"Unavailable"} devices`))),w?y("div",{class:"peer-meta coordinator-admin-inline-warning"},w):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(oy,{ariaLabel:"Legacy coordinator administration sections",listClassName:"coordinator-admin-tabs-list",onValueChange:L=>{P.activeSection=L||"groups",Hr()},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:P.activeSection},AD({summary:n,fresh:c,createGroup:()=>{GD()},runGroup:(L,D,G)=>{HD(L,D,G)},renderShell:Hr,reloadData:()=>{gc()}}),xD({summary:n,fresh:l,createInvite:()=>{VD()},renderShell:Hr}),DD({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(L,D)=>{KD(L,D)}}),ME({summary:n,fresh:f,snapshotMatchesTarget:u,runDevice:(L,D,G,q)=>{zD(L,D,G,q)}})),y("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),P.recoveryFocusPending&&(P.recoveryFocusPending=!1,queueMicrotask(()=>document.getElementById("coordinatorAdminRecoveryStatus")?.focus()))}function WD(){Hr()}var cp=null;function Bt(e){return cp?.generation===e?!1:cp?.operation??!1}function gc(){const e=cy(),t=JD(e);return cp={generation:e,operation:t},t}async function JD(e){const t=()=>_u(e);if(P.recoveryRetryRequested||(P.recoveryAnnouncement=""),Vo(P.recovery,"status"),Vo(P.recovery,"groups"),Vo(P.recovery,"joinRequests"),Vo(P.recovery,"devices"),Hr(),await hb(e)==="superseded")return Bt(e);const n=String(C.lastCoordinatorAdminStatus?.active_group||"").trim();if(zy(),C.lastCoordinatorAdminStatus?.readiness==="ready"&&xn(P.recovery,"status")){try{const o=await Lm();if(!t())return Bt(e);C.lastShareOperations=Array.isArray(o.items)?o.items:[]}catch{if(!t())return Bt(e)}try{const o=await pm(P.showArchivedGroups);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid groups payload");C.lastCoordinatorAdminGroups=o.items,Us(P.recovery,"groups"),Ux(),zy()}catch{if(!t())return Bt(e);un(P.recovery,"groups")}const r=Fn(),i=oc();try{if(!i)throw new Error("Missing coordinator administration target");const o=await NC(r||n);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid join requests payload");C.lastCoordinatorAdminJoinRequests=o.items,P.joinRequestsSnapshotTarget=i,Us(P.recovery,"joinRequests")}catch{if(!t())return Bt(e);un(P.recovery,"joinRequests",$t(P.joinRequestsSnapshotTarget))}try{if(!i)throw new Error("Missing coordinator administration target");const o=await mm(r||n,!0);if(!t())return Bt(e);if(!Array.isArray(o?.items))throw new Error("Invalid devices payload");C.lastCoordinatorAdminDevices=o.items,P.devicesSnapshotTarget=i,Us(P.recovery,"devices"),Hx()}catch{if(!t())return Bt(e);un(P.recovery,"devices",$t(P.devicesSnapshotTarget))}try{const o=await Va();if(!t())return Bt(e);P.availableProjects=o}catch{if(!t())return Bt(e)}}else P.recovery.status.availability==="fresh"?(yu(P.recovery,"groups"),yu(P.recovery,"joinRequests"),yu(P.recovery,"devices"),P.joinRequestsSnapshotTarget=null,P.devicesSnapshotTarget=null):(un(P.recovery,"groups"),un(P.recovery,"joinRequests",$t(P.joinRequestsSnapshotTarget)),un(P.recovery,"devices",$t(P.devicesSnapshotTarget)));return t()?(ay([...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}))],P.unnamedDeviceAliases),Bs(C.lastCoordinatorAdminDevices,P.unnamedDeviceAliases),P.recoveryRetryRequested&&(P.recoveryAnnouncement=bu(P.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.",P.recoveryFocusPending=!0),P.recoveryRetryRequested=!1,Hr(),bu(P.recovery)===null):Bt(e)}function lp(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var dp=new WeakMap,gb={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},YD={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},XD={available:"Available",offline:"Offline",unknown:"Availability unknown"};function QD(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function ZD(e,t){return t.get(e)??YD}function eL(e){return e.reduce((t,n)=>!t||gb[n.state]>gb[t.state]?n:t,null)}function tL(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 nL(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=QD(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),m=_=>{const R=s.get(_);if(!R)return null;const I=ZD(_,d);return{canonicalProjectIdentity:_,displayName:R,state:I.state,statusLabel:I.label,statusCopy:I.explanation,deliveredCopiesMayRemain:I.deliveredCopiesMayRemain}},v=f.flatMap(_=>{const R=m(_);return R?[R]:[]}),g=[],h=[...v,...g],b=eL(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:o.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:XD[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:v,inheritedProjects:g,unavailableProjectCount:f.length-v.length,statusState:b?.state??"no_projects",statusLabel:b?.statusLabel??"No directly shared Projects",statusCopy:b?.statusCopy??"Team access is not shown here without authoritative per-device eligibility.",deliveredCopiesMayRemain:h.some(_=>_.deliveredCopiesMayRemain),action:tL(w,b?.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 vb({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 ta(e){if(!(e instanceof Tl))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 vc(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:na(e)}}function na(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 yc(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 yb="devices-commit-status";function Bn(e){const t=document.getElementById(yb);t&&(t.textContent=e)}function rL({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,vc($,s)]))),[d,u]=x(null),[p,f]=x(!1),[m,v]=x(!1),[g,h]=x(""),b=B(null),w=B(0),_=r.previewBindings??Nm,R=r.commitBindings??Em,I=lp(r),T=d!==null&&yc(d.preview,d.request,n,"bind"),A=ke(()=>n.filter($=>$.state==="setup_required"&&c[$.deviceId]?.selected),[c,n]),O=JSON.stringify({items:t.items.map(na),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),F=i.map($=>`${$.identityId}:${$.displayName}`).sort().join("|");V(()=>{d&&b.current?.focus()},[d]),V(()=>{w.current+=1,v(!1),l($=>Object.fromEntries(n.map(E=>{const S=$[E.deviceId];if(!S)return[E.deviceId,vc(E,s)];if(E.state!=="setup_required")return[E.deviceId,vc(E,s)];const M=S.targetIdentityId!==""&&s.has(S.targetIdentityId);return S.itemSignature===na(E)&&M?[E.deviceId,S]:S.explicit&&M?[E.deviceId,{...S,selected:!1,itemSignature:na(E)}]:[E.deviceId,vc(E,s)]}))),u(null),f(!1)},[O,F]);const N=($,E)=>{w.current+=1,v(!1),l(S=>({...S,[$]:{...S[$],...E}})),u(null),f(!1),h(""),Bn("")},L=$=>({bindings:$.map(E=>{const S=c[E.deviceId];return{deviceId:E.deviceId,targetIdentityId:S?.targetIdentityId??"",confirmed:!0}})}),D=async $=>{if(I){h("Refresh Devices before reviewing Identity setup.");return}if($.some(M=>M.state!=="setup_required")){h("Only devices that require Identity setup can be reviewed here.");return}const E=$.find(M=>bs(t,M).blocked);if(E){h(bs(t,E).recovery??"Identity setup is unavailable.");return}if($.length===0||$.some(M=>!c[M.deviceId]?.targetIdentityId)){h("Choose an Identity for every selected device before review.");return}v(!0),h(""),Bn("");const S=w.current;try{const M=L($),H=await _(M);S===w.current&&(yc(H,M,$,"bind")?u({preview:H,request:M}):h("Identity setup preview was incomplete. Refresh and try again."))}catch(M){S===w.current&&h(ta(M))}S===w.current&&v(!1)},G=async()=>{if(!(!d||!p||I||!T)){v(!0),h("");try{await R({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),f(!1),Bn("Identity setup completed.");const $=await r.onCommitted?.();Bn($===!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(ta($))}v(!1)}},q=n.filter($=>$.state==="setup_required");return n.length===0?null:a(z,{children:[g?a("p",{role:"alert",children:g}):null,q.length>1?a("div",{className:"device-identity-setup-summary",children:[a("strong",{children:[q.length.toLocaleString()," devices need Identity setup"]}),a("button",{className:"settings-button",disabled:m||I||A.length===0,onClick:()=>{D(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],M=bs(t,$),H=M.blocked||I,U=`device-inventory-title-${E}`;return a("li",{children:a("article",{"aria-labelledby":U,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:U,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,q.length>1?a("label",{children:[a("input",{"aria-label":`Select for setup: ${$.displayName}`,checked:S?.selected??!1,disabled:H,onInput:re=>N($.deviceId,{selected:re.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,a("label",{htmlFor:`${U}-identity`,children:"Identity"}),a("select",{"aria-label":`Choose an Identity for ${$.displayName}`,disabled:H,id:`${U}-identity`,onInput:re=>N($.deviceId,{targetIdentityId:re.currentTarget.value,explicit:!0}),value:S?.targetIdentityId??"",children:[a("option",{value:"",children:"Choose Identity…"}),i.map(re=>a("option",{value:re.identityId,children:re.displayName},re.identityId))]}),$.suggestedIdentityId&&o.has($.suggestedIdentityId)?a("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,M.recovery?a("p",{className:"small",children:M.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:()=>{D([$])},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:b,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:I,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||I||!p||!T,onClick:()=>{G()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function bb({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,b]=x(!1),[w,_]=x(""),R=B(0),I=i,T=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,O=f!==null&&yc(f.preview,f.request,[n],"rebind"),F=bs(t,n),N=F.blocked||lp(r),L=`configured-rebind-trigger-${n.deviceId}`,D=o.find(S=>S.identityId===l)?.displayName??"",G=o.map(S=>S.identityId).sort().join("|"),q=na(n);V(()=>{R.current+=1,b(!1),l&&!o.some(S=>S.identityId===l)&&(d(""),p(!1)),m(null),g(!1)},[G,q]);const $=async()=>{if(N){_(F.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){_("Choose a target Identity and confirm the reassignment before review.");return}b(!0),_(""),Bn("");const S=R.current;try{const M={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},H=await(r.previewBindings??Nm)(M);S===R.current&&(H.status!=="ready"?_(ta(new Tl(409,H.errorCode??"binding_preview_unavailable",H))):yc(H,M,[n],"rebind")?m({preview:H,request:M}):_("Identity reassignment preview was incomplete. Refresh and try again."))}catch(M){S===R.current&&_(ta(M))}S===R.current&&b(!1)},E=async()=>{if(!(!f||!v||N||!O)){b(!0),_("");try{await(r.commitBindings??Em)({...f.request,reviewedInventoryDigest:f.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),m(null),g(!1),Bn("Identity reassignment completed.");const S=await r.onCommitted?.();Bn(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(L)??document.getElementById("devices-heading"))?.focus()}catch(S){_(ta(S))}b(!1)}};return a("div",{className:"device-identity-rebind",children:[a("button",{"aria-expanded":s,className:"settings-button",disabled:N,id:L,onClick:()=>{R.current+=1,b(!1),c(!s),m(null),g(!1),_(""),Bn("")},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):"})," ",I]}),a("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),a("select",{disabled:N,id:`configured-rebind-${n.deviceId}`,onInput:S=>{R.current+=1,b(!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:N||!l,onInput:S=>{R.current+=1,b(!1),p(S.currentTarget.checked),m(null),g(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",D||"the selected Identity"]}),a("button",{className:"settings-button",disabled:h||N,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?T.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",T.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:N,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||N||!v||!O,onClick:()=>{E()},type:"button",children:"Reassign Identity"})]}):null,w?a("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function iL({intent:e,options:t,projection:n}){if(t.loading)return a(Ug,{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=Gg(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(bb,{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(rL,{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(b=>b.state==="configured"&&b.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:[lp(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(vb,{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(vb,{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:b=>{b&&dp.set(b,{deviceId:f.deviceId,target:g.target})},type:"button",children:g.label}):null,h&&t.inventory?a(bb,{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 bc(e,t,n,r,i,o={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?dp.get(s):void 0,d=nL(t,n,r,i,o.peerRuntimeMetadata);if(Ue(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(iL,{intent:t,options:o,projection:d}),a("p",{"aria-live":"polite",id:yb,role:"status"})]}),e),Bn(""),!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=dp.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function oL(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Vr(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function aL(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 zi(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 sr(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 _b(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function sL(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 up(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 Wi(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 cL(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function ra(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function _c(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 wb(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function lL(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function dL(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 uL(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function pL(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function fL(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 Sb(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 wc(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function mL(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 hL(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 Cb(e){const t=ra(e.title),n=ra(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 Rb(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function Tt(e){return`${String(e.kind||"").toLowerCase()}:${Rb(e)}`}function gL(e){if(e.tags!=null)return _c(e.tags);const t=_c(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function vL(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function yL(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function bL(e){if(Sb(e))return"You";const t=String(e.actor_id||"").trim(),n=Ti(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function _L(e,t={}){if(Sb(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Ti(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Ib(e,t){const n=new Map;return e.forEach(r=>{n.set(Tt(r),r)}),t.forEach(r=>{n.set(Tt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function wL(e,t){const n=new Set(t.map(Tt));return Ib(e.filter(r=>!n.has(Tt(r))),t)}var Q2=560;function SL(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Sc(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Cc(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function CL(e,t){const n=new Set(t.map(Tt));return e.filter(r=>!n.has(Tt(r))).length}var RL=Object.defineProperty,it=(e,t)=>RL(e,"name",{value:t,configurable:!0}),[pp,Z2]=dt("Tooltip",[tr]),Rc=tr(),IL="TooltipProvider",kL=700,fp="tooltip.open",[TL,mp]=pp(IL),PL=it(e=>{const{__scopeTooltip:t,delayDuration:n=kL,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:o}=e,s=B(!0),c=B(!1),l=B(0);return V(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),a(TL,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:ae(()=>{r<=0||(window.clearTimeout(l.current),s.current=!1)},[r]),onClose:ae(()=>{r<=0||(window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r))},[r]),isPointerInTransitRef:c,onPointerInTransitChange:ae(d=>{c.current=d},[]),disableHoverableContent:i,children:o})},"TooltipProvider"),hp="Tooltip",[NL,ia]=pp(hp),EL=it(e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:o,disableHoverableContent:s,delayDuration:c}=e,l=mp(hp,e.__scopeTooltip),d=Rc(t),[u,p]=x(null),[f,m]=x(void 0),v=Et(),g=B(0),h=s??l.disableHoverableContent,b=c??l.delayDuration,w=B(!1),[_,R]=At({prop:r,defaultProp:i??!1,onChange:it(N=>{N?(l.onOpen(),document.dispatchEvent(new CustomEvent(fp))):l.onClose(),o?.(N)},"onChange"),caller:hp}),I=ke(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),T=ae(()=>{window.clearTimeout(g.current),g.current=0,w.current=!1,R(!0)},[R]),A=ae(()=>{window.clearTimeout(g.current),g.current=0,R(!1)},[R]),O=ae(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{w.current=!0,R(!0),g.current=0},b)},[b,R]);return V(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),a(nc,{...d,children:a(NL,{scope:t,contentId:f??v,setContentId:m,open:_,stateAttribute:I,trigger:u,onTriggerChange:p,onTriggerEnter:ae(()=>{l.isOpenDelayedRef.current?O():T()},[l.isOpenDelayedRef,O,T]),onTriggerLeave:ae(()=>{h?A():(window.clearTimeout(g.current),g.current=0)},[A,h]),onOpen:T,onClose:A,disableHoverableContent:h,children:n})})},"Tooltip"),kb="TooltipTrigger",AL=J(it(function(t,n){const{__scopeTooltip:r,...i}=t,o=ia(kb,r),s=mp(kb,r),c=Rc(r),l=B(null),d=Re(n,l,o.onTriggerChange),u=B(!1),p=B(!1),f=ae(()=>u.current=!1,[]);return V(()=>()=>document.removeEventListener("pointerup",f),[f]),a(Xo,{asChild:!0,...c,children:a(ye.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...i,ref:d,onPointerMove:te(t.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:te(t.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:te(t.onPointerDown,()=>{o.open&&o.onClose(),u.current=!0,document.addEventListener("pointerup",f,{once:!0})}),onFocus:te(t.onFocus,()=>{u.current||o.onOpen()}),onBlur:te(t.onBlur,o.onClose),onClick:te(t.onClick,o.onClose)})})},"TooltipTrigger")),Tb="TooltipPortal",[xL,DL]=pp(Tb,{forceMount:void 0}),LL=it(e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,o=ia(Tb,t);return a(xL,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"TooltipPortal"),oa="TooltipContent",$L=J(it(function(t,n){const r=DL(oa,t.__scopeTooltip),{forceMount:i=r.forceMount,side:o="top",...s}=t,c=ia(oa,t.__scopeTooltip);return a(kt,{present:i||c.open,children:c.disableHoverableContent?a(Pb,{side:o,...s,ref:n}):a(OL,{side:o,...s,ref:n})})},"TooltipContent")),OL=J(it(function(t,n){const r=ia(oa,t.__scopeTooltip),i=mp(oa,t.__scopeTooltip),o=B(null),s=Re(n,o),[c,l]=x(null),{trigger:d,onClose:u}=r,p=o.current,{onPointerInTransitChange:f}=i,m=ae(()=>{l(null),f(!1)},[f]),v=ae((g,h)=>{const b=g.currentTarget,w={x:g.clientX,y:g.clientY},_=Eb(w,Nb(w,b.getBoundingClientRect())),R=Ab(h.getBoundingClientRect()),I=Db([..._,...R]);l(I),f(!0)},[f]);return V(()=>()=>m(),[m]),V(()=>{if(d&&p){const g=it(b=>v(b,p),"handleTriggerLeave"),h=it(b=>v(b,d),"handleContentLeave");return d.addEventListener("pointerleave",g),p.addEventListener("pointerleave",h),()=>{d.removeEventListener("pointerleave",g),p.removeEventListener("pointerleave",h)}}},[d,p,v,m]),V(()=>{if(c){const g=it(h=>{const b=h.target,w={x:h.clientX,y:h.clientY},_=d?.contains(b)||p?.contains(b),R=!xb(w,c);_?m():R&&(m(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[d,p,c,u,m]),a(Pb,{...t,ref:s})},"TooltipContentHoverable")),jL=Wh("TooltipContent"),Pb=J(it(function(t,n){const{__scopeTooltip:r,children:i,"aria-label":o,id:s,onEscapeKeyDown:c,onPointerDownOutside:l,...d}=t,u=ia(oa,r),p=Rc(r),{onClose:f}=u;V(()=>(document.addEventListener(fp,f),()=>document.removeEventListener(fp,f)),[f]),V(()=>{if(u.trigger){const v=it(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 Ze(()=>(m(s),()=>{m(void 0)}),[s,m]),a(bi,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:v=>v.preventDefault(),onDismiss:f,children:a(rc,{"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(jL,{children:i}),o?a(oN,{id:u.contentId,role:"tooltip",children:o}):null]})})},"TooltipContentImpl")),ML=J(it(function(t,n){const{__scopeTooltip:r,...i}=t,o=Rc(r);return a(fx,{...o,...i,ref:n})},"TooltipArrow"));function Nb(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")}}it(Nb,"getExitSideFromRect");function Eb(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}it(Eb,"getPaddedExitPoints");function Ab(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}]}it(Ab,"getPointsFromRect");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}it(xb,"isPointInPolygon");function Db(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),Lb(t)}it(Db,"getHull");function Lb(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)}it(Lb,"getHullPresorted");var FL=PL,BL=EL,qL=AL,UL=LL,GL=$L,HL=ML;function Ic({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return a(FL,{delayDuration:t,skipDelayDuration:n,children:e})}function kc({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(BL,{children:[a(qL,{asChild:o,children:e}),a(UL,{children:a(GL,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,a(HL,{className:"tooltip-arrow"})]})})]})}function VL(e){e.dataset.feedRenderRoot="preact"}function KL(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function zL(e,t){VL(e),Ue(y(Ic,null,t),e)}function WL(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function JL(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function gp(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function YL(e){const t=wc(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=ra(n),o=ra(r),s=!!r&&o!==i,c=_c(e?.facts||t?.facts||[]),l=c.length?c:mL(r||n),d=l.length?l:hL(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function XL(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 QL(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function ZL(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function e$(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function t$(e,t){const n=C.feedTypeFilter==="observations"?" · observations":C.feedTypeFilter==="summaries"?" · session summaries":"",r=vL(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 Tc({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 n$({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),b=B(0),w=String(C.feedQuery||""),_=String(t||"").trim(),R=C.currentProject||null,I=JL(c),T=gp({project:R,query:_,workingSetFiles:I}),A=g&&gp({project:g.inputs.project,query:g.inputs.query,workingSetFiles:g.inputs.working_set_files})===T?g:null,O=p&&m===T?p:"";V(()=>{b.current+=1,u(!1),f(""),v(""),h(q=>!q||q.inputs.query!==_||q.inputs.project!==R?null:q)},[T]),V(()=>{e&&!r&&(n(WL({feedQuery:w,hasInspectorOverride:o,inspectorQuery:t})),i(!0))},[w,o,r,t,e]);const F=async()=>{const q=_,$=R,E=I,S=gp({project:$,query:q,workingSetFiles:E}),M=b.current+1;if(b.current=M,!q){f("Enter a query to inspect."),v(S),h(null);return}u(!0),f(""),v("");try{const H=await MC({context:q,project:$,working_set_files:E});if(M!==b.current)return;h(H)}catch(H){if(M!==b.current)return;f(H instanceof Error?H.message:String(H)),v(S),h(null)}finally{M===b.current&&u(!1)}},N=A?.retrieval.candidates.filter(q=>q.disposition==="selected")||[],L=A?.retrieval.candidates.filter(q=>q.disposition==="dropped")||[],D=A?.retrieval.candidates.filter(q=>q.disposition==="deduped")||[],G=A?.retrieval.candidates.filter(q=>q.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"},o?"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:q=>{n(String(q.currentTarget.value||"")),s(!0),h(null),f(""),v("")},placeholder:"Trace a pack query…",value:t}),y("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."),y("textarea",{className:"feed-inspector-files",onInput:q=>l(String(q.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:()=>{F()},type:"button"},d?"Tracing…":"Run trace"),A?y("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),g&&!A?y("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,O?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},O):null]),A?y(z,null,[y(Tc,{label:"Selected",candidates:N}),y(Tc,{label:"Dropped",candidates:L}),y(Tc,{label:"Deduped",candidates:D}),y(Tc,{label:"Trimmed",candidates:G}),y("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(q=>`kept #${q.kept} from [${q.dropped.join(", ")}]`).join(" · ")}`):null,A.assembly.trim_reasons.length?y("div",{className:"section-meta"},`Trim reasons: ${A.assembly.trim_reasons.join(", ")}`):null,y("div",{className:"section-meta"},"Final pack"),y("pre",{style:"white-space:pre-wrap; overflow:auto;"},A.output.pack_text)])]):null])):null}var r$={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function vp({variant:e,tone:t,title:n,children:r}){const i=r$[e],o=t?`${i} ${t}`:i;return a("span",{className:o,title:n,children:r})}function $b(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 i$(e){if(Array.isArray(e))return e}function o$(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 a$(){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 s$(e,t){return i$(e)||o$(e,t)||c$(e,t)||a$()}function c$(e,t){if(e){if(typeof e=="string")return $b(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)?$b(e,t):void 0}}var Ob=Object.entries,jb=Object.setPrototypeOf,l$=Object.isFrozen,d$=Object.getPrototypeOf,u$=Object.getOwnPropertyDescriptor,ot=Object.freeze,st=Object.seal,Ji=Object.create,Mb=typeof Reflect<"u"&&Reflect,yp=Mb.apply,bp=Mb.construct;ot||(ot=function(t){return t}),st||(st=function(t){return t}),yp||(yp=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)}),bp||(bp=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 Kr=et(Array.prototype.forEach),p$=et(Array.prototype.lastIndexOf),Fb=et(Array.prototype.pop),aa=et(Array.prototype.push),f$=et(Array.prototype.splice),Yi=Array.isArray,sa=et(String.prototype.toLowerCase),_p=et(String.prototype.toString),Bb=et(String.prototype.match),ca=et(String.prototype.replace),qb=et(String.prototype.indexOf),m$=et(String.prototype.trim),h$=et(Number.prototype.toString),g$=et(Boolean.prototype.toString),Ub=typeof BigInt>"u"?null:et(BigInt.prototype.toString),Gb=typeof Symbol>"u"?null:et(Symbol.prototype.toString),Pt=et(Object.prototype.hasOwnProperty),la=et(Object.prototype.toString),vt=et(RegExp.prototype.test),zr=v$(TypeError);function et(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 yp(e,t,r)}}function v$(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return bp(e,n)}}function Ae(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sa;if(jb&&jb(e,null),!Yi(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const o=n(i);o!==i&&(l$(t)||(t[r]=o),i=o)}e[i]=!0}return e}function y$(e){for(let t=0;t<e.length;t++)Pt(e,t)||(e[t]=null);return e}function Ot(e){const t=Ji(null);for(const r of Ob(e)){var n=s$(r,2);const i=n[0],o=n[1];Pt(e,i)&&(Yi(o)?t[i]=y$(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=Ot(o):t[i]=o)}return t}function b$(e){switch(typeof e){case"string":return e;case"number":return h$(e);case"boolean":return g$(e);case"bigint":return Ub?Ub(e):"0";case"symbol":return Gb?Gb(e):"Symbol()";case"undefined":return la(e);case"function":case"object":{if(e===null)return la(e);const t=e,n=Zt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:la(r)}return la(e)}default:return la(e)}}function Zt(e,t){for(;e!==null;){const r=u$(e,t);if(r){if(r.get)return et(r.get);if(typeof r.value=="function")return et(r.value)}e=d$(e)}function n(){return null}return n}function _$(e){try{return vt(e,""),!0}catch{return!1}}var Hb=ot(["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"]),wp=ot(["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"]),Sp=ot(["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"]),w$=ot(["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"]),Cp=ot(["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"]),S$=ot(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Vb=ot(["#text"]),Kb=ot(["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"]),Rp=ot(["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"]),zb=ot(["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"]),Pc=ot(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),C$=st(/{{[\w\W]*|^[\w\W]*}}/g),R$=st(/<%[\w\W]*|^[\w\W]*%>/g),I$=st(/\${[\w\W]*/g),k$=st(/^data-[\-\w.\u00B7-\uFFFF]+$/),T$=st(/^aria-[\-\w]+$/),Wb=st(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),P$=st(/^(?:\w+script|data):/i),N$=st(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),E$=st(/^html$/i),A$=st(/^[a-z][.\w]*(-[.\w]+)+$/i),Jb=st(/<[/\w!]/g),Yb=st(/<[/\w]/g),x$=st(/<\/no(script|embed|frames)/i),D$=st(/\/>/i),jt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Xb=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],L$=ot(Ae({},Xb)),$$=(function(){const e={};return Kr(Xb,t=>{e[t]=st(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),ot(e)})(),O$=function(){return typeof window>"u"?null:window},j$=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}},Qb=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},cr=function(t,n,r,i){return Pt(t,n)&&Yi(t[n])?Ae(i.base?Ot(i.base):{},t[n],i.transform):r},Ip=function(t,n,r){const i=Pt(t,n)?t[n]:void 0;return i&&typeof i=="object"?Ot(i):r()};function Zb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:O$();const t=Q=>Zb(Q);if(t.version="3.4.14",t.removed=[],!e||!e.document||e.document.nodeType!==jt.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=Zt(p,"cloneNode"),m=Zt(p,"remove"),v=Zt(p,"nextSibling"),g=Zt(p,"childNodes"),h=Zt(p,"parentNode"),b=Zt(p,"shadowRoot"),w=Zt(p,"attributes"),_=s&&s.prototype?Zt(s.prototype,"nodeType"):null,R=s&&s.prototype?Zt(s.prototype,"nodeName"):null,I=s&&s.prototype?Zt(s.prototype,"ownerDocument"):null,T=function(k){return _?_(k):k.nodeType},A=function(k){return R?R(k):k.nodeName};if(typeof o=="function"){const Q=n.createElement("template");Q.content&&Q.content.ownerDocument&&(n=Q.content.ownerDocument)}let O,F="",N,L=!1,D=0;const G=function(){if(D>0)throw zr('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.')},q=function(k){G(),D++;try{return O.createHTML(k)}finally{D--}},$=function(k){G(),D++;try{return O.createScriptURL(k)}finally{D--}},E=function(){return L||(N=j$(u,i),L=!0),N},S=n,M=S.implementation,H=S.createNodeIterator,U=S.createDocumentFragment,re=S.getElementsByTagName,oe=r.importNode;let ie=Qb();t.isSupported=typeof Ob=="function"&&typeof h=="function"&&M&&M.createHTMLDocument!==void 0;const se=C$,ue=R$,Pe=I$,Ie=k$,le=T$,ve=P$,X=N$,ce=A$;let be=Wb,fe=null;const We=Ae({},[...Hb,...wp,...Sp,...Cp,...Vb]);let he=null;const W=Ae({},[...Kb,...Rp,...zb,...Pc]);let de=Object.seal(Ji(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}})),ne=null,xe=null;const tt=Object.seal(Ji(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let po=!0,Vn=!0,bn=!1,we=!0,Ye=!1,Xe=!0,Kt=!1,Ua=!1,li=null,di=null,ui=!1,lt=!1,_n=!1,fo=!1,WS=!0,JS=!1;const YS="user-content-";let Qf=!0,Zf=!1,mo={},ho=null;const XS=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 QS=null;const ZS=Ae({},["audio","video","img","source","image","track"]);let eC=null;const tC=Ae({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gl="http://www.w3.org/1998/Math/MathML",vl="http://www.w3.org/2000/svg",wn="http://www.w3.org/1999/xhtml";let go=wn,em=!1,tm=null;const S2=Ae({},[gl,vl,wn],_p),nC=ot(["mi","mo","mn","ms","mtext"]);let nm=Ae({},nC);const rC=ot(["annotation-xml"]);let rm=Ae({},rC);const C2=Ae({},["title","style","font","a","script"]);let Ga=null;const R2=["application/xhtml+xml","text/html"],I2="text/html";let Qe=null,vo=null;const k2=n.createElement("form"),iC=function(k){return k instanceof RegExp||k instanceof Function},im=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(vo&&vo===k)return;(!k||typeof k!="object")&&(k={}),k=Ot(k),Ga=R2.indexOf(k.PARSER_MEDIA_TYPE)===-1?I2:k.PARSER_MEDIA_TYPE,Qe=Ga==="application/xhtml+xml"?_p:sa,fe=cr(k,"ALLOWED_TAGS",We,{transform:Qe}),he=cr(k,"ALLOWED_ATTR",W,{transform:Qe}),tm=cr(k,"ALLOWED_NAMESPACES",S2,{transform:_p}),eC=cr(k,"ADD_URI_SAFE_ATTR",tC,{transform:Qe,base:tC}),QS=cr(k,"ADD_DATA_URI_TAGS",ZS,{transform:Qe,base:ZS}),ho=cr(k,"FORBID_CONTENTS",XS,{transform:Qe}),ne=cr(k,"FORBID_TAGS",Ot({}),{transform:Qe}),xe=cr(k,"FORBID_ATTR",Ot({}),{transform:Qe}),mo=Pt(k,"USE_PROFILES")?k.USE_PROFILES&&typeof k.USE_PROFILES=="object"?Ot(k.USE_PROFILES):k.USE_PROFILES:!1,po=k.ALLOW_ARIA_ATTR!==!1,Vn=k.ALLOW_DATA_ATTR!==!1,bn=k.ALLOW_UNKNOWN_PROTOCOLS||!1,we=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ye=k.SAFE_FOR_TEMPLATES||!1,Xe=k.SAFE_FOR_XML!==!1,Kt=k.WHOLE_DOCUMENT||!1,lt=k.RETURN_DOM||!1,_n=k.RETURN_DOM_FRAGMENT||!1,fo=k.RETURN_TRUSTED_TYPE||!1,ui=k.FORCE_BODY||!1,WS=k.SANITIZE_DOM!==!1,JS=k.SANITIZE_NAMED_PROPS||!1,Qf=k.KEEP_CONTENT!==!1,Zf=k.IN_PLACE||!1,be=_$(k.ALLOWED_URI_REGEXP)?k.ALLOWED_URI_REGEXP:Wb,go=typeof k.NAMESPACE=="string"?k.NAMESPACE:wn,nm=Ip(k,"MATHML_TEXT_INTEGRATION_POINTS",()=>Ae({},nC)),rm=Ip(k,"HTML_INTEGRATION_POINTS",()=>Ae({},rC));const j=Ip(k,"CUSTOM_ELEMENT_HANDLING",()=>Ji(null));if(de=Ji(null),Pt(j,"tagNameCheck")&&iC(j.tagNameCheck)&&(de.tagNameCheck=j.tagNameCheck),Pt(j,"attributeNameCheck")&&iC(j.attributeNameCheck)&&(de.attributeNameCheck=j.attributeNameCheck),Pt(j,"allowCustomizedBuiltInElements")&&typeof j.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=j.allowCustomizedBuiltInElements),st(de),Ye&&(Vn=!1),_n&&(lt=!0),mo&&(fe=Ae({},Vb),he=Ji(null),mo.html===!0&&(Ae(fe,Hb),Ae(he,Kb)),mo.svg===!0&&(Ae(fe,wp),Ae(he,Rp),Ae(he,Pc)),mo.svgFilters===!0&&(Ae(fe,Sp),Ae(he,Rp),Ae(he,Pc)),mo.mathMl===!0&&(Ae(fe,Cp),Ae(he,zb),Ae(he,Pc))),tt.tagCheck=null,tt.attributeCheck=null,Pt(k,"ADD_TAGS")&&(typeof k.ADD_TAGS=="function"?tt.tagCheck=k.ADD_TAGS:Yi(k.ADD_TAGS)&&(fe===We&&(fe=Ot(fe)),Ae(fe,k.ADD_TAGS,Qe))),Pt(k,"ADD_ATTR")&&(typeof k.ADD_ATTR=="function"?tt.attributeCheck=k.ADD_ATTR:Yi(k.ADD_ATTR)&&(he===W&&(he=Ot(he)),Ae(he,k.ADD_ATTR,Qe))),Pt(k,"ADD_FORBID_CONTENTS")&&Yi(k.ADD_FORBID_CONTENTS)&&(ho===XS&&(ho=Ot(ho)),Ae(ho,k.ADD_FORBID_CONTENTS,Qe)),Qf&&(fe["#text"]=!0),Kt&&Ae(fe,["html","head","body"]),fe.table&&(Ae(fe,["tbody"]),delete ne.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw zr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw zr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const K=O;O=k.TRUSTED_TYPES_POLICY;try{F=q("")}catch(ee){throw O=K,ee}}else k.TRUSTED_TYPES_POLICY===null?(O=void 0,F=""):(O===void 0&&(O=E()),O&&typeof F=="string"&&(F=q("")));ot&&ot(k),vo=k},oC=Ae({},[...wp,...Sp,...w$]),aC=Ae({},[...Cp,...S$]),T2=function(k,j,K){return j.namespaceURI===wn?k==="svg":j.namespaceURI===gl?k==="svg"&&(K==="annotation-xml"||nm[K]):!!oC[k]},P2=function(k,j,K){return j.namespaceURI===wn?k==="math":j.namespaceURI===vl?k==="math"&&rm[K]:!!aC[k]},N2=function(k,j,K){return j.namespaceURI===vl&&!rm[K]||j.namespaceURI===gl&&!nm[K]?!1:!aC[k]&&(C2[k]||!oC[k])},E2=function(k){let j=h(k);(!j||!j.tagName)&&(j={namespaceURI:go,tagName:"template"});const K=sa(k.tagName),ee=sa(j.tagName);return tm[k.namespaceURI]?k.namespaceURI===vl?T2(K,j,ee):k.namespaceURI===gl?P2(K,j,ee):k.namespaceURI===wn?N2(K,j,ee):!!(Ga==="application/xhtml+xml"&&tm[k.namespaceURI]):!1},br=function(k){aa(t.removed,{element:k});try{h(k).removeChild(k)}catch{if(m(k),!h(k))throw zr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},sC=function(k,j,K){try{k.removeAttributeNode(j)}catch{try{k.removeAttribute(K)}catch{}}},yl=function(k){bl(k);const j=g(k);if(j){const ee=[];Kr(j,pe=>{aa(ee,pe)}),Kr(ee,pe=>{try{m(pe)}catch{}})}const K=w(k);if(K)for(let ee=K.length-1;ee>=0;--ee){const pe=K[ee],_e=pe&&pe.name;typeof _e=="string"&&sC(k,pe,_e)}},pi=function(k,j,K){if(!K)try{K=j.getAttributeNode(k)}catch{K=null}aa(t.removed,{attribute:K||null,from:j});try{K?j.removeAttributeNode(K):j.removeAttribute(k)}catch{try{j.removeAttribute(k)}catch{}}if(k==="is")if(lt||_n)try{br(j)}catch{}else try{j.setAttribute(k,"")}catch{}},A2=function(k){const j=w(k);if(j)for(let K=j.length-1;K>=0;--K){const ee=j[K],pe=ee&&ee.name;typeof pe!="string"||he[Qe(pe)]||sC(k,ee,pe)}},bl=function(k){const j=[k];for(;j.length>0;){const K=j.pop();T(K)===jt.element&&A2(K);const ee=g(K);if(ee)for(let pe=ee.length-1;pe>=0;--pe)j.push(ee[pe])}},cC=function(k,j){return Xe?k==="patchsrc"?!0:k==="for"&&j!=="label"&&j!=="output":!1},x2=function(k){if(!Xe)return;const j=[k];for(;j.length>0;){const K=j.pop(),ee=T(K);if(ee===jt.processingInstruction||ee===jt.comment&&vt(Yb,K.data)){try{m(K)}catch{}continue}if(ee===jt.element){const _e=K,De=Qe(A(K));try{_e.hasAttribute&&_e.hasAttribute("patchsrc")&&_e.removeAttribute("patchsrc"),_e.hasAttribute&&_e.hasAttribute("for")&&cC("for",De)&&_e.removeAttribute("for")}catch{}}const pe=g(K);if(pe)for(let _e=pe.length-1;_e>=0;--_e)j.push(pe[_e])}},lC=function(k){let j=null,K=null;if(ui)k="<remove></remove>"+k;else{const _e=Bb(k,/^[\r\n\t ]+/);K=_e&&_e[0]}Ga==="application/xhtml+xml"&&go===wn&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const ee=O?q(k):k;if(go===wn)try{j=new d().parseFromString(ee,Ga)}catch{}if(!j||!j.documentElement){j=M.createDocument(go,"template",null);try{j.documentElement.innerHTML=em?F:ee}catch{}}const pe=j.body||j.documentElement;return k&&K&&pe.insertBefore(n.createTextNode(K),pe.childNodes[0]||null),go===wn?re.call(j,Kt?"html":"body")[0]:Kt?j.documentElement:pe},dC=function(k){const j=I?I(k):k.ownerDocument;return H.call(j||k,k,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},_l=function(k){return k=ca(k,se," "),k=ca(k,ue," "),k=ca(k,Pe," "),k},om=function(k){var j;k.normalize();const K=I?I(k):k.ownerDocument,ee=H.call(K||k,k,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let pe=ee.nextNode();for(;pe;)pe.data=_l(pe.data),pe=ee.nextNode();const _e=(j=k.querySelectorAll)===null||j===void 0?void 0:j.call(k,"template");_e&&Kr(_e,De=>{yo(De.content)&&om(De.content)})},wl=function(k){const j=R?R(k):null;return typeof j!="string"||Qe(j)!=="form"?!1:typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||k.attributes!==w(k)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function"||k.nodeType!==_(k)||k.childNodes!==g(k)},yo=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return _(k)===jt.documentFragment}catch{return!1}},Ha=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return typeof _(k)=="number"}catch{return!1}};function Sn(Q,k,j){Q.length!==0&&Kr(Q,K=>{K.call(t,k,j,vo)})}const D2=function(k,j){return!!(Xe&&k.hasChildNodes()&&!Ha(k.firstElementChild)&&vt(Jb,k.textContent)&&vt(Jb,k.innerHTML)||Xe&&k.namespaceURI===wn&&L$[j]&&(Ha(k.firstElementChild)||typeof k.textContent=="string"&&vt($$[j],k.textContent))||k.nodeType===jt.processingInstruction||Xe&&k.nodeType===jt.comment&&vt(Yb,k.data))},Sl=function(k,j){if(k instanceof RegExp)return vt(k,j);if(k instanceof Function){for(var K=arguments.length,ee=new Array(K>2?K-2:0),pe=2;pe<K;pe++)ee[pe-2]=arguments[pe];return!!k(j,...ee)}return!1},L2=function(k,j,K){if(!ne[j]&&hC(j)&&Sl(de.tagNameCheck,j))return!1;if(Qf&&!ho[j]){const ee=h(k),pe=g(k);if(pe&&ee){const _e=pe.length;for(let De=_e-1;De>=0;--De){const Ct=k===K?f(pe[De],!0):pe[De];ee.insertBefore(Ct,v(k))}}}return br(k),!0},uC=function(k,j,K,ee){return k.length===0?j:j===K||j===ee?Ot(j):j},pC=function(k,j){return k===j||h(k)!==null?!1:(Zf&&bl(k),!0)},fC=function(k,j){if(Sn(ie.beforeSanitizeElements,k,null),pC(k,j))return!0;if(wl(k))return br(k),!0;const K=Qe(A(k));if(fe=uC(ie.uponSanitizeElement,fe,We,li),Sn(ie.uponSanitizeElement,k,{tagName:K,allowedTags:fe}),pC(k,j))return!0;if(D2(k,K))return br(k),!0;if(ne[K]||!(tt.tagCheck instanceof Function&&tt.tagCheck(K))&&!fe[K]){const ee=L2(k,K,j);return ee===!1&&Sn(ie.afterSanitizeElements,k,null),ee}if(T(k)===jt.element&&!E2(k)||(K==="noscript"||K==="noembed"||K==="noframes")&&vt(x$,k.innerHTML))return br(k),!0;if(Ye&&k.nodeType===jt.text){const ee=_l(k.textContent);k.textContent!==ee&&(aa(t.removed,{element:k.cloneNode()}),k.textContent=ee)}return Sn(ie.afterSanitizeElements,k,null),!1},mC=function(k,j,K){if(xe[j]||cC(j,k)||WS&&(j==="id"||j==="name")&&(K in n||K in k2))return!1;const ee=he[j]||tt.attributeCheck instanceof Function&&tt.attributeCheck(j,k);return Vn&&vt(Ie,j)||po&&vt(le,j)?!0:ee?eC[j]||vt(be,ca(K,X,""))||(j==="src"||j==="xlink:href"||j==="href")&&k!=="script"&&qb(K,"data:")===0&&QS[k]||bn&&!vt(ve,ca(K,X,""))?!0:!K:hC(k)&&Sl(de.tagNameCheck,k)&&Sl(de.attributeNameCheck,j,k)||j==="is"&&de.allowCustomizedBuiltInElements&&Sl(de.tagNameCheck,K)},$2=Ae({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),hC=function(k){return!$2[sa(k)]&&vt(ce,k)},O2=function(k,j,K,ee){if(O&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!K)switch(u.getAttributeType(k,j)){case"TrustedHTML":return q(ee);case"TrustedScriptURL":return $(ee)}return ee},j2=function(k,j,K,ee){try{K?k.setAttributeNS(K,j,ee):k.setAttribute(j,ee),wl(k)?br(k):Fb(t.removed)}catch{pi(j,k)}},gC=function(k){Sn(ie.beforeSanitizeAttributes,k,null);const j=k.attributes;if(!j||wl(k))return;he=uC(ie.uponSanitizeAttribute,he,W,di);const K={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he,forceKeepAttr:void 0};let ee=j.length;const pe=Qe(k.nodeName);for(;ee--;){const _e=j[ee],De=_e.name,Ct=_e.namespaceURI,rn=_e.value,Nt=Qe(De),sm=rn;let Rt=De==="value"?sm:m$(sm);if(K.attrName=Nt,K.attrValue=Rt,K.keepAttr=!0,K.forceKeepAttr=void 0,Sn(ie.uponSanitizeAttribute,k,K),Rt=K.attrValue,JS&&(Nt==="id"||Nt==="name")&&qb(Rt,YS)!==0&&(pi(De,k,_e),Rt=YS+Rt),Xe&&vt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Rt)){pi(De,k,_e);continue}if(Nt==="attributename"&&Bb(Rt,"href")){pi(De,k,_e);continue}if(!K.forceKeepAttr){if(!K.keepAttr){pi(De,k,_e);continue}if(!we&&vt(D$,Rt)){pi(De,k,_e);continue}if(Ye&&(Rt=_l(Rt)),!mC(pe,Nt,Rt)){pi(De,k,_e);continue}Rt=O2(pe,Nt,Ct,Rt),Rt!==sm&&j2(k,De,Ct,Rt)}}Sn(ie.afterSanitizeAttributes,k,null)},Cl=function(k){let j=null;const K=dC(k);for(Sn(ie.beforeSanitizeShadowDOM,k,null);j=K.nextNode();)if(Sn(ie.uponSanitizeShadowNode,j,null),fC(j,k),gC(j),yo(j.content)&&Cl(j.content),T(j)===jt.element){const ee=b(j);yo(ee)&&(am(ee),Cl(ee))}Sn(ie.afterSanitizeShadowDOM,k,null)},am=function(k){const j=[{node:k,shadow:null}];for(;j.length>0;){const K=j.pop();if(K.shadow){Cl(K.shadow);continue}const ee=K.node,pe=T(ee)===jt.element,_e=g(ee);if(_e)for(let De=_e.length-1;De>=0;--De)j.push({node:_e[De],shadow:null});if(pe){const De=R?R(ee):null;if(typeof De=="string"&&Qe(De)==="template"){const Ct=ee.content;yo(Ct)&&j.push({node:Ct,shadow:null})}}if(pe){const De=b(ee);yo(De)&&j.push({node:null,shadow:De},{node:De,shadow:null})}}};return t.sanitize=function(Q){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},j=null,K=null,ee=null,pe=null;if(em=!Q,em&&(Q="<!-->"),typeof Q!="string"&&!Ha(Q)&&(Q=b$(Q),typeof Q!="string"))throw zr("dirty is not a string, aborting");if(!t.isSupported)return Q;Ua?(fe=li,he=di):im(k),(ie.uponSanitizeElement.length>0||ie.uponSanitizeAttribute.length>0)&&(fe=Ot(fe)),ie.uponSanitizeAttribute.length>0&&(he=Ot(he)),t.removed=[];const _e=Zf&&typeof Q!="string"&&Ha(Q);if(_e){x2(Q);const rn=A(Q);if(typeof rn=="string"){const Nt=Qe(rn);if(!fe[Nt]||ne[Nt])throw yl(Q),zr("root node is forbidden and cannot be sanitized in-place")}if(wl(Q))throw yl(Q),zr("root node is clobbered and cannot be sanitized in-place");try{am(Q)}catch(Nt){throw yl(Q),Nt}}else if(Ha(Q))j=lC("<!---->"),K=j.ownerDocument.importNode(Q,!0),K.nodeType===jt.element&&K.nodeName==="BODY"||K.nodeName==="HTML"?j=K:j.appendChild(K),am(K);else{if(!lt&&!Ye&&!Kt&&Q.indexOf("<")===-1)return O&&fo?q(Q):Q;if(j=lC(Q),!j)return lt?null:fo?F:""}j&&ui&&br(j.firstChild);const De=_e?Q:j;try{const rn=dC(De);for(;ee=rn.nextNode();)fC(ee,De),gC(ee),yo(ee.content)&&Cl(ee.content)}catch(rn){throw _e&&(yl(Q),Kr(t.removed,Nt=>{Nt.element&&bl(Nt.element)})),rn}if(_e)return Kr(t.removed,rn=>{rn.element&&bl(rn.element)}),Ye&&om(Q),Q;if(lt){if(Ye&&om(j),_n)for(pe=U.call(j.ownerDocument);j.firstChild;)pe.appendChild(j.firstChild);else pe=j;return(he.shadowroot||he.shadowrootmode)&&(pe=oe.call(r,pe,!0)),pe}let Ct=Kt?j.outerHTML:j.innerHTML;return Kt&&fe["!doctype"]&&j.ownerDocument&&j.ownerDocument.doctype&&j.ownerDocument.doctype.name&&vt(E$,j.ownerDocument.doctype.name)&&(Ct="<!DOCTYPE "+j.ownerDocument.doctype.name+`>
|
|
44
|
+
`+Ct),Ye&&(Ct=_l(Ct)),O&&fo?q(Ct):Ct},t.setConfig=function(){let Q=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};im(Q),Ua=!0,li=fe,di=he},t.clearConfig=function(){vo=null,Ua=!1,li=null,di=null,O=N,F=""},t.isValidAttribute=function(Q,k,j){vo||im({});const K=Qe(Q),ee=Qe(k);return mC(K,ee,j)},t.addHook=function(Q,k){typeof k=="function"&&Pt(ie,Q)&&aa(ie[Q],k)},t.removeHook=function(Q,k){if(Pt(ie,Q)){if(k!==void 0){const j=p$(ie[Q],k);return j===-1?void 0:f$(ie[Q],j,1)[0]}return Fb(ie[Q])}},t.removeHooks=function(Q){Pt(ie,Q)&&(ie[Q]=[])},t.removeAllHooks=function(){ie=Qb()},t}var e_=Zb();function kp(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Wr=kp();function t_(e){Wr=e}var Jr={exec:()=>null};function Xi(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 Ne(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(yt.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var M$=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),yt={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:Xi(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Xi(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Xi(e=>new RegExp(`^ {0,${e}}>`))},F$=/^(?:[ \t]*(?:\n|$))+/,B$=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,q$=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,da=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,U$=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Tp=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,n_=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,r_=Ne(n_).replace(/bull/g,Tp).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(),G$=Ne(n_).replace(/bull/g,Tp).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(),Pp=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,H$=/^[^\n]+/,Np=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,V$=Ne(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Np).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),K$=Ne(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Tp).getRegex(),Nc="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",Ep=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,z$=Ne("^ {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",Ep).replace("tag",Nc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),i_=e=>Ne(Pp).replace("hr",da).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",Nc).getRegex(),W$=i_(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),J$=i_(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ap={blockquote:Ne(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",J$).getRegex(),code:B$,def:V$,fences:q$,heading:U$,hr:da,html:z$,lheading:r_,list:K$,newline:F$,paragraph:W$,table:Jr,text:H$},o_=Ne("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",da).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",Nc).getRegex(),Y$={...Ap,lheading:G$,table:o_,paragraph:Ne(Pp).replace("hr",da).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",o_).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",Nc).getRegex()},X$={...Ap,html:Ne(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ep).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:Jr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ne(Pp).replace("hr",da).replace("heading",` *#{1,6} *[^
|
|
45
|
+
]`).replace("lheading",r_).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q$=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Z$=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,a_=/^( {2,}|\\)\n(?!\s*$)/,eO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,qn=/[\p{P}\p{S}]/u,Qi=/[\s\p{P}\p{S}]/u,ua=/[^\s\p{P}\p{S}]/u,tO=Ne(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Qi).getRegex(),nO=/[\p{Pi}\p{Ps}"']/u,s_=/(?!~)[\p{P}\p{S}]/u,rO=/(?!~)[\s\p{P}\p{S}]/u,iO=/(?:[^\s\p{P}\p{S}]|~)/u,oO=Ne(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",M$?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),c_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,aO=Ne(c_,"u").replace(/punct/g,qn).getRegex(),sO=Ne(c_,"u").replace(/punct/g,s_).getRegex(),cO=Ne(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,"u").replace(/openQuote/g,nO).replace(/punct/g,qn).getRegex(),l_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",lO=Ne(l_,"gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),dO=Ne(l_,"gu").replace(/notPunctSpace/g,iO).replace(/punctSpace/g,rO).replace(/punct/g,s_).getRegex(),uO=Ne("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),pO=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),fO=Ne("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),mO=Ne(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,qn).getRegex(),hO=Ne("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ua).replace(/punctSpace/g,Qi).replace(/punct/g,qn).getRegex(),gO=Ne(/\\(punct)/,"gu").replace(/punct/g,qn).getRegex(),vO=Ne(/^<(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(),yO=Ne(Ep).replace("(?:-->|$)","-->").getRegex(),bO=Ne("^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",yO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ec=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,_O=Ne(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ec).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),d_=Ne(/^!?\[(label)\]\[(ref)\]/).replace("label",Ec).replace("ref",Np).getRegex(),u_=Ne(/^!?\[(ref)\](?:\[\])?/).replace("ref",Np).getRegex(),wO=Ne("reflink|nolink(?!\\()","g").replace("reflink",d_).replace("nolink",u_).getRegex(),p_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,xp={_backpedal:Jr,anyPunctuation:gO,autolink:vO,blockSkip:oO,br:a_,code:Z$,del:Jr,delLDelim:Jr,delRDelim:Jr,emStrongLDelim:aO,emStrongRDelimAst:lO,emStrongRDelimUnd:pO,escape:Q$,link:_O,nolink:u_,punctuation:tO,reflink:d_,reflinkSearch:wO,tag:bO,text:eO,url:Jr},SO={...xp,emStrongLDelim:cO,emStrongRDelimAst:uO,emStrongRDelimUnd:fO,link:Ne(/^!?\[(label)\]\((.*?)\)/).replace("label",Ec).getRegex(),reflink:Ne(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ec).getRegex()},Dp={...xp,emStrongRDelimAst:dO,emStrongLDelim:sO,delLDelim:mO,delRDelim:hO,url:Ne(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",p_).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:Ne(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",p_).getRegex()},CO={...Dp,br:Ne(a_).replace("{2,}","*").getRegex(),text:Ne(Dp.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ac={normal:Ap,gfm:Y$,pedantic:X$},pa={normal:xp,gfm:Dp,breaks:CO,pedantic:SO},RO={"&":"&","<":"<",">":">",'"':""","'":"'"},f_=e=>RO[e];function gn(e,t){if(t){if(yt.escapeTest.test(e))return e.replace(yt.escapeReplace,f_)}else if(yt.escapeTestNoEncode.test(e))return e.replace(yt.escapeReplaceNoEncode,f_);return e}function m_(e){try{e=encodeURI(e).replace(yt.percentDecode,"%")}catch{return null}return e}function h_(e,t){let n=e.replace(yt.findPipe,(i,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(yt.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(yt.slashPipe,"|");return n}function lr(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 g_(e){let t=e.split(`
|
|
46
|
+
`),n=t.length-1;for(;n>=0&&yt.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
47
|
+
`)}function IO(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 kO(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 v_(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 TO(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
48
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
|
|
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:
|
|
51
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=
|
|
49
|
+
`)}var xc=class{options;rules;lexer;constructor(e){this.options=e||Wr}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]:g_(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=TO(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=lr(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:lr(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:lr(t[0],`
|
|
51
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=lr(t[0],`
|
|
52
52
|
`).split(`
|
|
53
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(`
|
|
54
54
|
`),u=d.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -60,20 +60,20 @@ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
60
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+`
|
|
61
61
|
`+n.join(`
|
|
62
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=
|
|
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=kO(t[2].split(`
|
|
64
64
|
`,1)[0],t[1].length),f=e.split(`
|
|
65
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),
|
|
67
|
-
`,1)[0],
|
|
68
|
-
`+
|
|
69
|
-
`+f}m=!f.trim(),d+=
|
|
70
|
-
`,e=e.substring(
|
|
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=
|
|
72
|
-
`):[],o={type:"table",raw:
|
|
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(
|
|
66
|
+
`,e=e.substring(f.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(v),h=this.rules.other.hrRegex(v),b=this.rules.other.fencesBeginRegex(v),w=this.rules.other.headingBeginRegex(v),_=this.rules.other.htmlBeginRegex(v),R=this.rules.other.blockquoteBeginRegex(v);for(;e;){let I=e.split(`
|
|
67
|
+
`,1)[0],T;if(f=I,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),T=f):T=f.replace(this.rules.other.tabCharGlobal," "),b.test(f)||w.test(f)||_.test(f)||R.test(f)||g.test(f)||h.test(f))break;if(T.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
|
|
68
|
+
`+T.slice(v);else{if(m||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(p)||w.test(p)||h.test(p))break;u+=`
|
|
69
|
+
`+f}m=!f.trim(),d+=I+`
|
|
70
|
+
`,e=e.substring(I.length+1),p=T.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=g_(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:lr(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=h_(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:lr(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(h_(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:lr(t[0],`
|
|
74
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)===`
|
|
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=
|
|
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(
|
|
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=lr(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=IO(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)),v_(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 v_(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}}}},en=class cm{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Wr,this.options.tokenizer=this.options.tokenizer||new xc,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:yt,block:Ac.normal,inline:pa.normal};this.options.pedantic?(n.block=Ac.pedantic,n.inline=pa.pedantic):this.options.gfm&&(n.block=Ac.gfm,this.options.breaks?n.inline=pa.breaks:n.inline=pa.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ac,inline:pa}}static lex(t,n){return new cm(n).lex(t)}static lexInline(t,n){return new cm(n).inlineTokens(t)}lex(t){t=t.replace(yt.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(yt.tabCharGlobal," ").replace(yt.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
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(`
|
|
78
78
|
`)?"":`
|
|
79
79
|
`)+o.raw,c.text+=`
|
|
@@ -86,9 +86,9 @@ ${v}`,i=i.substring(0,i.length-m.text.length)+h.text;break}else if(f?.type==="li
|
|
|
86
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(`
|
|
87
87
|
`)?"":`
|
|
88
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)}},
|
|
90
|
-
`;return r?'<pre><code class="language-'+
|
|
91
|
-
`:"<pre><code>"+(n?i:
|
|
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)}},Dc=class{options;parser;constructor(e){this.options=e||Wr}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(yt.notSpaceStart)?.[0],i=e.replace(yt.endingNewline,"")+`
|
|
90
|
+
`;return r?'<pre><code class="language-'+gn(r)+'">'+(n?i:gn(i,!0))+`</code></pre>
|
|
91
|
+
`:"<pre><code>"+(n?i:gn(i,!0))+`</code></pre>
|
|
92
92
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
93
93
|
${this.parser.parse(e)}</blockquote>
|
|
94
94
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -104,8 +104,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
104
104
|
`}tablerow({text:e}){return`<tr>
|
|
105
105
|
${e}</tr>
|
|
106
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}>
|
|
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>${
|
|
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 x$;function Fe(e,t){return zr.parse(e,t)}Fe.options=Fe.setOptions=function(e){return zr.setOptions(e),Fe.defaults=zr.defaults,Sb(Fe.defaults),Fe},Fe.getDefaults=np,Fe.defaults=Kr;function D$(...e){return zr.use(...e),Fe.defaults=zr.defaults,Sb(Fe.defaults),Fe}Fe.use=D$,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 BU=Fe.options,UU=Fe.setOptions,qU=Fe.walkTokens,GU=Fe.parseInline,HU=Qt.parse,KU=Xt.lex,$$={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 L$(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:")}wb.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(L$(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 wb.sanitize(t,$$)}function j$(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"},m0(r)),b("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:up(i)}})):null}).filter(Boolean)}function O$(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 Fb(e,t="feed-body"){const n=String(e||"").trim();return n?b("div",{className:t,dangerouslySetInnerHTML:{__html:up(n)}}):null}function M$(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 F$(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Ic(e,t)?"session_summary":n||"change"}var B$=Object.defineProperty,Ge=(e,t)=>B$(e,"name",{value:t,configurable:!0}),pp=["Enter"," "],U$=["ArrowDown","PageUp","Home"],Bb=["ArrowUp","PageDown","End"],q$=[...U$,...Bb],VU={ltr:[...pp,"ArrowRight"],rtl:[...pp,"ArrowLeft"]},Rc="Menu",[fp,G$,H$]=$o(Rc),[Wr,Ub]=lt(Rc,[H$,Qn,Ai]),mp=Qn(),qb=Ai(),[K$,da]=Wr(Rc),[V$,hp]=Wr(Rc),z$=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(K$,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(V$,{scope:t,onClose:se(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})},"Menu"),W$=J(Ge(function(t,n){const{__scopeMenu:r,...i}=t,o=mp(r);return a(Vo,{...o,...i,ref:n})},"MenuAnchor")),Gb="MenuPortal",[J$,Y$]=Wr(Gb,{forceMount:void 0}),X$=Ge(e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=da(Gb,t);return a(J$,{scope:t,forceMount:n,children:a(Rt,{present:n||o.open,children:a(gi,{asChild:!0,container:i,children:r})})})},"MenuPortal"),sr="MenuContent",[Q$,Hb]=Wr(sr),Z$=J(Ge(function(t,n){const r=Y$(sr,t.__scopeMenu),{forceMount:i=r.forceMount,...o}=t,s=da(sr,t.__scopeMenu),c=hp(sr,t.__scopeMenu);return a(fp.Provider,{scope:t.__scopeMenu,children:a(Rt,{present:i||s.open,children:a(fp.Slot,{scope:t.__scopeMenu,children:c.modal?a(eL,{...o,ref:n}):a(tL,{...o,ref:n})})})})},"MenuContent")),eL=J(Ge(function(t,n){const r=da(sr,t.__scopeMenu),i=q(null),o=Se(n,i);return K(()=>{const s=i.current;if(s)return ds(s)},[]),a(Kb,{...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")),tL=J(Ge(function(t,n){const r=da(sr,t.__scopeMenu);return a(Kb,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),nL=on("MenuContent.ScrollLock"),Kb=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(sr,r),w=hp(sr,r),_=mp(r),I=qb(r),R=G$(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:nL,allowPinchZoom:!0}:void 0,D=Ge(G=>{const oe=M.current+G,ae=R().filter(Ne=>!Ne.disabled),ee=document.activeElement,ie=ae.find(Ne=>Ne.ref.current===ee)?.textValue,Ce=Xb(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&&Zb(G,B.current?.area),[]);return a(Q$,{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":zb(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||!q$.includes(G.key))return;G.preventDefault();const Ce=R().filter(Ie=>!Ie.disabled).map(Ie=>Ie.ref.current);Bb.includes(G.key)&&Ce.reverse(),Jb(Ce)}),onBlur:ne(t.onBlur,G=>{G.currentTarget.contains(G.target)||(window.clearTimeout(T.current),M.current="")}),onPointerMove:ne(t.onPointerMove,Pc(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",Vb="menu.itemSelect",rL=J(Ge(function(t,n){const{disabled:r=!1,onSelect:i,...o}=t,s=q(null),c=hp(gp,t.__scopeMenu),l=Hb(gp,t.__scopeMenu),d=Se(n,s),u=q(!1),p=Ge(()=>{const f=s.current;if(!r&&f){const m=new CustomEvent(Vb,{bubbles:!0,cancelable:!0});f.addEventListener(Vb,v=>i?.(v),{once:!0}),es(f,m),m.defaultPrevented?u.current=!1:c.onClose()}},"handleSelect");return a(iL,{...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")),iL=J(Ge(function(t,n){const{__scopeMenu:r,disabled:i=!1,textValue:o,...s}=t,c=Hb(gp,r),l=qb(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,Pc(g=>{i?c.onItemLeave(g):(c.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ne(t.onPointerLeave,Pc(g=>c.onItemLeave(g))),onFocus:ne(t.onFocus,()=>f(!0)),onBlur:ne(t.onBlur,()=>f(!1))})})})},"MenuItemImpl")),[zU,WU]=Wr("MenuRadioGroup",{value:void 0,onValueChange:Ge(()=>{},"onValueChange")}),oL="MenuItemIndicator",[JU,YU]=Wr(oL,{checked:!1}),aL="MenuSub",[XU,QU]=Wr(aL);function zb(e){return e?"open":"closed"}Ge(zb,"getOpenState");function Wb(e){return e==="indeterminate"}Ge(Wb,"isIndeterminate");function sL(e){return Wb(e)?"indeterminate":e?"checked":"unchecked"}Ge(sL,"getCheckedState");function Jb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}Ge(Jb,"focusFirst");function Yb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Ge(Yb,"wrapArray");function Xb(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=Yb(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(Xb,"getNextMatch");function Qb(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(Qb,"isPointInPolygon");function Zb(e,t){return t?Qb({x:e.clientX,y:e.clientY},t):!1}Ge(Zb,"isPointerInGraceArea");function Pc(e){return t=>t.pointerType==="mouse"?e(t):void 0}Ge(Pc,"whenMouse");var cL=z$,lL=W$,dL=X$,uL=Z$,pL=rL,fL=Object.defineProperty,ua=(e,t)=>fL(e,"name",{value:t,configurable:!0}),vp="DropdownMenu",[mL,ZU]=lt(vp,[Ub]),pa=Ub(),[hL,e_]=mL(vp),gL=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]=At({prop:i,defaultProp:o??!1,onChange:s,caller:vp});return a(hL,{scope:t,triggerId:Et(),triggerRef:d,contentId:Et(),open:u,onOpenChange:p,onOpenToggle:se(()=>p(f=>!f),[p]),modal:c,children:a(cL,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})},"DropdownMenu"),vL="DropdownMenuTrigger",yL=J(ua(function(t,n){const{__scopeDropdownMenu:r,disabled:i=!1,...o}=t,s=e_(vL,r),c=pa(r),l=Se(n,s.triggerRef);return a(lL,{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")),bL=ua(e=>{const{__scopeDropdownMenu:t,...n}=e,r=pa(t);return a(dL,{...r,...n})},"DropdownMenuPortal"),_L="DropdownMenuContent",wL=J(ua(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=e_(_L,r),s=pa(r),c=q(!1);return a(uL,{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")),SL=J(ua(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=pa(r);return a(pL,{...o,...i,ref:n})},"DropdownMenuItem")),CL=gL,IL=yL,RL=bL,PL=wL,t_=SL;function kL({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return b(CL,null,b(IL,{asChild:!0},b("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),b(RL,null,b(PL,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},b(t_,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),b(t_,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function TL({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 NL({tag:e}){const t=qy(e);return t?b(zu,{variant:"tag",title:String(e)},t):null}function EL({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=pc(e?.metadata_json),s=Ic(e,o),c=F$(e,o),l=Pt(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,f=u0(p),m=_0(e),v=uc(e.files||[]),g=e.project||"",h=C0(e),y=I0(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(),R=String(e.trust_state||o?.trust_state||"").trim(),k=m.length?` · ${m.map(me=>qy(me)).join(", ")}`:"",A=v.length?` · ${h0(v)}`:"",L=Number(e.id||0),F=L>0?`ID ${L}`:"",[T,M]=x(C.newItemKeys.has(l)),j=s?M$({...e,metadata_json:o}):null,B=s?null:eD({...e,metadata_json:o}),U=B?tD(B):[],$=B?nD(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$(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,R&&R!=="trusted"?S0(R):""].filter(Boolean).join(" · "),W=[`${k}${A}`.trim(),de].filter(Boolean).join(" · "),Re=!!B&&rD(D,B),re=[D==="facts"?"feed-body facts":"feed-body",Re&&!oe?iD(D).join(" "):""].filter(Boolean).join(" "),je=s?ce.length?b("div",{className:"feed-body facts"},ce):Fb(String(e.body_text||""))||b("div",{className:"feed-body"}):B?D==="facts"?O$(B.facts)||b("div",{className:re}):Fb(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 WS(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 JS(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 YS(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 qn=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},qn)),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:Vk(u,C.feedQuery)}}),b("div",{className:"feed-card-subtitle small"},He)),b("div",{className:"feed-actions"},B?b(TL,{active:D,modes:U,onSelect:me=>H(me)}):null,b(gc,{label:d0(p),side:"left"},b("div",{className:"small feed-age"},f)),e.owned_by_self&&L>0?b(kL,{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(NL,{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"},Re?b("button",{className:"feed-expand",onClick:()=>{const me=!oe;C.itemExpandState.set(G,me),ae(me)},type:"button"},oe?"Collapse":"Expand"):null)),gr))}function AL({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 xL({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(AL,{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(EL,{item:r,key:Pt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function n_({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 DL({text:e}){return b("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function $L({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 LL({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=x(!1);return b(z,null,b("div",{className:"feed-controls"},b(DL,{text:n||oD(t.length,r.hasMorePages())}),b("div",{className:"feed-controls-right"},b($L,{query:C.feedQuery,onQuery:r.updateFeedQuery}),b(n_,{active:C.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==C.feedScopeFilter&&(uv(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),b(n_,{active:C.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==C.feedTypeFilter&&(oT(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(aD,{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(xL,{items:t,loadingText:n,ops:r}):null)))}function jL(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 OL(e){const t=e.map(n=>`${Ky(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${C.feedTypeFilter}|${C.feedScopeFilter}|${C.currentProject}|${Zo(C.feedQuery)}|${t.join("|")}`}var r_="",fa=0,ma=0,zi=!0,Wi=!0,kc=null,ML=0,Ft=null,i_=!1,Ji=0,bp="all",o_="",ha=null,Yi="",e2=250;function a_(e){r_=e,bp=C.feedScopeFilter,o_=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 FL(e){const t=Pt(e);C.lastFeedItems=C.lastFeedItems.map(n=>Pt(n)===t?e:n)}function BL(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Pt(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 UL(){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?Vf(t,{limit:20,offset:r,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),Wi?zf(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=>!Hy(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=Vy(C.lastFeedItems,u);C.lastFeedItems=p,Jr()}finally{kc===e&&(kc=null)}}function s_(){C.activeTab==="feed"&&(ha||Ft||_p()&&P0()&&UL())}var qL={replaceFeedItem:FL,removeFeedItem:BL,updateFeedView:e=>Jr(e),loadFeedData:()=>Cp(),updateFeedQuery:e=>HL(e),hasMorePages:_p};function wp(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;X0(n,b(LL,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:qL}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Sp(e="Loading selected project..."){wp([],{loadingText:e})}function GL(){Y0(),wp(C.lastFeedItems,C.lastFeedItems.length||C.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),i_||(window.addEventListener("scroll",()=>{s_()},{passive:!0}),i_=!0)}function HL(e){if(e===C.feedQuery)return;const t=C.feedQuery.trim();C.feedQuery=e,e.trim()!==t&&(a_(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=jL(C.lastFeedItems),r=OL(n),i=e||r!==C.lastFeedSignature;C.lastFeedSignature=r,i&&wp(n,{errorText:Yi||void 0}),window.scrollTo({top:t}),s_()}async function Cp(){const e=C.currentProject||"",t=C.feedScopeFilter!==bp,n=C.feedQuery.trim(),r=n!==o_;(e!==r_||t||r)&&(a_(e),Sp(r?"Searching memories…":void 0));const i=Ji,o=++ML;Ft={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([Vf(e,{limit:20,offset:0,scope:C.feedScopeFilter,q:n||void 0}),zf(e,{limit:50,offset:0,scope:C.feedScopeFilter,q:n||void 0})]);if(Ft?.generation!==i||Ft.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=>!Hy(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=R0(C.lastFeedItems,g),y=C.lastFeedItems;if(k0(h,y)&&y.length>0){const w=new Set(y.map(Pt));h.forEach(_=>{w.has(Pt(_))||C.newItemKeys.add(Pt(_))})}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,Ft?.generation===i&&Ft.requestId===o&&(Ft=null),Jr(s)}catch(c){throw Ft?.generation===i&&Ft.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{Ft?.generation===i&&Ft.requestId===o&&(Ft=null)}}function KL(e){return e.channel==="latest"?"stable":e.channel}function t2(e){return e}function VL(e){if(!e.latest_version)return{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"};if(e.stale)return{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"};if(e.update_available)return{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"};const t=KL(e);return t?{title:`Codemem ${e.current_version} is up to date`,detail:`You are running the latest ${t} release.`,tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not on a supported release channel.",tone:"unavailable"}}function zL({status:e}){const t=VL(e),n=e.update_available||e.stale||!e.latest_version||!e.channel;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 WL(e,t){e&&(e.hidden=!t,We(t?b(zL,{status:t}):null,e))}function JL({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 YL({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 XL(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function QL({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"},XL(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(QL,{...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 ZL(e,t){e&&We(b(Ku,null,t.map(n=>b(JL,{...n,key:n.key??n.label}))),e)}function ej(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(YL,{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;WL(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),R=Number(f.flush_success_rate??1),k=Number(f.dropped_event_rate||0),A=Bu(v.tokens_saved,v.tokens_read),L=f0(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":Uy(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")),R<.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 ${ir(D)} ago`:`${j} peers · last sync ${ir(D)} ago`;Ne&&!B&&!$&&(U?E="Peers offline":T==="degraded"&&oe&&(E="Syncing"));const ce=`last pack ${ir(H)} ago`,ge=l.map(W=>{const Re=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*Re/re)}%)`:"",hr=re&&re>0?`${Re.toLocaleString()}/${re.toLocaleString()} ${je}${it}`:`${Re.toLocaleString()} ${je}`,Zt=W.status==="failed",qn=W.status==="completed",gr=W.kind===d_,me=Zt?"Failed":qn?"Complete":hr,ot=Zt?String(W.error||"unknown error").trim():qn?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":qn?"check-circle":"loader",className:Zt?"status-attention":void 0,title:Zt?`Error: ${W.error||"unknown"}`:qn?`${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:ir(H),detail:ce,icon:"clock-3",title:"Recency of last memory pack activity"}];ZL(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"}),ej(n,de),t.textContent=ie.length?`Why this status: ${ie.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Ip()}function tj(){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(R=>R.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 nj(){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?`
|
|
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>${gn(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=m_(e);if(i===null)return r;e=i;let o='<a href="'+e+'"';return t&&(o+=' title="'+gn(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=m_(e);if(i===null)return gn(n);e=i;let o=`<img src="${e}" alt="${gn(n)}"`;return t&&(o+=` title="${gn(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:gn(e.text)}},Lp=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}},tn=class lm{options;renderer;textRenderer;constructor(t){this.options=t||Wr,this.options.renderer=this.options.renderer||new Dc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Lp}static parse(t,n){return new lm(n).parse(t)}static parseInline(t,n){return new lm(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}},fa=class{options;block;constructor(e){this.options=e||Wr}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?en.lex:en.lexInline}provideParser(e=this.block){return e?tn.parse:tn.parseInline}},PO=class{defaults=kp();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=tn;Renderer=Dc;TextRenderer=Lp;Lexer=en;Tokenizer=xc;Hooks=fa;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 Dc(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 xc(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 fa;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];fa.passThroughHooks.has(o)?i[s]=d=>{if(this.defaults.async&&fa.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 en.lex(e,t??this.defaults)}parser(e,t){return tn.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?en.lex:en.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?tn.parse:tn.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?en.lex:en.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?tn.parse:tn.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>"+gn(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Yr=new PO;function Fe(e,t){return Yr.parse(e,t)}Fe.options=Fe.setOptions=function(e){return Yr.setOptions(e),Fe.defaults=Yr.defaults,t_(Fe.defaults),Fe},Fe.getDefaults=kp,Fe.defaults=Wr;function NO(...e){return Yr.use(...e),Fe.defaults=Yr.defaults,t_(Fe.defaults),Fe}Fe.use=NO,Fe.walkTokens=function(e,t){return Yr.walkTokens(e,t)},Fe.parseInline=Yr.parseInline,Fe.Parser=tn,Fe.parser=tn.parse,Fe.Renderer=Dc,Fe.TextRenderer=Lp,Fe.Lexer=en,Fe.lexer=en.lex,Fe.Tokenizer=xc,Fe.Hooks=fa,Fe.parse=Fe;var eG=Fe.options,tG=Fe.setOptions,nG=Fe.walkTokens,rG=Fe.parseInline,iG=tn.parse,oG=en.lex,EO={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 AO(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:")}e_.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(AO(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function $p(e){const t=Fe.parse(String(e||""),{async:!1});return e_.sanitize(t,EO)}function xO(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"},lL(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:$p(i)}})):null}).filter(Boolean)}function DO(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:y("div",{className:"summary-section",key:`${s}-${i}`},y("div",{className:"summary-section-label"},s),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:$p(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 y_(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:$p(n)}}):null}function LO(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 Lc(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 Lc(e,t)?"session_summary":n||"change"}var OO=Object.defineProperty,He=(e,t)=>OO(e,"name",{value:t,configurable:!0}),Op=["Enter"," "],jO=["ArrowDown","PageUp","Home"],b_=["ArrowUp","PageDown","End"],MO=[...jO,...b_],aG={ltr:[...Op,"ArrowRight"],rtl:[...Op,"ArrowLeft"]},$c="Menu",[jp,FO,BO]=Fo($c),[Xr,__]=dt($c,[BO,tr,Oi]),Mp=tr(),w_=Oi(),[qO,ma]=Xr($c),[UO,Fp]=Xr($c),GO=He(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=B(!1),p=ht(o),f=$i(i);return V(()=>{const m=He(()=>{u.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},"handleKeyDown"),v=He(()=>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})}},[]),V(()=>{if(!n)return;const m=He(()=>p(!1),"handleBlur");return window.addEventListener("blur",m),()=>window.removeEventListener("blur",m)},[n,p]),a(nc,{...c,children:a(qO,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:a(UO,{scope:t,onClose:ae(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})},"Menu"),HO=J(He(function(t,n){const{__scopeMenu:r,...i}=t,o=Mp(r);return a(Xo,{...o,...i,ref:n})},"MenuAnchor")),S_="MenuPortal",[VO,KO]=Xr(S_,{forceMount:void 0}),zO=He(e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,o=ma(S_,t);return a(VO,{scope:t,forceMount:n,children:a(kt,{present:n||o.open,children:a(_i,{asChild:!0,container:i,children:r})})})},"MenuPortal"),dr="MenuContent",[WO,C_]=Xr(dr),JO=J(He(function(t,n){const r=KO(dr,t.__scopeMenu),{forceMount:i=r.forceMount,...o}=t,s=ma(dr,t.__scopeMenu),c=Fp(dr,t.__scopeMenu);return a(jp.Provider,{scope:t.__scopeMenu,children:a(kt,{present:i||s.open,children:a(jp.Slot,{scope:t.__scopeMenu,children:c.modal?a(YO,{...o,ref:n}):a(XO,{...o,ref:n})})})})},"MenuContent")),YO=J(He(function(t,n){const r=ma(dr,t.__scopeMenu),i=B(null),o=Re(n,i);return V(()=>{const s=i.current;if(s)return hs(s)},[]),a(R_,{...t,ref:o,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:te(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),XO=J(He(function(t,n){const r=ma(dr,t.__scopeMenu);return a(R_,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),QO=cn("MenuContent.ScrollLock"),R_=J(He(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,b=ma(dr,r),w=Fp(dr,r),_=Mp(r),R=w_(r),I=FO(r),[T,A]=x(null),O=B(null),F=Re(n,O,b.onContentChange),N=B(0),L=B(""),D=B(0),G=B(null),q=B("right"),$=B(0),E=g?To:z,S=g?{as:QO,allowPinchZoom:!0}:void 0,M=He(U=>{const re=L.current+U,oe=I().filter(Ie=>!Ie.disabled),ie=document.activeElement,se=oe.find(Ie=>Ie.ref.current===ie)?.textValue,ue=E_(oe.map(Ie=>Ie.textValue),re,se),Pe=oe.find(Ie=>Ie.textValue===ue)?.ref.current;He((function Ie(le){L.current=le,window.clearTimeout(N.current),le!==""&&(N.current=window.setTimeout(()=>Ie(""),1e3))}),"updateSearch")(re),Pe&&setTimeout(()=>Pe.focus())},"handleTypeaheadSearch");V(()=>()=>window.clearTimeout(N.current),[]),Ci();const H=ae(U=>q.current===G.current?.side&&x_(U,G.current?.area),[]);return a(WO,{scope:r,searchRef:L,onItemEnter:ae(U=>{H(U)&&U.preventDefault()},[H]),onItemLeave:ae(U=>{H(U)||(O.current?.focus(),A(null))},[H]),onTriggerLeave:ae(U=>{H(U)&&U.preventDefault()},[H]),pointerGraceTimerRef:D,onPointerGraceIntentChange:ae(U=>{G.current=U},[]),children:a(E,{...S,children:a(as,{asChild:!0,trapped:o,onMountAutoFocus:te(s,U=>{U.preventDefault(),O.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:a(bi,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:u,onPointerDownOutside:p,onFocusOutside:f,onInteractOutside:m,onDismiss:v,children:a(uu,{asChild:!0,...R,dir:w.dir,orientation:"vertical",loop:i,currentTabStopId:T,onCurrentTabStopIdChange:A,onEntryFocus:te(d,U=>{w.isUsingKeyboardRef.current||U.preventDefault()}),preventScrollOnEntryFocus:!0,children:a(rc,{role:"menu","aria-orientation":"vertical","data-state":k_(b.open),"data-radix-menu-content":"",dir:w.dir,..._,...h,ref:F,style:{outline:"none",...h.style},onKeyDown:te(h.onKeyDown,U=>{const re=U.target.closest("[data-radix-menu-content]")===U.currentTarget,oe=U.ctrlKey||U.altKey||U.metaKey,ie=U.key.length===1;re&&(U.key==="Tab"&&U.preventDefault(),!oe&&ie&&M(U.key));const se=O.current;if(U.target!==se||!MO.includes(U.key))return;U.preventDefault();const ue=I().filter(Pe=>!Pe.disabled).map(Pe=>Pe.ref.current);b_.includes(U.key)&&ue.reverse(),P_(ue)}),onBlur:te(t.onBlur,U=>{U.currentTarget.contains(U.target)||(window.clearTimeout(N.current),L.current="")}),onPointerMove:te(t.onPointerMove,Oc(U=>{const re=U.target,oe=$.current!==U.clientX;if(U.currentTarget.contains(re)&&oe){const ie=U.clientX>$.current?"right":"left";q.current=ie,$.current=U.clientX}}))})})})})})})},"MenuContentImpl")),Bp="MenuItem",I_="menu.itemSelect",ZO=J(He(function(t,n){const{disabled:r=!1,onSelect:i,...o}=t,s=B(null),c=Fp(Bp,t.__scopeMenu),l=C_(Bp,t.__scopeMenu),d=Re(n,s),u=B(!1),p=He(()=>{const f=s.current;if(!r&&f){const m=new CustomEvent(I_,{bubbles:!0,cancelable:!0});f.addEventListener(I_,v=>i?.(v),{once:!0}),os(f,m),m.defaultPrevented?u.current=!1:c.onClose()}},"handleSelect");return a(ej,{...o,ref:d,disabled:r,onClick:te(t.onClick,p),onPointerDown:f=>{t.onPointerDown?.(f),u.current=!0},onPointerUp:te(t.onPointerUp,f=>{u.current||f.currentTarget?.click()}),onKeyDown:te(t.onKeyDown,f=>{r||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||Op.includes(f.key)&&(f.currentTarget.click(),f.preventDefault())})})},"MenuItem")),ej=J(He(function(t,n){const{__scopeMenu:r,disabled:i=!1,textValue:o,...s}=t,c=C_(Bp,r),l=w_(r),d=B(null),u=Re(n,d),[p,f]=x(!1),[m,v]=x("");return V(()=>{const g=d.current;g&&v((g.textContent??"").trim())},[s.children]),a(jp.ItemSlot,{scope:r,disabled:i,textValue:o??m,children:a(pu,{asChild:!0,...l,focusable:!i,children:a(ye.div,{role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...s,ref:u,onPointerMove:te(t.onPointerMove,Oc(g=>{i?c.onItemLeave(g):(c.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:te(t.onPointerLeave,Oc(g=>c.onItemLeave(g))),onFocus:te(t.onFocus,()=>f(!0)),onBlur:te(t.onBlur,()=>f(!1))})})})},"MenuItemImpl")),[sG,cG]=Xr("MenuRadioGroup",{value:void 0,onValueChange:He(()=>{},"onValueChange")}),tj="MenuItemIndicator",[lG,dG]=Xr(tj,{checked:!1}),nj="MenuSub",[uG,pG]=Xr(nj);function k_(e){return e?"open":"closed"}He(k_,"getOpenState");function T_(e){return e==="indeterminate"}He(T_,"isIndeterminate");function rj(e){return T_(e)?"indeterminate":e?"checked":"unchecked"}He(rj,"getCheckedState");function P_(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}He(P_,"focusFirst");function N_(e,t){return e.map((n,r)=>e[(t+r)%e.length])}He(N_,"wrapArray");function E_(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=N_(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}He(E_,"getNextMatch");function A_(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}He(A_,"isPointInPolygon");function x_(e,t){return t?A_({x:e.clientX,y:e.clientY},t):!1}He(x_,"isPointerInGraceArea");function Oc(e){return t=>t.pointerType==="mouse"?e(t):void 0}He(Oc,"whenMouse");var ij=GO,oj=HO,aj=zO,sj=JO,cj=ZO,lj=Object.defineProperty,ha=(e,t)=>lj(e,"name",{value:t,configurable:!0}),qp="DropdownMenu",[dj,fG]=dt(qp,[__]),ga=__(),[uj,D_]=dj(qp),pj=ha(e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:o,onOpenChange:s,modal:c=!0}=e,l=ga(t),d=B(null),[u,p]=At({prop:i,defaultProp:o??!1,onChange:s,caller:qp});return a(uj,{scope:t,triggerId:Et(),triggerRef:d,contentId:Et(),open:u,onOpenChange:p,onOpenToggle:ae(()=>p(f=>!f),[p]),modal:c,children:a(ij,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})},"DropdownMenu"),fj="DropdownMenuTrigger",mj=J(ha(function(t,n){const{__scopeDropdownMenu:r,disabled:i=!1,...o}=t,s=D_(fj,r),c=ga(r),l=Re(n,s.triggerRef);return a(oj,{asChild:!0,...c,children:a(ye.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:te(t.onPointerDown,d=>{!i&&d.button===0&&d.ctrlKey===!1&&(s.onOpenToggle(),s.open||d.preventDefault())}),onKeyDown:te(t.onKeyDown,d=>{i||(["Enter"," "].includes(d.key)&&s.onOpenToggle(),d.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),hj=ha(e=>{const{__scopeDropdownMenu:t,...n}=e,r=ga(t);return a(aj,{...r,...n})},"DropdownMenuPortal"),gj="DropdownMenuContent",vj=J(ha(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=D_(gj,r),s=ga(r),c=B(!1);return a(sj,{id:o.contentId,"aria-labelledby":o.triggerId,...s,...i,ref:n,onCloseAutoFocus:te(t.onCloseAutoFocus,l=>{c.current||o.triggerRef.current?.focus(),c.current=!1,l.preventDefault()}),onInteractOutside:te(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")),yj=J(ha(function(t,n){const{__scopeDropdownMenu:r,...i}=t,o=ga(r);return a(cj,{...o,...i,ref:n})},"DropdownMenuItem")),bj=pj,_j=mj,wj=hj,Sj=vj,L_=yj;function Cj({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(bj,null,y(_j,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(wj,null,y(Sj,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(L_,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(L_,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function Rj({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 Up({label:e,variant:t=""}){return y(vp,{variant:"provenance",tone:t||void 0},e)}function Ij({tag:e}){const t=uL(e);return t?y(vp,{variant:"tag",title:String(e)},t):null}function kj({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=wc(e?.metadata_json),s=Lc(e,o),c=$O(e,o),l=Tt(e),d=e.title||"(untitled)",u=s&&o?.request?o.request:d,p=e.created_at||e.created_at_utc,f=aL(p),m=gL(e),v=_c(e.files||[]),g=e.project||"",h=bL(e),b=_L(e,o),w=String(e.visibility||o?.visibility||"private").trim(),_=String(e.workspace_kind||o?.workspace_kind||"").trim(),R=String(e.origin_source||o?.origin_source||"").trim(),I=String(e.trust_state||o?.trust_state||"").trim(),T=v.length?` · ${dL(v)}`:"",A=Number(e.id||0),O=A>0?`ID ${A}`:"",[F,N]=x(C.newItemKeys.has(l)),L=s?LO({...e,metadata_json:o}):null,D=s?null:YL({...e,metadata_json:o}),G=D?XL(D):[],q=D?QL(D):"summary",$=C.itemViewState.get(l),E=D&&$&&G.some(we=>we.id===$)?$:q,[S,M]=x(E),H=`${l}:${S}`,[U,re]=x(C.itemExpandState.get(H)===!0),[oe,ie]=x(w==="shared"?"shared":"private"),[se,ue]=x(!1),[Pe,Ie]=x(!1),[le,ve]=x(!1),X=L?xO(L):[];V(()=>{D&&(G.some(we=>we.id===S)||M(q))},[S,q,G,D]),V(()=>{C.itemViewState.set(l,S)},[S,l]),V(()=>{const we=`${l}:${S}`;re(C.itemExpandState.get(we)===!0)},[S,l]),V(()=>{ie(w==="shared"?"shared":"private")},[w]),V(()=>{if(!F)return;const we=window.setTimeout(()=>{C.newItemKeys.delete(l),N(!1)},700);return()=>window.clearTimeout(we)},[F,l]);const ce=oe,be=ce==="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.",fe=[g?`Project ${g}`:"No project",f].filter(Boolean).join(" · "),We=[_&&_!==w?`Workspace ${_}`:"",R?`From ${R}`:"",b,I&&I!=="trusted"?yL(I):""].filter(Boolean).join(" · "),he=[T.trim(),We].filter(Boolean).join(" · "),W=!!D&&ZL(S,D),de=[S==="facts"?"feed-body facts":"feed-body",S==="narrative"?"narrative":"",W&&!U?e$(S).join(" "):""].filter(Boolean).join(" "),ne=s?X.length?y("div",{className:"feed-body facts"},X):y_(String(e.body_text||""))||y("div",{className:"feed-body"}):D?S==="facts"?DO(D.facts)||y("div",{className:de}):y_(S==="narrative"?D.narrative:D.summary,de)||y("div",{className:de}):y("div",{className:"feed-body"});async function xe(we){const Ye=ce;ie(we),ue(!0);try{const Xe=await $C(A,we);Xe?.item&&(t(Xe.item),r()),Z(we==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Xe){ie(Ye),Z(Xe instanceof Error?Xe.message:"Failed to save visibility.","warning")}finally{ue(!1)}}async function tt(){const we=String(e.project||"").trim(),Ye=we,Xe=String(u||"this memory").trim(),Kt=Xe.length>80?`${Xe.slice(0,79).trimEnd()}…`:Xe,Ua=we?`Move "${Kt}" from "${we}" 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 "${Kt}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let li=[];try{li=(await Va()).filter(lt=>lt&<!==we)}catch{}const di=await rp({title:"Assign to project",description:Ua,initialValue:Ye,placeholder:"Pick one or type a new project name",suggestions:li,confirmLabel:"Move",cancelLabel:"Cancel",validate:lt=>{const _n=lt.trim();return _n?_n===we?"Already assigned to this project.":null:"Enter a project name."}});if(di==null)return;const ui=di.trim();if(!(!ui||ui===we)){ve(!0);try{const lt=await OC(A,ui),_n=Number(lt.moved_memory_count||1),fo=_n>1?`Moved ${_n} memories from this session to "${lt.project}".`:`Moved to "${lt.project}".`;Z(fo),await i(),r()}catch(lt){Z(lt instanceof Error?lt.message:"Failed to move memory.","warning")}finally{ve(!1)}}}async function po(){const we=String(u||"this memory").trim(),Ye=we.length>80?`${we.slice(0,79).trimEnd()}…`:we;if(await hn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${Ye}". 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"})){Ie(!0);try{await jC(A),n(A),r(),await i(),Z("Memory forgotten and removed from the active feed.")}catch(Xe){Z(Xe instanceof Error?Xe.message:"Failed to forget memory.","warning")}finally{Ie(!1)}}}const Vn=c.replace(/_/g," "),bn=v.length?y("div",{className:"feed-files"},v.map((we,Ye)=>y("span",{className:"feed-file",key:`${String(we)}-${Ye}`},String(we)))):null;return y("article",{className:`feed-item ${c}${F?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(vp,{variant:"kind",tone:c},Vn)),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:MN(u,C.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},fe)),y("div",{className:"feed-actions"},D?y(Rj,{active:S,modes:G,onSelect:we=>M(we)}):null,y(kc,{label:oL(p),side:"left"},y("div",{className:"small feed-age"},f)),e.owned_by_self&&A>0?y(Cj,{assignProjectDisabled:le,disabled:Pe,onAssignProject:()=>{tt()},onForget:()=>{po()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(Up,{label:h,variant:h==="You"?"mine":"author"}),y(Up,{label:w||"private",variant:w||"private"}),O?y(kc,{label:`Memory database id ${A}`,side:"top"},y(Up,{label:O,variant:"memory-id"})):null),he?y("div",{className:"feed-meta"},he):null,ne,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},m.length?y("div",{className:"feed-tags"},m.map((we,Ye)=>y(Ij,{key:`${String(we)}-${Ye}`,tag:we}))):null,e.owned_by_self&&A>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:se,onChange:we=>{xe(String(we.currentTarget.value)==="shared"?"shared":"private")},value:ce},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},be)):null),y("div",{className:"feed-footer-right"},W?y("button",{className:"feed-expand",onClick:()=>{const we=!U;C.itemExpandState.set(H,we),re(we)},type:"button"},U?"Collapse":"Expand"):null)),bn))}function Tj({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 Pj({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(Tj,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!C.feedQuery.trim()||C.feedTypeFilter!=="all"||C.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(kj,{item:r,key:Tt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function $_({id:e,active:t,options:n,onSelect:r}){return y("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{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"},o)}))}function Nj({text:e}){return y("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function Ej({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 Aj({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=x(!1);return y(z,null,y("div",{className:"feed-controls"},y(Nj,{text:n||t$(t.length,r.hasMorePages())}),y("div",{className:"feed-controls-right"},y(Ej,{query:C.feedQuery,onQuery:r.updateFeedQuery}),y($_,{active:C.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==C.feedScopeFilter&&(Kv(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y($_,{active:C.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==C.feedTypeFilter&&(XN(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:()=>o(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),y(n$,{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(Pj,{items:t,loadingText:n,ops:r}):null)))}function xj(e){return C.feedTypeFilter==="observations"?e.filter(t=>!Lc(t,wc(t?.metadata_json))):C.feedTypeFilter==="summaries"?e.filter(t=>Lc(t,wc(t?.metadata_json))):e}function Dj(e){const t=e.map(n=>`${Rb(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${C.feedTypeFilter}|${C.feedScopeFilter}|${C.currentProject}|${ra(C.feedQuery)}|${t.join("|")}`}var O_="",va=0,ya=0,Zi=!0,eo=!0,jc=null,Lj=0,qt=null,j_=!1,to=0,Gp="all",M_="",ba=null,no="",mG=250;function F_(e){O_=e,Gp=C.feedScopeFilter,M_=C.feedQuery.trim(),no="",to+=1,va=0,ya=0,Zi=!0,eo=!0,C.lastFeedItems=[],C.pendingFeedItems=null,C.lastFeedFilteredCount=0,C.lastFeedSignature="",C.newItemKeys.clear(),C.itemViewState.clear(),C.itemExpandState.clear()}function Hp(){return Zi||eo}function $j(e){const t=Tt(e);C.lastFeedItems=C.lastFeedItems.map(n=>Tt(n)===t?e:n)}function Oj(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Tt(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 jj(){if(!Hp())return;const e=to;if(jc===e)return;const t=C.currentProject||"",n=C.feedQuery.trim(),r=va,i=ya;jc=e;try{const[o,s]=await Promise.all([Zi?gm(t,{limit:20,offset:r,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),eo?vm(t,{limit:50,offset:i,scope:C.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==to||t!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(f=>!Cb(f));C.lastFeedFilteredCount+=l.length-d.length,eo=Sc(s,c.length,50),Zi=Sc(o,l.length,20),ya=Cc(s,i+c.length),va=Cc(o,r+l.length);const u=[...c,...d],p=Ib(C.lastFeedItems,u);C.lastFeedItems=p,Qr()}finally{jc===e&&(jc=null)}}function B_(){C.activeTab==="feed"&&(ba||qt||Hp()&&SL()&&jj())}var Mj={replaceFeedItem:$j,removeFeedItem:Oj,updateFeedView:e=>Qr(e),loadFeedData:()=>zp(),updateFeedQuery:e=>Bj(e),hasMorePages:Hp};function Vp(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;zL(n,y(Aj,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:Mj}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Kp(e="Loading selected project..."){Vp([],{loadingText:e})}function Fj(){KL(),Vp(C.lastFeedItems,C.lastFeedItems.length||C.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),j_||(window.addEventListener("scroll",()=>{B_()},{passive:!0}),j_=!0)}function Bj(e){if(e===C.feedQuery)return;const t=C.feedQuery.trim();C.feedQuery=e,e.trim()!==t&&(F_(C.currentProject||""),Kp("Searching memories…"),ba&&clearTimeout(ba),ba=setTimeout(()=>{ba=null,zp().catch(()=>{})},250))}function Qr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=xj(C.lastFeedItems),r=Dj(n),i=e||r!==C.lastFeedSignature;C.lastFeedSignature=r,i&&Vp(n,{errorText:no||void 0}),window.scrollTo({top:t}),B_()}async function zp(){const e=C.currentProject||"",t=C.feedScopeFilter!==Gp,n=C.feedQuery.trim(),r=n!==M_;(e!==O_||t||r)&&(F_(e),Kp(r?"Searching memories…":void 0));const i=to,o=++Lj;qt={generation:i,requestId:o};const s=!!no;s&&(no="",C.lastFeedItems.length>0?Qr(!0):Kp(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([gm(e,{limit:20,offset:0,scope:C.feedScopeFilter,q:n||void 0}),vm(e,{limit:50,offset:0,scope:C.feedScopeFilter,q:n||void 0})]);if(qt?.generation!==i||qt.requestId!==o||i!==to||e!==(C.currentProject||"")||n!==C.feedQuery.trim())return;const p=u.items||[],f=d.items||[],m=n?f:f.filter(w=>!Cb(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=wL(C.lastFeedItems,g),b=C.lastFeedItems;if(CL(h,b)&&b.length>0){const w=new Set(b.map(Tt));h.forEach(_=>{w.has(Tt(_))||C.newItemKeys.add(Tt(_))})}C.pendingFeedItems=null,C.lastFeedItems=h,no="",C.lastFeedFilteredCount=Math.max(C.lastFeedFilteredCount,v),eo=Sc(u,p.length,50),Zi=Sc(d,f.length,20),ya=Math.max(ya,Cc(u,p.length)),va=Math.max(va,Cc(d,f.length)),Gp=C.feedScopeFilter,qt?.generation===i&&qt.requestId===o&&(qt=null),Qr(s)}catch(c){throw qt?.generation===i&&qt.requestId===o&&i===to&&e===(C.currentProject||"")&&n===C.feedQuery.trim()&&(Zi=!1,eo=!1,no="Feed unavailable. Refresh and try again.",Qr(!0)),c}finally{qt?.generation===i&&qt.requestId===o&&(qt=null)}}function qj(e){return e.channel==="latest"?"stable":e.channel}function hG(e){return e}function Uj(e){const t=new Date(e.periodStart),n=new Date(e.periodEnd),r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),i=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});return t.getFullYear()===n.getFullYear()?[r.format(t),i.format(n)]:[i.format(t),i.format(n)]}function Gj(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function Hj(e){if(e.freshEvaluations===0)return[{label:"Recalls checked",value:0,tooltip:"No automatic recalls were checked for repeated memories in this period.",icon:"activity"},{label:"Not checked",value:e.unmeasuredAttempts,tooltip:`Codemem could not check ${e.unmeasuredAttempts.toLocaleString()} automatic recalls for repeated memories, so savings are unknown.`,icon:"circle-help"}];const t=Gj(e.evaluationsWithDuplicates,e.freshEvaluations),n=e.missingRetainedMetadata>0||e.invalidRetainedMetadata>0||e.packMetadataGaps>0;return[{label:"Recalls with repeats",value:t,tooltip:`Codemem removed repeated memories from ${e.evaluationsWithDuplicates.toLocaleString()} of ${e.freshEvaluations.toLocaleString()} automatic recalls.`,icon:"filter"},{label:"Memories skipped",value:e.duplicatesOmitted,tooltip:`Codemem left out ${e.duplicatesOmitted.toLocaleString()} memories that were already in your conversation, out of ${e.candidateItems.toLocaleString()} considered.`,icon:"minus-circle"},{label:"Repeated tokens removed",value:`~${Wi(e.estimatedTokensAvoided)}`,tooltip:`About ${e.estimatedTokensAvoided.toLocaleString()} tokens were left out because they repeated information already in your conversation.`,icon:"trending-down"},{label:"Recalls checked",value:e.freshEvaluations,tooltip:`Codemem checked ${e.freshEvaluations.toLocaleString()} automatic recalls for repeated memories. ${e.unmeasuredAttempts.toLocaleString()} more could not be checked.${n?" Some results may be incomplete.":""}`,icon:"activity"}]}function Vj(e){if(!e||e.availability==="unavailable")return y("p",{class:"section-meta"},"Automatic recall details aren’t available. Update Codemem and refresh this page.");const[t,n]=Uj(e);return y(z,null,y("div",{class:"grid-2 automatic-recall-grid"},Hj(e).map(r=>y(q_,{...r,key:`${r.label}-${r.icon}`}))),y("p",{class:"automatic-recall-meta"},y("time",{dateTime:e.periodStart},t),"–",y("time",{dateTime:e.periodEnd},n),` · Based on up to ${e.windowLimit.toLocaleString()} recent automatic recalls across all projects.${e.freshEvaluations===0?" No recalls were checked, so savings are unknown.":""}`))}function Kj(e,t){e&&(Ue(y(Ic,null,y("details",{class:"automatic-recall"},y("summary",null,"Automatic recall"),y("section",{"aria-label":"Automatic recall measurements"},Vj(qC(t))))),e),Mc())}function zj(e){if(!e.latest_version)return{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"};if(e.stale)return{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"};if(e.update_available)return{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"};const t=qj(e);return t?{title:`Codemem ${e.current_version} is up to date`,detail:`You are running the latest ${t} release.`,tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not on a supported release channel.",tone:"unavailable"}}function Wj({status:e}){const t=zj(e),n=e.update_available||e.stale||!e.latest_version||!e.channel;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 Jj(e,t){e&&(e.hidden=!t,Ue(t?y(Wj,{status:t}):null,e))}function Yj({label:e,value:t,detail:n,icon:r,className:i,title:o}){const s=y("div",{class:`stat${i?` ${i}`:""}`,style:o?"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 o?y(kc,{label:o},s):s}function Xj({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(t)}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Uo(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:o,ref:s=>{n=s}},"Copy"):null))}function Qj(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function q_({label:e,value:t,icon:n,tooltip:r}){const i=y("div",{class:"stat",style:r?"cursor: help;":void 0,tabIndex:r?0:void 0},y("i",{"data-lucide":n,class:"stat-icon"}),y("div",{class:"stat-content"},y("div",{class:"value"},Qj(t)),y("div",{class:"label"},e)));return r?y(kc,{label:r},i):i}function U_(e,t){e&&Ue(y(Ic,null,t.map(n=>y(q_,{...n,key:`${n.label}-${n.icon}`}))),e)}function G_(e,t){e&&Ue(y(z,null,t),e)}function Mc(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function Zj(e,t){e&&Ue(y(Ic,null,t.map(n=>y(Yj,{...n,key:n.key??n.label}))),e)}function eM(e,t){if(e){if(!t.length){e.hidden=!0,Ue(null,e);return}e.hidden=!1,Ue(y(z,null,t.slice(0,3).map((n,r)=>y(Xj,{item:n,key:`${n.label}-${r}`}))),e)}}var H_="scope_id_backfill";function tM(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>Ar({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function V_(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;Jj(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(de=>de.kind===H_),u=l.some(de=>de.status==="failed"),p=i.reliability||{},f=p.counts||{},m=p.rates||{},v=i.database||{},g=o.totals_filtered||o.totals||o.totals_global||i.usage?.totals||{},h=Array.isArray(o.recent_packs)?o.recent_packs:[],b=h.length?h[0]?.created_at:null,w=h.length?h[0]?.metadata_json||{}:{},_=Number(w?.exact_duplicates_collapsed||0),R=Number(s.pending||0),I=Number(f.errored_batches||0),T=Number(m.flush_success_rate??1),A=Number(m.dropped_event_rate||0),O=up(g.tokens_saved,g.tokens_read),F=cL(O),N=Number(v.tags_coverage||0),L=String(c.daemon_state||"unknown"),D=L==="offline-peers"?"Offline peers":L==="needs_attention"?"Needs attention":L==="rebootstrapping"?"Rebootstrapping":wb(L),G=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers.length:0,q=L==="disabled"||c.enabled===!1,$=L==="offline-peers",E=!q&&G===0;let S=q?"Disabled":E?"No peers":D;const M=c.last_sync_at||c.last_sync_at_utc||null,H=zi(M),U=zi(b),re=H!==null&&H>7200,oe=H!==null&&H<=300,ie=R>=200;let se=0;const ue=[];R>=1e3?(se+=40,ue.push("high raw-event backlog")):R>=200&&(se+=24,ue.push("growing raw-event backlog")),I>0&&R>=200&&(se+=I>=5?10:6,ue.push("batch errors during backlog pressure")),T<.95&&(se+=20,ue.push("lower flush success")),A>.02?(se+=24,ue.push("high dropped-event rate")):A>.005&&(se+=10,ue.push("non-trivial dropped-event rate")),!q&&!E&&(L==="error"?(se+=36,ue.push("sync daemon reports errors")):L==="needs_attention"?(se+=40,ue.push("sync needs manual attention")):L==="stopped"?(se+=22,ue.push("sync daemon stopped")):L==="degraded"&&!oe&&(se+=20,ue.push("sync daemon degraded")),$?(se+=4,ue.push("all peers currently offline"),re&&(se+=4,ue.push("offline peers and sync not recent"))):re?(se+=26,ue.push("sync looks stale")):H!==null&&H>1800&&(se+=12,ue.push("sync not recent"))),F!==null&&F<10&&(se+=8,ue.push("low retrieval reduction")),U!==null&&U>86400&&(se+=12,ue.push("memory pack activity is old"));let Pe="Healthy",Ie="status-healthy";se>=60?(Pe="Attention",Ie="status-attention"):se>=25&&(Pe="Degraded",Ie="status-degraded");const le=Ie==="status-healthy";r&&(r.className=`health-dot ${Ie}`,r.title=Pe);const ve=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${_.toLocaleString()} deduped in latest pack`,X=R>0?"Queue is actively draining":"Queue is clear",ce=q?"Sync disabled":E?"No peers configured":$?`${G} peers offline · last sync ${sr(H)} ago`:`${G} peers · last sync ${sr(H)} ago`;le&&!q&&!E&&($?S="Peers offline":L==="degraded"&&oe&&(S="Syncing"));const be=`last pack ${sr(U)} ago`,fe=l.map(de=>{const ne=Number(de.progress?.current||0),xe=typeof de.progress?.total=="number"?de.progress.total:null,tt=String(de.progress?.unit||"items"),po=xe&&xe>0?` (${Math.round(100*ne/xe)}%)`:"",Vn=xe&&xe>0?`${ne.toLocaleString()}/${xe.toLocaleString()} ${tt}${po}`:`${ne.toLocaleString()} ${tt}`,bn=de.status==="failed",we=de.status==="completed",Ye=de.kind===H_,Xe=bn?"Failed":we?"Complete":Vn,Kt=bn?String(de.error||"unknown error").trim():we?Ye?`${Vn} · one-time Sharing-domain upgrade finished`:Vn:Ye?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(de.kind||de.title||"background-maintenance"),label:String(de.title||de.kind||"Background maintenance"),value:Xe,detail:Kt,icon:bn?"alert-triangle":we?"check-circle":"loader",className:bn?"status-attention":void 0,title:bn?`Error: ${de.error||"unknown"}`:we?`${String(de.title||"Maintenance")} finished`:Ye?`${String(de.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(de.title||"Maintenance")} in progress`}}),We=[{key:"overall-health",label:"Overall health",value:Pe,detail:`Weighted score ${se}`,icon:"heart-pulse",className:`health-primary ${Ie}`,title:ue.length?`Main signals: ${ue.join(", ")}`:"No major risk signals detected"},...fe,{key:"pipeline-health",label:"Pipeline health",value:`${R.toLocaleString()} pending`,detail:X,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:O,detail:ve,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:S,detail:ce,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:sr(U),detail:be,icon:"clock-3",title:"Recency of last memory pack activity"}];Zj(e,We);const he=async()=>{await xl()},W=[];ie?(W.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status",action:de=>Ar({subsystem:"capture",trigger:de}),actionLabel:"View diagnostics"}),W.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):L==="stopped"?W.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!q&&!E&&!le&&(L==="error"||L==="degraded")?(W.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:he,actionLabel:"Sync now"}),W.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!q&&!E&&re&&W.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:he,actionLabel:"Sync now"}),tM(W,u),N>0&&N<.7&&W.length<2&&W.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&W.length<3&&W.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),eM(n,W),t.textContent=ue.length?`Why this status: ${ue.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Mc()}function nM(){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(I=>I.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=up(m,f),b=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${Vr(u)}`:"",_=o?"Project":"All projects",R=[{label:"Last pack savings",value:l?`${Wi(m)} (${h})`:"n/a",tooltip:l?`Exact: ${m.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Wi(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"}];G_(t,[_,b,w].filter(Boolean).join(" · ")),U_(e,R),Mc()}function rM(){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
109
|
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",v=d?`
|
|
110
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: ${p0(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:By(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:By(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=g0(o.path||"unknown");l_(t,`DB: ${w} · ${v0(o.size_bytes||0)}${y}`)}Ip()}async function rj(){const e=C.lastStatsPayload?.identity?.actor_id||null,t=C.activeTab==="health"&&!C.lastUpdateStatus?QC().catch(ZC):Promise.resolve(C.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([eC(),tC(C.currentProject),nC(C.currentProject),rC(C.currentProject),t]);C.lastStatsPayload=n||{},C.lastUsagePayload=r||{},C.lastRawEventsPayload=o||{},C.lastUpdateStatus=s;const c=C.lastStatsPayload?.identity?.actor_id||null;nj(),tj(),u_(),C.activeTab==="feed"&&e!==c&&Jr(!0)}function Rp(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 ij={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 oj(e){return e.targetIdentityRef??e.existingIdentityRef??""}function aj({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=oj(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),R=n?.has(o.deviceRef)??!1,k=e||R||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:R?Rp("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: ",ij[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 sj(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(aj,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function cj(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function lj({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,R]=x(w);K(()=>R(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=cj(c,f),B=[L||F?u:void 0,e?t:A?Rp("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:$=>R($.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 dj(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(lj,{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"},uj=10;function pt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Pp(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${Ro(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>uj;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 pj({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}.`),R=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=Pp(o.projectChanges,S=>S.projectDisplayName,S=>S.projectRef,()=>"project"),L=Pp(o.recipientChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),F=Pp(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:R,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 fj(e){let t=null;return async n=>{try{const r=await mj(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 hj(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 mj(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 hj(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Nt)||!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 gj(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.",vj="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",yj="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",bj="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",w_="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",_j="Another device completed this Team with different reviewed details. Retry to load the completed setup.",wj="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function Sj(){return{status:"closed",generation:0}}function Np(e,t){switch(t.type){case"open":return e.status==="open"&&Mn(e)?e:Cj(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 Ij(e,t.step);case"blocked_navigation":return Tc(e,t.step,t.message);case"retry":return Rj(e);case"refresh":return kj(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 Pj(e,t);case"finish":return Tj(e);case"command_started":return qj(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return Nj(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function Cj(e,t){return cr({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 Ij(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:gj(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function Rj(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 cr(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 cr(Yr(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function Pj(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:cr(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 kj(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||ya(e)||Mn(e)?e:cr(Yr(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function Tj(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:cr(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 cr(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 Nj(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"?Aj(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?xj(r,n.attemptId):t.view?S_({...Uj(r,n),message:Ej(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function Ej(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 Aj(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?S_(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=Dj(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 S_(e,t,n){const r=Fj(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:Bj(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=cr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function xj(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=cr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function Dj(e,t,n){const r=t instanceof Nt&&Tp(t.errorCode),i=t instanceof Nt&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=jj({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i});return{scope:$j(e,{globalError:r||i||o!==null}),message:s,retry:Lj(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null})}}function $j(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 Lj(e,t,n,r){return t instanceof Nt&&t.errorCode==="team_setup_confirmation_stale"||n instanceof Nt&&n.errorCode==="team_setup_confirmation_stale"||r.terminalRecovery?"load":r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load"}function jj(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Nt?xp(n.errorCode):null,c=Mj(r instanceof Nt?xp(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?Oj(n):I_(l);if(c)return{completionCode:l,message:d??C_(t.kind),terminalRecoveryCode:c};if(i)return{completionCode:l,message:b_,terminalRecoveryCode:c};if(o){let u=__;return t.kind==="finish"&&(u=n instanceof Nt&&n.reason==="local_candidate_scan_budget_exceeded"?yj:vj),{completionCode:l,message:u,terminalRecoveryCode:c}}return{completionCode:l,message:d??C_(t.kind),terminalRecoveryCode:c}}function Oj(e){return e instanceof Nt&&e.reason==="coordinator_route_missing"?`${w_} The coordinator may be running an older version.`:w_}function Mj(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function C_(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 Fj(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 Bj(e){if(Tp(e))return b_;if(e==="team_setup_roster_unavailable")return __;const t=I_(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 I_(e){return e==="team_setup_completion_unavailable"?bj:e==="team_setup_completion_conflict"?_j:e==="team_setup_completion_invalid"?wj:null}function R_(e){return e.kind==="global"||e.kind==="load"}function Yr(e,t){const n=R_(t);return{...e,errors:e.errors.filter(r=>n?!R_(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function Uj(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 qj(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 Gj={role:"list"},Hj={role:"listitem"};function Kj(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(Pr,{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(rP,{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?Rp(_.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(Vj,{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(sj,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:g,busyDeviceRefs:y,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(dj,{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(pj,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(zj,{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 Vj(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(z,{children:[a("ol",{...Gj,"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",{...Hj,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 zj(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 Wj={clearDecision:RC,finish:TC,loadDetail:SC,onCompleted:()=>{},refreshCandidate:kC,saveAssignment:CC,saveDecision:IC,saveProjectMapping:PC},Dp="codemem:open-legacy-team-setup";function k_(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 Jj(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 Yj({dependencies:e}){const[t,n]=x(Sj),r=q(null),i=Pe(()=>fj(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(Kj,{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=>Qj(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:Xj,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var Xj=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function Qj(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(Jj(t.current)?t.current:n)?.focus(),t.current=null}function Zj(e,t={}){const n={...Wj,...t};We(a(Yj,{dependencies:n}),e)}var ba=new WeakMap;function Fn(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function $p(e,t){const n=document.createElement("h3");return n.className="recipient-policy-review-heading",n.textContent=`${e} (${t.toLocaleString()})`,n}function eO(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-review-item";const n=document.createElement("h4");return n.className="project-inventory-title",n.textContent=e.finding,t.append(n,Fn(e.reason,"project-inventory-meta")),t}function tO(e){const t=document.createElement("section");t.className="recipient-policy-review-section recipient-policy-review-decisions",t.append($p("Review findings",e.reviewItems.length),Fn("Access has not changed. These findings are informational because this view has no decision controls. You may use the existing sharing controls below to change access, but those changes do not record a review decision.","section-meta"));const n=document.createElement("div");n.className="project-inventory-list recipient-policy-review-list";for(const r of e.reviewItems)n.appendChild(eO(r));return t.appendChild(n),t}function nO(e){const t=e.categoryCounts.preservedContinuity,n=document.createElement("section");n.className="recipient-policy-review-section recipient-policy-review-continuity";const r=Fn(`${t.toLocaleString()} preserved legacy finding${t===1?"":"s"}. Access has not changed. These preserved findings require no action. Next step: none for this category; Codemem will keep this legacy sharing state as-is.`,"settings-note");return r.setAttribute("role","status"),r.setAttribute("aria-live","polite"),n.append($p("Preserved legacy continuity",t),r),n}function rO(e,t){const n=document.createElement("section");n.className="recipient-policy-review-section recipient-policy-review-blocked",n.append($p("Blocked source repairs",e.blockedItems.length),Fn("Access has not changed. Action is required before Codemem can safely interpret these records. Next step: repair each source record below.","section-meta project-attention-note"));const r=document.createElement("div");r.className="project-inventory-list recipient-policy-review-list";for(const i of e.blockedItems)r.appendChild(iO(i,t));return n.appendChild(r),n}function iO(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=Fn(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,Fn(e.reason,"project-inventory-meta"),s,Fn(`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(Fn("Open Projects to repair this item.","settings-note"));return n}function oO(e,t,n={}){const r=`review:${t.blockedItems.map(c=>n.onRepair&&(n.isRepairAvailable?.(c.repair)??!0)?"1":"0").join("")}:${JSON.stringify(t)}`;if(ba.get(e)===r)return;const{preservedContinuity:i}=t.categoryCounts;if(t.reviewItems.length===0&&i===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,ba.set(e,r);return}e.hidden=!1;const o=document.createElement("section");o.className="card recipient-policy-review",o.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const s=document.createElement("h2");s.id="recipientPolicyReviewTitle",s.textContent="Sharing review",o.appendChild(s),t.reviewItems.length>0&&o.appendChild(tO(t)),i>0&&o.appendChild(nO(t)),t.blockedItems.length>0&&o.appendChild(rO(t,n)),e.replaceChildren(o),ba.set(e,r)}function aO(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=Fn(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),ba.set(e,r)}var T_=[["","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,Bt=0,Ec=250,sO=100,Lp=[],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,Bn=0,Ca=0,Qi=null,Ia=null,Ut=new Set,N_=new WeakMap,jc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Zi=jc,dr=!1,jp;function Op(e=!1){if(!e&&Ia)return Ia;const t=rm().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 cO(e){return T_.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function lO(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 dO(e){const t=wa.get(e.workspace_identity);(!t||mn(t)&&!mn(e))&&wa.set(e.workspace_identity,e)}function Mp(e){return mn(e)?"Received from peers":Fc(e.resolved_scope_id)}function uO(e){return mn(e)?"source-owned project":lO(e.resolution_reason)}function pO(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 E_(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function A_(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Qr(){const e=Ut.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=N_.get(r)??[],o=i.filter(s=>Ut.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 fO(e){const t=e.every(n=>Ut.has(n));for(const n of e)t?Ut.delete(n):Ut.add(n);Qr()}function x_(e,t){const n=A_(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),N_.set(i,n),i.addEventListener("change",()=>fO(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function mO(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 D_(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=mO(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 $_(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)Ut.add(r);Qr(),To({mode:"project-add",projectIds:[...e].sort()})})),n}function hO(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function Fp(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function Bp(e){return e.project||e.display_project||"Unnamed Project"}function L_(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 gO(){return new Set(C.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function vO(e){return!Sa||e.authority_type!=="coordinator"||!e.group_id?!1:!gO().has(String(e.group_id).trim())}function Mc(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function j_(){Lc&&(Lc=!1,yt?.())}async function yO(){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 qf(!1);C.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],Sa=!0}catch{C.lastProjectCoordinatorAdminGroups=[],Sa=!1}}function bO(e){return e.kind==="team_default"}function Up(e){const t=e.label||"Untitled Space";return bO(e)?`${t} (default)`:t}function _O(e,t){const n=Up(e);return t.some(r=>r.scope_id!==e.scope_id&&Up(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function wO(e){const t=L_(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 SO(e){return e?Lp.find(t=>t.scope_id===e)??null:null}function Fc(e){const t=SO(e);return e?t?`${Up(t)} · ${wO(t)}`:"Unknown Space":"—"}function qp(){return Lp.filter(e=>e.scope_id!=="legacy-shared-review"&&!vO(e))}function CO(e){return qp().some(t=>t.scope_id===e)}function O_(...e){for(const t of e)if(t&&CO(t))return t;return e.find(t=>!!t)??""}function IO(e){const t=L_(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function RO(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function PO(){const e=new Map;for(const t of qp()){const n=RO(t),r=IO(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function M_(e){for(const t of PO()){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=_O(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function kO(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 Gp(e,t,n=[]){try{await BC({...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 TO(e,t){const n=e.filter(Oc);if(n.length!==0)try{await UC({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(Fp(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 NO(e){if(e.mapping_id!=null)try{await qC(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 F_(e,t=!1){try{const n=_a.get(e.workspace_identity),r=await HC({...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 Qf){_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 B_(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 GC({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 EO(e){const t=wa.get(e);if(t&&!mn(t))return{offset:Bt,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>=sO)return null;n=s}}catch{return null}}function U_(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 AO(e){if(Mc()){Q("Finish the open Space assignment, then try Repair again.","warning");return}const t=Bn,n=De("projectsSearch")?.value??"",r=De("projectsStatusFilter")?.value??"",i=Bt,o=await EO(e.projectIdentity);if(Bn!==t||(De("projectsSearch")?.value??"")!==n||(De("projectsStatusFilter")?.value??"")!==r||Bt!==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 B_(s);return}if(!U_(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=Bt;Bt=o.offset;const v=Bn;if(await Ra(),!U_(s.workspace_identity)){if(Bn!==v||c&&c.value!==d||u&&u.value!==f||Bt!==o.offset)return;c&&(c.value=l),u&&(u.value=p),Bt=m,await Ra(),Q("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function xO(e){const t=Bn,n=(Qi?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Bn===t)try{await AO(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 DO(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=qp().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)}M_(i),i.value=O_(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",()=>{Gp(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",j_);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{Gp(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",()=>{NO(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",()=>{B_(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",()=>{F_(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"),R=document.createElement("strong");R.textContent=`${kO(_)}: `;const k=document.createElement("span");k.textContent=_.message,I.append(R,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||Gp(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",()=>{F_(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 q_(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(x_([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($_([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 · ${E_(e.latest_session_at)}`,t.appendChild(o),t.appendChild(D_([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=Mp(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${uO(e)} · ${e.identity_source} · ${E_(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"),R=document.createElement("strong");R.textContent=pO(_);const k=document.createElement("span");k.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,I.append(R,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=hO(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=cO(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",Mp(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(DO(e)),t.appendChild(p),t}function $O(e){const t=[...new Set(e.map(n=>Mp(n)))];return t.length===1?t[0]:"Mixed Spaces"}function LO(e){if(e.length===1)return q_(e[0]);const t=Fp(e[0]),n=e.filter(ps),r=A_(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const o=Bp(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(x_(n,`Select all identities for ${Bp(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($_(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=$O(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(D_(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),R=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 ${Bp(e[0])} group`);const L=document.createElement("option");L.value="",L.textContent="Choose Space…",A.appendChild(L),M_(A),A.value=O_($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",()=>{TO(g,A.value)}),A.addEventListener("change",()=>{A.value?$c.set(t,A.value):$c.delete(t),F.disabled=!A.value||I}),A.addEventListener("blur",j_),v.append(A,F),R.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(R=>R.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(q_(_));return i.appendChild(h),i}function jO(e){const t=new Map;for(const n of e){const r=Fp(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function G_(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 H_(){document.getElementById("projectsInventorySkeleton")?.remove()}function K_(e){const t=De("projectsInventoryMeta"),n=De("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;H_(),wa.clear();for(const s of e.projects)dO(s);if(n.textContent="",e.projects.length===0)G_("No projects match those filters.");else for(const s of jO(e.projects))n.appendChild(LO(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 OO(e,t){yO().then(()=>{t===Xi&&(Mc()||K_(e))})}async function MO(){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 V_(e,t,n){const r=De("recipientPolicyManagementMount");r&&gg(r,fs(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Ut.clear(),Qr(),yt?.()}})}function z_(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),jp){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",()=>jp?.(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 W_(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 FO(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 Ra(e={}){const t=De("projectsInventoryMeta"),n=De("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await Op(!0)).ok:!0;if(Mc()){if(Lc=!0,!e.requireTeamSetupSummary)return!0;const i=++Ca,o=await Op(!0);if(i!==Ca)return!1;const s=De("recipientPolicyReviewMount");return o.ok?(s&&z_(s,o.summary),!0):(s&&W_(s),!1)}Lc=!1;const r=++Xi;lr=!1,dr=!1,Qr(),t.textContent="Loading project inventory…";try{const i=++Ca,o=Op(e.requireTeamSetupSummary===!0),[s,c,l,d,u]=await Promise.all([ho({limit:Ec,offset:Bt,q:De("projectsSearch")?.value.trim()||void 0,status:De("projectsStatusFilter")?.value||void 0}),LC(),MO().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),$C().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(Lp=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 Ut)g.has(h)||Ut.delete(h)}const p=De("projectShareFlowMount");p&&wg(p,l.projects,{inventoryError:!l.ok});const f=De("recipientPolicyReviewMount");if(f){const g=FO(f);"review"in d?oO(g,d.review,{isRepairAvailable:h=>!h.projectIdentity.startsWith("unmapped:"),onRepair:xO}):aO(g,d.error),f.hidden=g.hidden&&!f.querySelector(".project-team-setup-entry")}V_(l.projects,Zi,!l.ok||!u.ok),K_(s),OO(s,r),o.then(g=>{if(r!==Xi||i!==Ca)return;const h=De("recipientPolicyReviewMount");if(h){if(!g.ok){W_(h);return}z_(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&&wg(o,[],{inventoryError:!0}),V_([],jc,!0),Qr(),H_(),t.textContent="Project inventory failed to load.",G_(i instanceof Error?i.message:"Unable to load project inventory."),!1}}function BO(e,t={}){yt=e,jp=t.onOpenTeamSetup,Ut.clear();const n=De("projectsStatusFilter");if(n&&n.options.length===0)for(const[o,s]of T_){const c=document.createElement("option");c.value=o,c.textContent=s,n.appendChild(c)}const r=()=>{Bn+=1,Bt=0,yt?.()};De("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),De("projectsPrevPage")?.addEventListener("click",()=>{Bn+=1,Bt=Math.max(0,Bt-Ec),yt?.()}),De("projectsNextPage")?.addEventListener("click",()=>{Bn+=1,Bt+=Ec,yt?.()});const i=De("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Ut.size!==0&&To({mode:"project-add",projectIds:[...Ut].sort()})})),Qr()}function Hp(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 UO(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 J_="codemem-settings-advanced",Y_="gpt-5.1-codex-mini",X_="claude-4.5-haiku",qO=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],GO={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"},HO=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),KO={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 VO(){try{return globalThis.localStorage?.getItem(J_)==="1"}catch{return!1}}function zO(e){try{globalThis.localStorage?.setItem(J_,e?"1":"0")}catch{}}function Un(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ee(e,t,n){if(Un(t,n))return t[n];if(Un(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 WO(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function JO(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function YO(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:X_,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Y_,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:X_,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:Y_,source:"Recommended (direct API)"}}function XO(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(!Un(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(!Un(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Un(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 Un(n,t)?n[t]:""}}function QO(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Un(r,i)&&(r[i]=XO(t,i))}),r}function ZO(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Hp(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("claude_command"))throw I;const R=r.claude_command;o=Array.isArray(R)?R.filter(k=>typeof k=="string").map(k=>k.trim()).filter(k=>k.length>0):[]}let s=[];try{s=Hp(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("codex_command"))throw I;const R=r.codex_command;s=Array.isArray(R)?R.filter(k=>typeof k=="string").map(k=>k.trim()).filter(k=>k.length>0):[]}let c=[];try{c=Hp(t.observerAuthCommand,{label:"observer auth command"})}catch(I){if(!i||n.has("observer_auth_command"))throw I;const R=r.observer_auth_command;c=Array.isArray(R)?R.filter(k=>typeof k=="string"):[]}let l={};try{l=UO(t.observerHeaders)}catch(I){if(!i||n.has("observer_headers"))throw I;const R=r.observer_headers;R&&typeof R=="object"&&!Array.isArray(R)&&Object.entries(R).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 eM(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 tM(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=YO(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Un(t,r))?"Env override":n.source}: ${n.model}`}function nM(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 rM(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function iM(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 oM(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 aM(e){return!e}function sM(e,t,n){return t.has(e)||n.has(e)}function cM(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:VO(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...KO}}};function lM(){Z.controller?.hideTooltip()}function Zr(e){if(Z.controller){Z.controller.setRenderState(e);return}Z.renderState={...Z.renderState,...e}}function dM(e){Zr({values:{...Z.renderState.values,...e}})}function uM(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 pM(e){Z.showAdvanced=e,Z.controller?.setShowAdvanced(e)}function Q_(){return Z.open}function fM(e){return sM(e,Z.protectedKeys,HO)}function Z_(e={}){return ZO({values:Z.renderState.values,touchedKeys:Z.touchedKeys,baseline:Z.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function mM(e){Zr({observerStatus:e&&typeof e=="object"?e:null})}function hM(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=eM(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:WO(t.providers),statusText:"No unsaved changes",values:s}),Z.touchedKeys=new Set;try{const c=Z_({allowUntouchedParseErrors:!0});Z.baseline=QO(c,r,i)}catch{Z.baseline={}}Uc(!1)}async function gM(){if(!Z.open)try{const[e,t]=await Promise.all([xS(),AS().catch(()=>null)]);hM(e),mM(t)}catch{}}function Kp(e){return String(e||"").replace(/_/g," ")}function Vp(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 vM(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 yM(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 bM(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function _M({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"," ",vM(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),": ",yM(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 ${bM(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 ew(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 Pa(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function wM(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 SM(){const e=Le("settingsModal");(wM(e)[0]||e)?.focus()}function CM(){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=Pa(u.target);p&&r(p)},s=u=>{const p=Pa(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=Pa(u.target);p&&r(p)},l=u=>{Pa(u.target)&&i()},d=u=>{const p=Pa(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&&ew(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&&ew(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:Pe(()=>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 IM({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}=CM();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,zO(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(Pr,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:g=>{g.preventDefault()},onOpenAutoFocus:g=>{g.preventDefault(),SM()},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 zp({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 RM({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(zp,{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(rr,{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(rr,{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(rr,{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 PM({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(z,{children:[a(zp,{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 kM({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(z,{children:[a(zp,{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 TM({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(Iv,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:qO,triggerClassName:"settings-tab",value:t,children:[a(xr,{className:"settings-panel",forceMount:!0,value:"observer",children:a(RM,{...e,observerStatusBannerSlot:d})}),a(xr,{className:"settings-panel",forceMount:!0,value:"queue",children:a(PM,{...e})}),a(xr,{className:"settings-panel",forceMount:!0,value:"sync",children:a(kM,{...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 NM(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||Un(r,c)&&!i.has(c)||JO(l,n[c])||(s[c]=l)}),s}function EM(e){const t=s=>{const c=GO[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 AM(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=>Kp(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>Kp(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>Kp(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: ${Vp(r)}.`),i.length&&d.push(`Live settings updated: ${Vp(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 ${Vp(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 xM=()=>tM(Z.renderState.values,Z.envOverrides),DM=()=>nM(Z.renderState.values),$M=()=>rM(Z.renderState.values),LM=()=>iM(Z.renderState.values),jM=()=>oM(Z.renderState.values),OM=()=>aM(Z.showAdvanced),{onTextInput:MM,onSelectValueChange:FM,onSwitchInput:BM}=EM({getTouchedKeys:()=>Z.touchedKeys,getValues:()=>Z.renderState.values,updateFormState:dM,setDirty:e=>Uc(e)});function UM(){const e=Z.renderState.observerStatus;return a(_M,{status:e})}function qM(){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:OM,onTextInput:MM,onSelectValueChange:FM,onSwitchInput:BM,getObserverModelLabel:$M,getObserverModelTooltip:LM,getObserverModelDescription:jM,getObserverModelHint:xM,getTieredRoutingHelperText:DM,protectedConfigHelp:cM};return a(TM,{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&&VM(Z.startPolling,Z.refresh)},onActiveTabChange:uM,onAdvancedToggle:pM,observerStatusBannerSlot:a(UM,{})})}function GM(){return a(IM,{DialogContent:qM,onClose:Gc})}function HM(){const e=Le("settingsDialogMount");e&&We(a(GM,{}),e)}function tw(){Le("settingsDialogMount")&&(Z.shellMounted||(HM(),Z.shellMounted=!0))}function KM(e){Z.shellMounted||tw(),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),lM(),(Z.previouslyFocused&&typeof Z.previouslyFocused.focus=="function"?Z.previouslyFocused:Ed("settingsButton"))?.focus(),Z.previouslyFocused=null,Z.touchedKeys=new Set,e(),t()}async function VM(e,t){if(!Z.renderState.isSaving){Zr({isSaving:!0,statusText:"Saving changes…"});try{const n=Z_({allowUntouchedParseErrors:!0}),r=NM({current:n,baseline:Z.baseline,envOverrides:Z.envOverrides,touchedKeys:Z.touchedKeys,isProtected:fM});if(Object.keys(r).length===0){Zr({isSaving:!1,statusText:"No unsaved changes"}),Uc(!1),Gc(e,t);return}const i=await DS(r),o=AM(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 zM(e,t,n){Z.startPolling=t,Z.refresh=n,tw(),Ed("settingsButton")?.addEventListener("click",()=>KM(e))}function WM(e){e.dataset.syncRenderRoot="preact"}function JM(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function ft(e,t){WM(e),We(t,e)}function eo(e){e.dataset.syncRenderRoot==="preact"&&We(null,e)}function YM(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 XM(e){return typeof e=="object"&&e!==null}function QM(e,t){return C.pairingCommandRaw="",{payloadText:e,hintText:t}}function ZM(e){if(!XM(e))return QM("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 e1(){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 t1(){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 n1(){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 r1(){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 i1(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 o1({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 a1({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 nw({text:e}){return a(z,{children:e})}function s1({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function c1(e,t){if(!t.length){eo(e);return}ft(e,a(o1,{items:t}))}function l1(e,t,n){if(!t.length){eo(e);return}ft(e,a(a1,{attempts:t,note:n}))}function ei(e,t){ft(e,a(s1,{...t}))}function rw(e,t,n){ft(e,a(nw,{text:n.payloadText})),t&&ft(t,a(nw,{text:n.hintText}))}function iw({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 d1({open:e,onOpenChange:t}){return a(iw,{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 u1({contentHost:e,open:t,onOpenChange:n}){return a(iw,{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 p1(e,t){ft(e,a(d1,{...t}))}function f1(e,t){ft(e,a(u1,{...t}))}function fe(e){return String(e??"").trim()}function m1(e){return fe(e).replace(/\s+/g," ").toLowerCase()}function h1(e){const t=fe(e);return t?t.slice(0,8):"Unnamed device"}function ow(e){return fe(e?.last_error).toLowerCase()}function aw(e){return e.includes("401")&&e.includes("unauthorized")}function sw(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var g1={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function cw(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 v1(e){const t=cw(e);return!fe(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function lw(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=w1(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=>dw(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=>dw(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 dw(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 y1(n)?"trust":b1(n)?"scope":null}function y1(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function b1(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function _1(e){const t=fe(e?.reason);return g1[t]??(t.replaceAll("_"," ")||"sync filters")}function w1(e){const t=new Map;for(const n of e){const r=_1(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 uw(e){const t=fe(e.localName);if(t)return t;const n=fe(e.coordinatorName);return n||h1(fe(e.deviceId))}function S1(e){const t=fe(e.localName),n=fe(e.coordinatorName);return t||n?!1:!!fe(e.deviceId)}function C1(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=ow(e);return aw(n)?"needs-repair":sw(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=ow(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}:aw(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}:sw(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 I1={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 R1(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:I1[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 pw(e){return Array.isArray(e)?e.map(t=>fe(t)).filter(t=>!!t):[]}function fw(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 P1(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 mw(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 k1=["personal","private","home","mine","me"],T1=["oss","open source","opensource","community","public"],N1=["work","client"],E1=["local","legacy","review"];function A1(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>fe(t)??"").join(" ").toLowerCase()}function x1(e){return[e.scope_id,e.label,e.kind].map(t=>fe(t)??"").join(" ").toLowerCase()}function hw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wp(e,t){const n=A1(e);return t.some(r=>{const i=hw(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function gw(e){return Wp(e,k1)||Wp(e,T1)}function D1(e){const t=x1(e);return E1.some(n=>{const r=hw(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function $1(e){return!gw(e)&&(!D1(e)||Wp(e,N1))}function L1(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(gw),r=t.some($1);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 j1(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function O1(e){const t=pw(e?.effective_include),n=pw(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${fw(t,"all projects")}`,o=`Exclude filter: ${fw(n,"no exclusions")}`,s=j1(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 M1(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=fe(n?.display_name),i=fe(n?.actor_id),o=m1(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 vw(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 F1=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),B1=new Set(["pending","verifying","waiting"]);function U1(e){return(Array.isArray(e?.groups)?e.groups.map(t=>fe(t)).filter(Boolean):[]).join(", ")||"none"}function q1(e){return fe(e?.projects?.[0]?.display_name)||"the shared Project"}function G1(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 H1(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"&&!mw(n).rows.some(r=>r.status==="pending"))}function K1(e){return e.some(t=>fe(t.status?.peer_state)==="online"&&to(t).state==="mutual-trust")}function V1(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 z1(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 yw(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=U1(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&&F1.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&B1.has(f)});if(l||d){const p=l?q1(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(z1(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(G1(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."}:V1(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&&H1(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}:K1(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 W1(e){return e.discovered?.stale?e.peer?Ta(e.peer)!=="connected":!0:!1}function bw(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 Jp(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 J1(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 Y1(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 X1(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 Q1(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=X1(n,r),o=e.duplicatePersonDecisions??{},s=M1(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=uw({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(bw({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(bw({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(Jp({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(Jp({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(Jp({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&&S1({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(J1({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:yw({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=>W1(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var _w={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 ww=!1;function Z1(e){ww=e}var Yp=!1;function eF(e){Yp=e}var Xp=!1;function tF(e){Xp=e}var nF=new Set,Qp=new Set,Zp=new Set,Sw="codemem-sync-duplicate-person-decisions";function rF(e){const t=String(e||"").trim();t&&(Qp.add(t),Zp.add(t),nF.add(t))}function ef(e){const t=String(e||"").trim();return!!t&&Qp.has(t)}function iF(e){const t=String(e||"").trim();t&&Qp.delete(t)}function oF(e){const t=String(e||"").trim();return!t||!Zp.has(t)?!1:(Zp.delete(t),!0)}function tf(){try{const e=localStorage.getItem(Sw);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Cw(e){try{localStorage.setItem(Sw,JSON.stringify(e))}catch{}}function Iw(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function aF(){return tf()}function sF(e,t){const n=Iw(e);if(!n)return;const r=tf();r[n]=t,Cw(r)}function cF(e){const t=Iw(e);if(!t)return;const n=tf();delete n[t],Cw(n)}function Rw(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?Rw(t):""}function lF(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function dF(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 nf(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Kc(e)}function uF(e){return(Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function pF(){return vw({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}).visibleActors}function kw(e){return pF().filter(t=>String(t?.actor_id||"")!==e)}function fF(e,t){const n=kw(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${nf(n)}. Assigned devices move now; existing memories keep their current provenance.`}function rf(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 Tw(e,t){return t&&e.error_redacted===!0}function Nw(){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,n1());return}const r=i1(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?Rw(m):m),Tw(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):"",...Tw(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});l1(e,i,r)}function mF(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&ei(e,t1()),t&&ei(t,r1()),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."),rf(r,[])}function no(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function hF(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 Ew(){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,e1()),rf(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||YM(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),R=v.last_run_at||null,k=String(v.last_error||""),A=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":Uy(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: ${ir(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(R?`Retention last ran ${ir(qi(R))} 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?`${ir(qi(c))} ago`:"never"},{label:"Last peer ping",value:l?`${ir(qi(l))} ago`:"never"},{label:"Retention",value:_?R?`${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:hF(g)}),c1(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"}),rf(n,j)}var gF="syncRedactMount",vF="syncRedactLabel",Aw=()=>{};function yF(e){Aw=e}var of=()=>{};function af(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;f1(e,{contentHost:t,open:C.syncPairingOpen,onOpenChange:r=>{if(sT(r),af(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&rw(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}of()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=C.pairingCommandRaw;r&&await Oo(r,n)})}function sf(){af();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;rw(e,t,ZM(C.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!C.pairingCommandRaw)}function xw(){const e=document.getElementById(gF);e&&ft(e,b(Mi,{"aria-labelledby":vF,checked:Fo(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{cT(t),xw(),of(),Ew(),Aw(),Nw(),sf()},thumbClassName:"sync-redact-switch-thumb"}))}function bF(e){of=e,af(),xw()}function _F(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),_F(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,cf=null,wF={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 SF(e){const t=e instanceof Error?e.message:String(e);return wF[t]??"Setup could not be retried. Review diagnostics for details."}function CF(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 IF(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function lf(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 RF({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(()=>{cf!==e.operation_id||!d.current||(cf=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),cf=e.operation_id,l(h),await r()}catch(g){const h={message:SF(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":`${lf(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:lf(e.lifecycle.state)}),a("ul",{"aria-label":`${lf(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 PF({operations:e,...t}){const n=e[0].person,r=IF(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(RF,{operation:i,...t},i.operation_id))]})}function kF(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:CF(e.operations).map(t=>a(PF,{...e,operations:t},t[0].person.actor_id))})}function TF(e,t){ft(e,a(kF,{...t}))}function Dw({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 NF(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 EF({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Kc(e),c=uF(o),l=kw(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,R]=x(""),[k,A]=x(!1);K(()=>{p(s),m(!1),g("Rename"),y(!1),_("Merge into selected person"),R(""),A(!1)},[o,c,t,s,d]);const L=l.length?fF(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?nf(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:nf(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?NF(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(rr,{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:R,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 AF({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(EF,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(Dw,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function xF(e,t){ft(e,a(AF,{...t}))}function DF(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function $F(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 LF({devices:e}){return a(z,{children:$F(e)})}function jF(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 OF(e){const t=DF(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),eo(e.mount),eo(e.meta);return}const n=t.map(jF),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(rr,{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(LF,{devices:t}))}var MF={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function FF({state:e,size:t=8,"aria-label":n}){const r=n??MF[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 BF(){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 UF(e){switch(Ta(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Vc=null,$w=0,df=new Set;function Lw(e){if(Vc!==e){Vc=e,$w+=1;for(const t of df)t($w)}}function qF(){const[,e]=x(0);return K(()=>(df.add(e),()=>{df.delete(e)}),[]),Vc}var GF={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 jw(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 HF(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: ${jw(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: ${jw(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 KF(e){C.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function VF(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 zF(){window.location.hash="advanced/teams"}function uf(e=C.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function WF({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=GF[C1(e)],d=e.status||{},u=P1(e),p=ef(i),f=p&&u.total===0,m=L1(e),v=R1(e),g=mw(e),h=e.project_scope||{},y=O1(h),w=lF(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(re=>String(re)))):[],I=Number(e.address_count??0),R=Number.isFinite(I)&&I>0?I:0,k=_.length?_.map(re=>Fo()?Pw(re):re).join(" · "):R>0?`${R} ${R===1?"address":"addresses"} hidden`:"No addresses",A=C.lastDeviceIdentityInventory?.items.find(re=>re.deviceId===i||re.evidenceDeviceIds.includes(i)),L=HF(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=oF(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&&iF(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=uf();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=qF()===i&&i!=="",ge=`device-drawer-${i||"unknown"}`,pe=UF(e),He=F?`Sync: ${qr(F)}`:"Sync: never",de=uf(),W=`${ce?"Collapse":"Expand"} device ${o}`;return a(qo,{asChild:!0,open:ce,onOpenChange:re=>{re?Lw(i):Vc===i&&Lw(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(FF,{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(BF,{})})]})}),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:VF(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>KF(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:zF,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 JF(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(WF,{peer:i,...e},o)})]}):a(z,{children:[a(ni,{feedback:t}),a(Dw,{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 YF(e,t){ft(e,a(JF,{...t}))}var pr=async()=>{},zc="";function pf(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function XF(e){pr=e}function QF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;ur("syncActorsSkeleton"),pf(!1);const n=vw({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.`)),xF(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await JC(i,o),await pr()},onMerge:async(i,o)=>{try{await um(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 YC(i),Q("Person removed. Assigned devices have been unassigned."),await pr()}catch(o){throw Q(bt(o,"Failed to remove person."),"warning"),o}}})}function ZF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");pf(!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 eB(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;TF(e,{operations:C.lastShareOperations,onAdvance:n=>FC(n),onLoadOperation:n=>MC(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 ff(){const e=document.getElementById("syncPeers");if(!e)return;ur("syncPeersSkeleton");const t=C.lastSyncPeers,n=Array.isArray(t)?t:[];dF(C.syncPeersSectionFeedback,n)&&(C.syncPeersSectionFeedback=null),YF(e,{peers:n,onRename:async(r,i)=>{try{return await Xf(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=lw(s);let l;c.ok?o&&ef(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${uf()?"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 Yf(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 tB(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");pf(!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 Ow(){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:[];OF({devices:r,meta:n,mount:t,onValueChange:i=>{i!==zc&&(zc=i,Ow())},panel:e,value:zc})}function nB(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 WC(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 XC(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 rB(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function mf(e=rB()){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 Mw=!1;function iB(){Mw||(Mw=!0,window.addEventListener("hashchange",()=>{mf()}))}var hn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function oB(e){hn.loadSyncData=e}var aB=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function sB(){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 hf(){const e=document.getElementById("syncAdminDisclosureMount");e&&p1(e,{open:ww,onOpenChange:t=>{Z1(t),hf(),Jc(),gf()}})}function cB(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function gf(){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(rr,{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:aB,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:hn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function lB(e,t){hf(),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 R=await Jf(_);if(I!==y||d?.value.trim()!==_)return"stale";if(h=R.kind,R.kind!=="project_share_invite")return"other";const k=(R.projects??[]).map(A=>`${A.display_name} (${A.existing_memory_count} existing ${A.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${R.inviter_name||"A teammate"} invited you${R.team_name?` through ${R.team_name}`:""} to share ${k||"selected projects"}.`),m.value=Ci(R.recipient_name),v.value=Ci(R.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 R=!0;if(_?Na(o):R=ro(o,"Team name is required."),!I||I<1?R=ro(s,"Must be at least 1 hour."):Na(s),!!R){i.disabled=!0,i.textContent="Creating…";try{const k=await Kf({group_id:_,policy:hn.invitePolicy,ttl_hours:I||24});C.lastTeamInvite=k,gf(),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 R=y;try{const k=await w(_,R);if(k==="project"||k==="stale")return}catch{}if(R!==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 R=k=>Ci(k)==="";if(R(I.recipient_name)){m&&ro(m,"Enter a human-readable name using 120 characters or fewer.");return}if(R(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 R=await pl(_,I,h);C.lastTeamJoin=R;const k=R,A=typeof k.type=="string"?k.type:"team_join";let L;if(A==="pair"){const F=String(R.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"||R.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:R.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(R){C.syncJoinFlowFeedback={message:bt(R,"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=lw(_);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 vf({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 dB({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(vf,{element:e,hidden:!t,restoreParent:n}):null]})}function uB(){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 pB({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(vf,{element:e,hidden:!t,restoreParent:n}):null]})}function fB({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(vf,{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(pB,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(dB,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(uB,{}):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 mB({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 hB({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 gB({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 vB(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(mB,{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 yB({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 bB({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(gB,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function _B({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(hB,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function Fw(e){return a(z,{children:[a(vB,{...e}),a(yB,{children:e.children}),a(_B,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(bB,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function Bw(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 wB(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ea(){return wB()?"auto":"smooth"}var yf="syncTeamActionsMount",SB="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function CB(e,t,n=!1){return e.length>1&&(!t||n)}function IB(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 RB(e,t){const n=document.createElement("div");n.id=yf,e.appendChild(n),ft(n,b(Fw,{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 Uw(e,t){const n=document.getElementById(yf);n&&(eo(n),n.remove()),Bw(e),t.forEach(r=>{Bw(r)})}function Aa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;hf(),Jc(),gf(),Wc(),sB();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"),cB();const p=C.lastSyncCoordinator,f=C.lastSyncViewModel||{primaryStatus:yw({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 gx({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"){sF(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 um(String(G.actor_id),String(oe.actor_id)),cF(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=Y1(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?IB(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!h){Uw(n,[c,u]),t.hidden=!1,n.hidden=!1,RB(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:[],R=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=uw({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=CB(ee,!!ie,E.needs_local_approval===!0),Ie=cw({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&&v1({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 Re=null,re=ge?"accept":"none",je=null;return le?re="conflict":Y?(Re="Waiting for refreshed coordinator status. You do not need to approve again.",re="approval-pending"):y&&(!ie||Ie.state==="needs-your-approval")?(Re=y.message,re="setup-blocked"):Ce?(Re="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",re="ambiguous"):ie&&ef(S)?(Re="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?(Re="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:Re,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?_w.conflicts:ie?_w.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=R.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),Uw(n,[c,u]);const $=document.createElement("div");$.id=yf,n.appendChild($),ft($,b(Fw,{actionItems:T,actionableCount:U,children:b(fB,{invitePanel:r,invitePanelOpen:Yp,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:Xp,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(eF(!Yp),Aa())},onToggleJoinPanel:()=>{o&&(tF(!Xp),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 Yf(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 PB(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 PB(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 lC(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."}],rF(e.deviceId);let u=n?{message:SB,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 Xf(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 kB(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 qw(e){return io(e)?"Unclear project identity":e.displayProject}function qt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function TB(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function NB(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function EB(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function AB(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function xB(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 DB(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function $B({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"," · ",xB(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:DB(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 Gw(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${NB(t)}\\b`,"g"),EB(t,n))),r}function LB(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 jB({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 OB({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,R=e.totalGroupCount??I,k=r.filter(io).length,A=r.filter(S=>S.suggestedScopeId&&!io(S)&&qt(S)).length,L=r.filter(S=>f[S.workspaceIdentity]&&qt(S)).length,F=r.filter(S=>f[S.workspaceIdentity]&&qt(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()||LB(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]:Gw(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(qt).map(H=>[H.workspaceIdentity,S]))}))}function $(){m(S=>({...S,...Object.fromEntries(r.filter(D=>D.suggestedScopeId&&!io(D)&&qt(D)).map(D=>[D.workspaceIdentity,!0]))}))}async function E(){if(!t||w||F===0)return;const S=r.filter(D=>f[D.workspaceIdentity]&&qt(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]:Gw(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:[R.toLocaleString()," older"," ",R===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",I<R?` 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]&&qt(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]&&qt(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 ${qw(S)}`,checked:!!f[S.workspaceIdentity],className:"cm-checkbox",disabled:!qt(S),onChange:D=>B(S,D.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:qw(S)}),a("div",{className:"legacy-review-group-meta",children:[kB(S.identitySource),TB(S,i)]}),qt(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($B,{group:S}),i.length>0&&t&&qt(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," · ",AB(D.authorityType),D.scopeId===S.suggestedScopeId?" · suggested":""]},D.scopeId))]})]}):null,i.length>0&&t&&qt(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 MB({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(z,{children:[t?a(OB,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(jB,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function FB(){uv("mine"),C.feedQuery="",window.location.hash="feed"}function BB(){window.location.hash="projects"}async function UB(e,t,n,r){try{const i=await KC({...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}.`),Hw(),null}catch(i){if(i instanceof Zf)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Q(o,"warning"),new Error(o)}}function Hw(){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(MB,{items:d,legacyReview:c,onLegacyReassign:UB,onLegacyReview:BB,onReview:FB}))}var Zc="";function qB(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 GB(){return[...C.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var xa=null,bf=0,HB=15e3;function Kw(e){return`project:${e||""}|includeJoinRequests:false`}function KB(e){const t=Kw(e);return!xa||xa.key!==t||Date.now()>=xa.expiresAtMs?null:xa.payload}function VB(e,t){xa={key:Kw(e),expiresAtMs:Date.now()+HB,payload:t}}function zB(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function WB(){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=++bf;try{const t=C.currentProject||"",n=!1,r=C.activeTab==="health";let i=!1;const o=!Fo();let s;r?(s=KB(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=aF();try{c=await sC()}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 R=await dm();u=Array.isArray(R.items)?R.items:[]}catch{v=!0}if(e!==bf)return;i&&VB(t,zB(s)),qB(s.coordinator);const h=JSON.stringify([s,c,l,d,m,u,v,g,GB()]);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(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),I=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(R=>{const k=String(R?.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=Q1({actors:C.lastSyncActors,peers:C.lastSyncPeers,coordinator:C.lastSyncCoordinator,status:y,shareOperations:C.lastShareOperations,shareOperationsLoadError:v,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:C.lastSyncDuplicatePersonDecisions}),Ew(),Aa(),QF(),eB(),Hw(),ff(),Ow(),Nw(),u_(),p&&ZF(),f&&(C.lastSyncCoordinatorAdminStatus=null,Aa())}catch{if(e!==bf)return;Zc="",C.deviceIdentityInventoryLoadError=!0,ur("syncTeamSkeleton"),ur("syncActorsSkeleton"),ur("syncPeersSkeleton"),ur("syncDiagSkeleton"),WB(),tB(),mF()}}function JB(){Zc="",C.lastSyncPeers?.length&&ff()}async function YB(){try{const e=await cC();C.pairingPayloadRaw=e||null,sf()}catch{C.pairingPayloadRaw=null,sf()}}function XB(e){JM(),ic(),oB(oo),XF(oo),yF(ff),lB(e,oo),nB(oo),bF(e),mf(),iB()}function QB(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 ZB(){try{const e=await ZS();if(!e?.version)return;QB(e.version,"261c109")}catch{}}var _f=null,Vw=1500,zw="codemem-legacy-upgrade-notice-dismissed",fr=null,gn=!1,wf=!1,Da=null;function Ww(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function Jw(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=Ww(n.total_group_count,r.length),o=Ww(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function Yw(){try{return localStorage.getItem(zw)==="1"}catch{return!1}}function el(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(zw,"1")}catch{}}function Xw(){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 eU(){const e=Xw(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function Qw(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=Xw();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 Zw(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",Qw),eU(),Zw(!0);return}Zw(!1),document.removeEventListener("keydown",Qw),Da&&document.contains(Da)&&Da.focus(),Da=null}}function eS(e){!e||wf||Yw()||(wf=!0,$a(!0,e))}async function tU(){if(!(wf||Yw()))try{eS(Jw(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 Sf(){try{return await QS(),!0}catch{return!1}}function nU(){return document.visibilityState!=="hidden"&&!Q_()}function tS(){if(gn)return;gn=!0,Cf(),ii("error","(reconnecting)"),ri(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Sf()){if(fr&&(clearTimeout(fr),fr=null),gn=!1,ri(!0,"Viewer responded. Restoring your session…"),nU()){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,Vw)};fr=setTimeout(e,Vw)}function ii(e,t){C.refreshState=e;const n=Le("refreshStatus");if(!n)return;const r=o=>{const s=Le("refreshAnnouncer");!s||_f===e||(s.textContent=o,_f=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}`,_f=null}function Cf(){C.refreshTimer&&(clearInterval(C.refreshTimer),C.refreshTimer=null)}function La(){C.refreshTimer||(C.refreshTimer=setInterval(()=>mr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Cf(),ii("paused","(tab hidden)")):!Q_()&&!gn&&(La(),mr())});function nS(){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(/^#/,"");mf(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}function rS(e){const t=new Set(eT(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")}),nS()}function oi(e,t={}){const n=Mo(e,C.lastCoordinatorAdminStatus);n==="advanced"&&$d(t.advancedSection??Dd()??C.advancedSection),dv(n,t.canonicalHash?{canonicalHash:!0}:{}),rS(n),mr()}function rU(){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),nS(),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 iU(){try{const e=await Fa();C.knownProjects=e,JB();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 oU(e){C.pendingDeviceIdentityFocus=e?.trim()||null,oi("devices",{canonicalHash:!0})}var ja=ZP({},{onOpenTeamSetup:k_,onReviewDevices:oU}),iS={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},If=0,Rf=null,Gt=null;async function aU(){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 sU(){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 cU(){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 oS(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=lU(e,++If);return Rf=t,t}async function lU(e,t){Gt||dc(e,iS,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,o]=await Promise.all([aU(),gl(),NC(),vl().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:Gt?.inventory,unavailable:!0})),oo()]);if(t!==If)return Rf??!1;const s=sU(),c=cU(),l=pm(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:oS,peerRuntimeMetadata:c}),Gt={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==If?Rf??!1:(Gt?dc(e,Gt.intent,Gt.reconciliation,Gt.projects,Gt.availability,{coordinatorEnrollmentIssueCount:Gt.coordinatorEnrollmentIssueCount,inventory:Gt.inventory,inventoryUnavailable:Gt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Pf(),ja()]);return n&&r},onNavigate:oS,peerRuntimeMetadata:Gt.peerRuntimeMetadata,refreshError:!0}):dc(e,iS,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Nd("projectFilter")?.addEventListener("change",()=>{C.currentProject=Nd("projectFilter")?.value||"",Jr(!0),mr()});var kf=null;async function mr(){gn||(kf&&clearTimeout(kf),kf=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=[rj(),gM()];let n=!0;if(e==="feed"){const i=zx();t.push(Ly(i))}e==="feed"&&t.push(Cp()),e==="projects"&&t.push(Ra()),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(YB()),await Promise.all(t),eS(Jw(C.lastSyncLegacySharedReview));const r=Mo(C.activeTab,C.lastCoordinatorAdminStatus);r!==C.activeTab&&dv(r),rS(C.activeTab),ii(n?"idle":"error")}catch{await Sf()?ii("error"):tS()}finally{C.refreshInFlight=!1,C.refreshQueued&&!gn&&(C.refreshQueued=!1,tl())}}}lT();var aS=document.getElementById("toastRoot");aS&&Hk(aS);var sS=document.getElementById("legacyTeamSetupMount");sS&&Zj(sS,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(C.activeTab==="sharing"?(t=await Ra(n),e=await ja(n)):(e=await ja(n),t=await Ra(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),dT(Ed("themeToggle")),mv(jd()),rU(),GL(),BO(()=>mr(),{onOpenTeamSetup:k_}),XB(()=>mr()),e0(),zM(Cf,La,()=>mr()),iU(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(ri(!0,"Checking whether the viewer server is back…"),!await Sf()){tS();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)}),ZB(),tU(),mr(),La()})();
|
|
111
|
+
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",h=[{label:d?"Savings (project)":"Savings",value:Wi(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:Wi(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:up(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${sL(u.tokens_saved,u.tokens_read)}.`+v+g,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Wi(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:_b(o.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:_b(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"}),U_(e,h),t){const b=s?` · project: ${s}`:"",w=pL(o.path||"unknown");G_(t,`DB: ${w} · ${fL(o.size_bytes||0)}${b}`)}Mc()}async function iM(){const e=C.lastStatsPayload?.identity?.actor_id||null,t=C.activeTab==="health"&&!C.lastUpdateStatus?BR().catch(qR):Promise.resolve(C.lastUpdateStatus),[n,r,i,o,s]=await Promise.all([UC(),GC(C.currentProject),HC(C.currentProject),VC(C.currentProject),t]);C.lastStatsPayload=n||{},C.lastUsagePayload=r||{},C.lastRawEventsPayload=o||{},C.lastUpdateStatus=s;const c=C.lastStatsPayload?.identity?.actor_id||null;rM(),Kj(document.getElementById("automaticRecallStats"),C.lastStatsPayload.automatic_recall),nM(),V_(),C.activeTab==="feed"&&e!==c&&Qr(!0)}function Wp(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function K_(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function z_(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var oM={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function W_(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function aM(e){return e.targetIdentityRef??e.existingIdentityRef??""}function sM({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Ir(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,v=aM(o),g=o.targetIdentityRef??"",[h,b]=x(v);V(()=>b(v),[v]);const w=i.identityChoices.some(M=>M.identityRef===h),_=W_(i,o.existingIdentityRef),R=W_(i,o.suggestedIdentityRef),I=n?.has(o.deviceRef)??!1,T=e||I||r,A=T||!o.actions.assignIdentity.enabled,O=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!h&&!w,N=!o.actions.include.enabled||O||F||!g||h!==g,L=T||N,D=A||!h||O||F||h===g,G=!o.enabled||N,q=e?t:I?Wp("device",o.deviceRef):void 0,$=[f,G?m:void 0,q].filter(Boolean).join(" "),E=[f,q].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,!_&&R?a("span",{children:["Suggested person: ",R]}):null,a("span",{children:["Decision: ",oM[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:M=>b(M.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(M=>a("option",{value:M.identityRef,children:M.displayName},M.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."}):O?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":D?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{D||c(o,h)},type:"button",children:"Save assignment"}),o.enabled?a(z,{children:[a("button",{"aria-describedby":$,"aria-disabled":L?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{L||d(o,"included",g)},type:"button",children:"Include"}),a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":E,"aria-disabled":T||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function cM(e){const t=K_(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)=>y(sM,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function lM(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function dM({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=Ir(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=Nr(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,$])),b=m.flatMap($=>{const E=h.get($);return E?[{...E,label:f.get($)??E.displayName,token:g.get($)??""}]:[]}),w=b.find($=>$.resolvedProjectRef===p)?.token??"",_=JSON.stringify(v),[R,I]=x(w);V(()=>I(w),[w,_]);const T=b.find($=>$.token===R)?.resolvedProjectRef,A=n?.has(c.projectRef)??!1,O=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!R,N=e||A||r||!c.actions.map.enabled,L=N||!T||T===p,D=lM(c,f),G=[O||F?u:void 0,e?t:A?Wp("project",c.projectRef):void 0].filter(Boolean).join(" "),q=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${q?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:q?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[q?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:D?`Saved mapping: ${D}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a("select",{"aria-describedby":G||void 0,className:"feed-search legacy-team-project-select",disabled:N,id:d,onChange:$=>I($.currentTarget.value),value:R,children:[a("option",{value:"",children:"Choose a Project"}),b.map($=>a("option",{value:$.token,children:$.label},$.resolvedProjectRef))]}),O?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":G||void 0,"aria-disabled":L?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!L&&T&&o(c,T)},type:"button",children:"Save mapping"})]})]})]})}function uM(e){const t=z_(e.detail.projects),n=Nr(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(dM,{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 _a={add:"Add",update:"Update",remove:"Remove"},pM=10;function ft(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Jp(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${No(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 Yp(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${ft(e.projectRefs.size,t)}`:e.displayName}function wa({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>pM;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 ",ft(n.length,`exact ${t}`)]}),a(J_,{items:n,title:i})]}):a(J_,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function J_({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 fM({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 M=S.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":S.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${_a[S.change]} ${S.teamDisplayName}: change device access from ${M} to the reviewed device list.`}),m=o.membershipChanges.map(S=>`${_a[S.change]} ${S.identityDisplayName} ${S.change==="remove"?"from":"to"} ${S.teamDisplayName}.`),v=Nr([...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=Nr(g.map(S=>({canonicalId:S.canonicalProjectRef??S.resolvedProjectRef,displayName:S.displayName}))),b=new Map(g.map(S=>[S.resolvedProjectRef,h.get(S.canonicalProjectRef??S.resolvedProjectRef)??S.displayName])),w=Nr([...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=>`${_a[S.change]} ${v.get(S.projectRef)??S.projectDisplayName}: ${S.fromResolvedProjectRef?b.get(S.fromResolvedProjectRef)??S.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${S.toResolvedProjectRef?b.get(S.toResolvedProjectRef)??S.toResolvedProjectDisplayName??"no Project":"no Project"}.`),R=o.recipientChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.change==="remove"?"Stop":"Start"} using legacy default sharing for ${S.recipientDisplayName}.`:`${_a[S.change]} ${S.recipientDisplayName} ${S.change==="remove"?"from":"as"} a recipient for ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),I=o.deviceAccessChanges.map(S=>S.canonicalProjectKind==="legacy_default_sharing"?`${S.deviceDisplayName} ${S.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${_a[S.change]} ${S.deviceDisplayName} access ${S.change==="remove"?"from":"to"} ${w.get(S.canonicalProjectRef)??S.canonicalProjectDisplayName}.`),T=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,A=Jp(o.projectChanges,S=>S.projectDisplayName,S=>S.projectRef,()=>"project"),O=Jp(o.recipientChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),F=Jp(o.deviceAccessChanges,S=>S.canonicalProjectDisplayName,S=>S.canonicalProjectRef,S=>S.canonicalProjectKind),N=n.devices.filter(S=>S.decision==="included").length,L=[ft(o.teamChanges.length,"Team policy change"),ft(o.membershipChanges.length,"membership change"),ft(o.projectChanges.length,"Project change"),ft(o.recipientChanges.length,"recipient change"),ft(o.deviceAccessChanges.length,"device-access change")],D=`${ft(n.projects.length,"Project")} included; ${ft(N,"included device")}.`,G=Math.max(n.candidate.projectCount,n.projects.length),q=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}.${q>0?` ${ft(q,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${ft(G,"reviewed Project")}.`:`${ft(T,"server-confirmed access change")} will be applied atomically; ${ft($,"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:ft(T,"exact access change")})," to review."]}),a("ul",{children:L.map(S=>a("li",{children:S},S))}),a("p",{className:"small",children:["Scope: ",D]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(wa,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),a(wa,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(wa,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:_,summaryItems:A.map(S=>`${Yp(S,"reviewed Project")}, ${ft(S.changeCount,"Project change")}`),title:"Projects"}),a(wa,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:R,summaryItems:O.map(S=>`${Yp(S,"canonical Project")}, ${ft(S.changeCount,"recipient change")}`),title:"Recipients"}),a(wa,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:I,summaryItems:F.map(S=>`${Yp(S,"canonical Project")}, ${ft(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 mM(e){let t=null;return async n=>{try{const r=await hM(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 gM(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 hM(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 gM(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof wt)||!Xp(n.errorCode))&&!(e.kind==="load"&&(e.refresh||e.completionOnly||n.errorCode!=="team_setup_confirmation_stale")))return t.loadDetail(e.candidateRef)}function Xp(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function Y_(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function vM(e,t,n){return Q_(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function X_(e,t){return Q_(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function Q_(e,t){return{id:e,targetId:t}}var Z_="Team setup changed since it was last reviewed. Reload the latest details to continue.",ew="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",yM="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",bM="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",_M="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",tw="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",wM="Another device completed this Team with different reviewed details. Retry to load the completed setup.",SM="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function CM(){return{status:"closed",generation:0}}function Qp(e,t){switch(t.type){case"open":return e.status==="open"&&Un(e)?e:RM(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Un(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 IM(e,t.step);case"blocked_navigation":return Fc(e,t.step,t.message);case"retry":return kM(e);case"refresh":return PM(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Zp(e,t,"assign_device");case"decide_device":return Zp(e,t,"decide_device");case"clear_device":return Zp(e,t,"clear_device");case"map_project":return TM(e,t);case"finish":return NM(e);case"command_started":return GM(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return EM(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function RM(e,t){return ur({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 IM(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return Fc(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return Fc(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return Fc(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:Y_(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function Fc(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?K_(e.view.devices).findIndex(i=>i.decision==="unresolved"):z_(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:vM(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function kM(e){if(e.status!=="open"||e.step==="completed"||Sa(e)||Un(e))return e;const t=Bc(e)?.retry??e.errors.find(n=>n.retry)?.retry??"load";return ur(e,{kind:"load",candidateRef:e.candidateRef,refresh:t==="refresh",completionOnly:t==="completion",focusOnOutcome:!0})}function Zp(e,t,n){if(e.status!=="open"||e.step==="completed"||!ef(e.view)||Bc(e)||Sa(e)||Un(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 ur(Zr(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function TM(e,t){if(e.status!=="open"||e.step==="completed"||!ef(e.view)||Bc(e)||Sa(e)||Un(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:ur(Zr(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 PM(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Sa(e)||Un(e)?e:ur(Zr(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function NM(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:ur(Zr(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 ur(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 EM(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 n.kind==="load"&&n.completionOnly&&t.status==="success"&&t.view?.state!=="completed"?nw(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new wt(409,"team_setup_confirmation_stale")}):t.status==="failure"?nw(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?xM(r,n.attemptId):t.view?rw({...UM(r,n),message:AM(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function AM(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 nw(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?rw(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=DM(t,n.cause,n.recoveryCause),o={...r,errors:[...Zr(r,i.scope).errors,i],message:""};return t.kind!=="load"||!t.focusOnOutcome?o:{...o,focus:X_(o.nextFocusId,{hasError:!0,recovery:o.view?.state==="unavailable",step:o.step}),nextFocusId:o.nextFocusId+1}}function rw(e,t,n){const r=BM(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:qM(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:X_(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!sw(s,t.attemptId)&&(s=ur(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function xM(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:Y_(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return sw(n,t)||(n=ur(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function DM(e,t,n){const r=t instanceof wt&&Xp(t.errorCode),i=t instanceof wt&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=jM({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i});return{scope:LM(e,{globalError:r||i||o!==null}),message:s,retry:$M(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null})}}function LM(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 $M(e,t,n,r){return t instanceof wt&&t.errorCode==="team_setup_confirmation_stale"||n instanceof wt&&n.errorCode==="team_setup_confirmation_stale"?e.kind==="load"&&e.refresh?"completion":"refresh":e.kind==="load"&&e.completionOnly?OM(t):r.terminalRecovery?"load":r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load"}function OM(e){return e instanceof wt&&qc(e.errorCode)!==null?"completion":"refresh"}function jM(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof wt?qc(n.errorCode):null,c=FM(r instanceof wt?qc(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?MM(n):ow(l);if(c)return{completionCode:l,message:d??iw(t.kind),terminalRecoveryCode:c};if(i)return{completionCode:l,message:Z_,terminalRecoveryCode:c};if(o){let u=ew;return t.kind==="finish"&&(u=n instanceof wt&&n.reason==="local_candidate_scan_budget_exceeded"?bM:yM),{completionCode:l,message:u,terminalRecoveryCode:c}}return{completionCode:l,message:d??iw(t.kind),terminalRecoveryCode:c}}function MM(e){return e instanceof wt&&e.reason==="coordinator_route_missing"?`${tw} The coordinator may be running an older version.`:tw}function FM(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function iw(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 BM(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function ef(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Un(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 Sa(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function Bc(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function qM(e){if(Xp(e))return Z_;if(e==="team_setup_roster_unavailable")return ew;const t=ow(qc(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 qc(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function ow(e){return e==="team_setup_completion_unavailable"?_M:e==="team_setup_completion_conflict"?wM:e==="team_setup_completion_invalid"?SM:null}function aw(e){return e.kind==="global"||e.kind==="load"}function Zr(e,t){const n=aw(t);return{...e,errors:e.errors.filter(r=>n?!aw(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function UM(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?Zr(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?Zr(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function GM(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function sw(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var HM={role:"list"},VM={role:"listitem"};function KM(e){const t=e.session,n=t.view,r=Bc(t),i=t.commands.some(_=>_.kind==="load"),o=Sa(t)||Un(t),s=t.commands.some(_=>_.kind==="finish"),c=n?.state==="unavailable"||r?.retry==="refresh",l=r!=null&&(!n||c),d=!ef(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]:[])),b=new Set(t.commands.flatMap(_=>"deviceRef"in _?[_.deviceRef]:[])),w=new Set(t.commands.flatMap(_=>"projectRef"in _?[_.projectRef]:[]));return a(Qn,{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(Dg,{children:p})}),a(kr,{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?Wp(_.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(zM,{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(cM,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:g,busyDeviceRefs:b,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(uM,{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(fM,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(WM,{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 zM(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(z,{children:[a("ol",{...HM,"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 y("li",{...VM,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 WM(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 JM={clearDecision:fR,finish:gR,loadDetail:dR,onCompleted:()=>{},refreshCandidate:hR,saveAssignment:uR,saveDecision:pR,saveProjectMapping:mR},tf="codemem:open-legacy-team-setup";function cw(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(tf,{detail:t})),t.handled}function YM(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 XM({dependencies:e}){const[t,n]=x(CM),r=B(null),i=ke(()=>mM(e),[e]),o=l=>{n(d=>Qp(d,l))};return It(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Un(p)?Qp(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Qp(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(tf,l),()=>{window.removeEventListener(tf,l)}},[]),V(()=>{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]),V(()=>{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(KM,{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(Un(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=>ZM(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:QM,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var QM=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function ZM(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(YM(t.current)?t.current:n)?.focus(),t.current=null}function e1(e,t={}){const n={...JM,...t};Ue(a(XM,{dependencies:n}),e)}var Ca=new WeakMap;function pr(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function lw(e,t){const n=document.createElement("h3");return n.className="recipient-policy-review-heading",n.textContent=`${e} (${t.toLocaleString()})`,n}function t1(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-review-item";const n=document.createElement("h4");return n.className="project-inventory-title",n.textContent=e.finding,t.append(n,pr(e.reason,"project-inventory-meta")),t}function n1(e){const t=document.createElement("section");t.className="recipient-policy-review-section recipient-policy-review-decisions",t.append(lw("Review findings",e.reviewItems.length),pr("Access has not changed. These findings are informational because this view has no decision controls. You may use the existing sharing controls below to change access, but those changes do not record a review decision.","section-meta"));const n=document.createElement("div");n.className="project-inventory-list recipient-policy-review-list";for(const r of e.reviewItems)n.appendChild(t1(r));return t.appendChild(n),t}function r1(e,t){const n=document.createElement("section");n.className="recipient-policy-review-section recipient-policy-review-blocked",n.append(lw("Blocked source repairs",e.blockedItems.length),pr("Access has not changed. Action is required before Codemem can safely interpret these records. Next step: repair each source record below.","section-meta project-attention-note"));const r=document.createElement("div");r.className="project-inventory-list recipient-policy-review-list";for(const i of e.blockedItems)r.appendChild(i1(i,t));return n.appendChild(r),n}function i1(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=pr(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,pr(e.reason,"project-inventory-meta"),s,pr(`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(pr("Open Projects to repair this item.","settings-note"));return n}function o1(e,t,n={}){const r=t.blockedItems.map(l=>n.onRepair&&(n.isRepairAvailable?.(l.repair)??!0)?"1":"0"),i={blockedItems:t.blockedItems.map(l=>({blockedItemId:l.blockedItemId,finding:l.finding,ownerLabel:l.ownerLabel,reason:l.reason,repair:l.repair,repairAction:l.repairAction})),reviewItems:t.reviewItems.map(l=>({finding:l.finding,reason:l.reason}))},o=`review:${r.join("")}:${JSON.stringify(i)}`;if(Ca.get(e)===o)return;if(t.reviewItems.length===0&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,Ca.set(e,o);return}e.hidden=!1;const s=document.createElement("section");s.className="card recipient-policy-review",s.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const c=document.createElement("h2");c.id="recipientPolicyReviewTitle",c.textContent="Sharing review",s.appendChild(c),t.reviewItems.length>0&&s.appendChild(n1(t)),t.blockedItems.length>0&&s.appendChild(r1(t,n)),e.replaceChildren(s),Ca.set(e,o)}function a1(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(Ca.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=pr(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(o,s),e.replaceChildren(i),Ca.set(e,r)}var dw=[["","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"]],bt=null,Ut=0,Uc=250,s1=100,nf=[],Gc=new Set,Hc=new Set,Vc=new Map,Kc=new Map,ei=new Map,Ra=new Map,zc=!1,Ia=new Map,ka=!1,fr=!1,ro=0,uw=null,Gn=0,Ta=0,io=null,Pa=null,Gt=new Set,pw=new WeakMap,Wc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},oo=Wc,mr=!1,rf;function of(e=!1){if(!e&&Pa)return Pa;const t=Tm().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return Pa=t,t.then(()=>{Pa===t&&(Pa=null)}),t}function $e(e){return document.getElementById(e)}function c1(e){return dw.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function l1(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 vn(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Jc(e){return e.identity_source!=="unmapped"&&!vn(e)}function d1(e){const t=Ia.get(e.workspace_identity);(!t||vn(t)&&!vn(e))&&Ia.set(e.workspace_identity,e)}function af(e){return vn(e)?"Received from peers":Xc(e.resolved_scope_id)}function u1(e){return vn(e)?"source-owned project":l1(e.resolution_reason)}function p1(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 fw(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function mw(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function ti(){const e=Gt.size,t=$e("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!fr||!mr,t.classList.add("project-selection-target"));const n=$e("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=pw.get(r)??[],o=i.filter(s=>Gt.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=!fr||!mr}function f1(e){const t=e.every(n=>Gt.has(n));for(const n of e)t?Gt.delete(n):Gt.add(n);ti()}function hw(e,t){const n=mw(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),pw.set(i,n),i.addEventListener("change",()=>f1(n));const o=document.createElement("span");return o.className="sr-only",o.textContent=t,r.append(i,o),r}function m1(e){if(!mr)return[];const t=new Set(e),n=new Map(oo.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(oo.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of oo.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 gw(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=m1(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=mr?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 vw(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!fr||!mr,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{xo({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)Gt.add(r);ti(),xo({mode:"project-add",projectIds:[...e].sort()})})),n}function h1(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function sf(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function cf(e){return e.project||e.display_project||"Unnamed Project"}function yw(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 g1(){return new Set(C.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function v1(e){return!ka||e.authority_type!=="coordinator"||!e.group_id?!1:!g1().has(String(e.group_id).trim())}function Yc(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function bw(){zc&&(zc=!1,bt?.())}async function y1(){let e;try{const t=await Rl();e=t&&typeof t=="object"?t:null}catch{C.lastProjectCoordinatorAdminGroups=[],ka=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){C.lastProjectCoordinatorAdminGroups=[],ka=!1;return}try{const t=await pm(!1);C.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],ka=!0}catch{C.lastProjectCoordinatorAdminGroups=[],ka=!1}}function b1(e){return e.kind==="team_default"}function lf(e){const t=e.label||"Untitled Space";return b1(e)?`${t} (default)`:t}function _1(e,t){const n=lf(e);return t.some(r=>r.scope_id!==e.scope_id&&lf(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function w1(e){const t=yw(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 S1(e){return e?nf.find(t=>t.scope_id===e)??null:null}function Xc(e){const t=S1(e);return e?t?`${lf(t)} · ${w1(t)}`:"Unknown Space":"—"}function df(){return nf.filter(e=>e.scope_id!=="legacy-shared-review"&&!v1(e))}function C1(e){return df().some(t=>t.scope_id===e)}function _w(...e){for(const t of e)if(t&&C1(t))return t;return e.find(t=>!!t)??""}function R1(e){const t=yw(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function I1(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function k1(){const e=new Map;for(const t of df()){const n=I1(t),r=R1(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function ww(e){for(const t of k1()){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=_1(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function T1(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 uf(e,t,n=[]){try{await PR({...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}),ei.delete(e.workspace_identity),Vc.delete(e.workspace_identity),Z("Project Space assignment updated. Device access grants are unchanged."),bt?.()}catch(r){if(r instanceof za){ei.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),bt?.();return}Z(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function P1(e,t){const n=e.filter(Jc);if(n.length!==0)try{await NR({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}))}),Z(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),Kc.delete(sf(n[0])),bt?.()}catch(r){Z(r instanceof za?"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 N1(e){if(e.mapping_id!=null)try{await ER(e.mapping_id),ei.delete(e.workspace_identity),Vc.delete(e.workspace_identity),Z("Project Space assignment removed. The next fallback now applies."),bt?.()}catch(t){Z(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function Sw(e,t=!1){try{const n=Ra.get(e.workspace_identity),r=await xR({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});Ra.delete(e.workspace_identity),Z(`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.`),bt?.()}catch(n){if(n instanceof Sm){Ra.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),bt?.();return}Z(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function Cw(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Va()).filter(i=>i&&i!==t)}catch{}const r=await rp({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 AR({project:r.trim(),workspace_identity:e.workspace_identity});Z(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),bt?.()}catch(i){Z(i instanceof Error?i.message:"Unable to change project.","warning")}}async function E1(e){const t=Ia.get(e);if(t&&!vn(t))return{offset:Ut,project:t};try{let n=0,r=0;for(;;){const i=await bo({limit:Uc,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!vn(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>=s1)return null;n=s}}catch{return null}}function Rw(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&&Hc.add(o)}return n.open=!0,Gc.add(`${t.dataset.projectRepairable}:${e}`),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}async function A1(e){if(Yc()){Z("Finish the open Space assignment, then try Repair again.","warning");return}const t=Gn,n=$e("projectsSearch")?.value??"",r=$e("projectsStatusFilter")?.value??"",i=Ut,o=await E1(e.projectIdentity);if(Gn!==t||($e("projectsSearch")?.value??"")!==n||($e("projectsStatusFilter")?.value??"")!==r||Ut!==i)return;if(Yc()){Z("Finish the open Space assignment, then try Repair again.","warning");return}if(!o){Z("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){Z("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await Cw(s);return}if(!Rw(s.workspace_identity)){const c=$e("projectsSearch"),l=c?.value??"",d=s.workspace_identity;c&&(c.value=d);const u=$e("projectsStatusFilter"),p=u?.value??"",f="";u&&(u.value=f);const m=Ut;Ut=o.offset;const v=Gn;if(await Na(),!Rw(s.workspace_identity)){if(Gn!==v||c&&c.value!==d||u&&u.value!==f||Ut!==o.offset)return;c&&(c.value=l),u&&(u.value=p),Ut=m,await Na(),Z("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function x1(e){const t=Gn,n=(io?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Gn===t)try{await A1(e)}catch(r){Z(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return io=n,n.then(()=>{io===n&&(io=null)},()=>{io===n&&(io=null)}),n}function D1(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Jc(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=!fr,fr||(m.title="The complete project list is unavailable."),m.addEventListener("click",()=>_s([e.workspace_identity])),t.appendChild(m)}if(vn(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=df().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=`${Xc(e.resolved_scope_id)} — not assignable`,m.disabled=!0,i.appendChild(m)}ww(i),i.value=_w(Vc.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",()=>{uf(e,i.value)}),i.addEventListener("change",()=>{Vc.set(e.workspace_identity,i.value),ei.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,bt?.()}),i.addEventListener("blur",bw);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{uf(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",()=>{N1(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",()=>{Cw(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",()=>{Sw(e)}),t.append(n,i,s,c,l,d,u);const p=ei.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 R=document.createElement("li"),I=document.createElement("strong");I.textContent=`${T1(_)}: `;const T=document.createElement("span");T.textContent=_.message,R.append(I,T),h.appendChild(R)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const _=ei.get(e.workspace_identity);!_||_.scopeId!==i.value||uf(e,_.scopeId,_.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{ei.delete(e.workspace_identity),bt?.()}),m.append(v,g,h,b,w),t.appendChild(m)}const f=Ra.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 b=document.createElement("button");b.className="settings-button danger",b.type="button",b.textContent="I understand, forget local memories",b.addEventListener("click",()=>{Sw(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{Ra.delete(e.workspace_identity),bt?.()}),m.append(v,g,h,b,w),t.appendChild(m)}return t}function Iw(e){const t=document.createElement("article");t.className="project-inventory-row",t.dataset.projectWorkspaceIdentity=e.workspace_identity,t.dataset.projectRepairable=String(Jc(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",vs(e)&&r.appendChild(hw([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),vs(e)&&r.appendChild(vw([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 · ${fw(e.latest_session_at)}`,t.appendChild(o),t.appendChild(gw([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=af(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${u1(e)} · ${e.identity_source} · ${fw(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 b=document.createElement("strong");b.textContent="Project sharing";const w=document.createElement("ul");w.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const _ of e.sharing){const R=document.createElement("li"),I=document.createElement("strong");I.textContent=p1(_);const T=document.createElement("span");T.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,R.append(I,T),w.appendChild(R)}h.append(b,w),s.appendChild(h)}if(vn(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=h1(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 ${Xc(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(b=>b.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const b of e.statuses){const w=document.createElement("span");w.className=`project-status-badge ${b}`,w.textContent=c1(b),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=Gc.has(f),p.addEventListener("toggle",()=>{p.open?Gc.add(f):Gc.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",af(e)],["Suggested Space",e.suggested_scope_id?Xc(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,b]of g){const w=document.createElement("dt");w.textContent=h;const _=document.createElement("dd");_.textContent=b==null||b===""?"—":String(b),v.append(w,_)}return p.appendChild(v),p.appendChild(D1(e)),t.appendChild(p),t}function L1(e){const t=[...new Set(e.map(n=>af(n)))];return t.length===1?t[0]:"Mixed Spaces"}function $1(e){if(e.length===1)return Iw(e[0]);const t=sf(e[0]),n=e.filter(vs),r=mw(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const o=cf(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(hw(n,`Select all identities for ${cf(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(vw(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=L1(e),d.appendChild(u);const p=e.reduce((_,R)=>_+(R.memory_count??0),0),f=e.reduce((_,R)=>_+R.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(gw(r));const v=document.createElement("div");v.className="project-inventory-actions";const g=e.filter(Jc);if(g.length===0){const _=document.createElement("div");_.className="settings-note",_.textContent=e.every(vn)?"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(N=>({project:N,warnings:(N.guardrail_warnings??[]).filter(L=>L.requires_confirmation)})),R=_.some(({warnings:N})=>N.length>0),I=new Set(g.map(N=>N.suggested_scope_id).filter(N=>!!N)),T=new Set(g.map(N=>N.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${cf(e[0])} group`);const O=document.createElement("option");O.value="",O.textContent="Choose Space…",A.appendChild(O),ww(A),A.value=_w(Kc.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||R,F.addEventListener("click",()=>{P1(g,A.value)}),A.addEventListener("change",()=>{A.value?Kc.set(t,A.value):Kc.delete(t),F.disabled=!A.value||R}),A.addEventListener("blur",bw),v.append(A,F),I.size>1||T.size>1||R){const N=document.createElement("div");if(N.className="settings-note project-attention-note",N.textContent=R?"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.",R){const L=document.createElement("ul");for(const{project:D,warnings:G}of _){if(G.length===0)continue;const q=document.createElement("li"),$=document.createElement("strong");$.textContent=`Blocked identity: ${D.workspace_identity}`;const E=document.createElement("span");E.textContent=` — ${G.map(S=>S.message).join(" ")}`,q.append($,E),L.appendChild(q)}N.appendChild(L)}v.appendChild(N)}d.appendChild(v)}const h=document.createElement("details");h.className="project-inventory-details",h.open=Hc.has(t),h.addEventListener("toggle",()=>{h.open?Hc.add(t):Hc.delete(t)});const b=document.createElement("summary"),w=e.reduce((_,R)=>_+(R.guardrail_warnings??[]).filter(I=>I.severity==="warning").length,0);b.textContent=w>0?`Advanced Project administration — ${w.toLocaleString()} item${w===1?"":"s"} need attention`:"Advanced Project administration",h.appendChild(b),h.appendChild(d);for(const _ of e)h.appendChild(Iw(_));return i.appendChild(h),i}function O1(e){const t=new Map;for(const n of e){const r=sf(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function kw(e){const t=$e("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function Tw(){document.getElementById("projectsInventorySkeleton")?.remove()}function Pw(e){const t=$e("projectsInventoryMeta"),n=$e("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;Tw(),Ia.clear();for(const s of e.projects)d1(s);if(n.textContent="",e.projects.length===0)kw("No projects match those filters.");else for(const s of O1(e.projects))n.appendChild($1(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=$e("projectsPrevPage"),o=$e("projectsNextPage");i&&(i.disabled=e.offset===0),o&&(o.disabled=!e.has_more),ti(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function j1(e,t){y1().then(()=>{t===ro&&(Yc()||Pw(e))})}async function M1(){const e=new Map;let t=0;for(;;){const n=await bo({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 Nw(e,t,n){const r=$e("recipientPolicyManagementMount");r&&qg(r,ys(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Gt.clear(),ti(),bt?.()}})}function Ew(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&&$e("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),rf){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",()=>rf?.(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||$e("projectsSearch")?.focus()}}function Aw(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 F1(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}function Na(e={}){const t=B1(e);return uw=t,t}async function xw(e,t){return e.requireTeamSetupSummary?(await t,!1):uw??!1}async function B1(e){const t=$e("projectsInventoryMeta"),n=$e("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await of(!0)).ok:!0;if(Yc()){if(zc=!0,!e.requireTeamSetupSummary)return!0;const o=++Ta,s=await of(!0);if(o!==Ta)return!1;const c=$e("recipientPolicyReviewMount");return s.ok?(c&&Ew(c,s.summary),!0):(c&&Aw(c),!1)}zc=!1;const r=++ro;fr=!1,mr=!1,ti(),t.textContent="Loading project inventory…";let i=null;try{const o=++Ta;i=of(e.requireTeamSetupSummary===!0);const[s,c,l,d,u]=await Promise.all([bo({limit:Uc,offset:Ut,q:$e("projectsSearch")?.value.trim()||void 0,status:$e("projectsStatusFilter")?.value||void 0}),CR(),M1().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),SR().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),El().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==ro)return xw(e,i);if(nf=c.scopes,fr=l.ok,mr=u.ok,oo=u.ok?u.intent:Wc,l.ok){const g=new Set(ys(l.projects).map(h=>h.canonicalProjectIdentity));for(const h of Gt)g.has(h)||Gt.delete(h)}const p=$e("projectShareFlowMount");p&&Kg(p,l.projects,{inventoryError:!l.ok});const f=$e("recipientPolicyReviewMount");if(f){const g=F1(f);"review"in d?o1(g,d.review,{isRepairAvailable:h=>!h.projectIdentity.startsWith("unmapped:"),onRepair:x1}):a1(g,d.error),f.hidden=g.hidden&&!f.querySelector(".project-team-setup-entry")}Nw(l.projects,oo,!l.ok||!u.ok),Pw(s),j1(s,r),i.then(g=>{if(r!==ro||o!==Ta)return;const h=$e("recipientPolicyReviewMount");if(h){if(!g.ok){Aw(h);return}Ew(h,g.summary)}});const m=l.ok&&"review"in d&&u.ok;if(!e.requireTeamSetupSummary)return m;const v=await i;return r!==ro||o!==Ta?!1:m&&v.ok}catch(o){if(r!==ro)return xw(e,i);Ia.clear(),fr=!1,mr=!1,oo=Wc;const s=$e("projectShareFlowMount");return s&&Kg(s,[],{inventoryError:!0}),Nw([],Wc,!0),ti(),Tw(),t.textContent="Project inventory failed to load.",kw(o instanceof Error?o.message:"Unable to load project inventory."),!1}}function q1(e,t={}){bt=e,rf=t.onOpenTeamSetup,Gt.clear();const n=$e("projectsStatusFilter");if(n&&n.options.length===0)for(const[o,s]of dw){const c=document.createElement("option");c.value=o,c.textContent=s,n.appendChild(c)}const r=()=>{Gn+=1,Ut=0,bt?.()};$e("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),$e("projectsPrevPage")?.addEventListener("click",()=>{Gn+=1,Ut=Math.max(0,Ut-Uc),bt?.()}),$e("projectsNextPage")?.addEventListener("click",()=>{Gn+=1,Ut+=Uc,bt?.()});const i=$e("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Gt.size!==0&&xo({mode:"project-add",projectIds:[...Gt].sort()})})),ti()}function pf(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 U1(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 Dw="codemem-settings-advanced",Lw="gpt-5.1-codex-mini",$w="claude-4.5-haiku",G1=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],H1={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"},V1=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),K1={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 z1(){try{return globalThis.localStorage?.getItem(Dw)==="1"}catch{return!1}}function W1(e){try{globalThis.localStorage?.setItem(Dw,e?"1":"0")}catch{}}function Hn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ee(e,t,n){if(Hn(t,n))return t[n];if(Hn(e,n))return e[n]}function Oe(e){return e==null?"":String(e)}function Qc(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 J1(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Y1(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function X1(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:$w,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:Lw,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:$w,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:Lw,source:"Recommended (direct API)"}}function Q1(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(Oe(n[t]));case"observer_runtime":return ct(Oe(n.observer_runtime));case"observer_auth_source":return ct(Oe(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(!Hn(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(!Hn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Hn(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 Qc(n[t]);default:return Hn(n,t)?n[t]:""}}function Z1(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Hn(r,i)&&(r[i]=Q1(t,i))}),r}function eF(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=pf(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("claude_command"))throw R;const I=r.claude_command;o=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=pf(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("codex_command"))throw R;const I=r.codex_command;s=Array.isArray(I)?I.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=pf(t.observerAuthCommand,{label:"observer auth command"})}catch(R){if(!i||n.has("observer_auth_command"))throw R;const I=r.observer_auth_command;c=Array.isArray(I)?I.filter(T=>typeof T=="string"):[]}let l={};try{l=U1(t.observerHeaders)}catch(R){if(!i||n.has("observer_headers"))throw R;const I=r.observer_headers;I&&typeof I=="object"&&!Array.isArray(I)&&Object.entries(I).forEach(([T,A])=>{typeof T=="string"&&T.trim()&&typeof A=="string"&&(l[T]=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),b=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 b!="number"||!Number.isFinite(b)||b<=0||!Number.isInteger(b)))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:b,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 tF(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:Oe(Ee(t,n,"observer_provider")),observerModel:Oe(Ee(t,n,"observer_model")),observerTierRoutingEnabled:Qc(Ee(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Oe(Ee(t,n,"observer_simple_model")),observerSimpleTemperature:Oe(Ee(t,n,"observer_simple_temperature")),observerReasoningEffort:Oe(Ee(t,n,"observer_reasoning_effort")),observerReasoningSummary:Oe(Ee(t,n,"observer_reasoning_summary")),observerRichModel:Oe(Ee(t,n,"observer_rich_model")),observerRichTemperature:Oe(Ee(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Oe(Ee(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Oe(Ee(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Oe(Ee(t,n,"observer_rich_max_output_tokens")),observerRuntime:Oe(Ee(t,n,"observer_runtime"))||"api_http",observerAuthSource:Oe(Ee(t,n,"observer_auth_source"))||"auto",observerAuthFile:Oe(Ee(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Oe(Ee(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Oe(Ee(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Oe(Ee(t,n,"observer_max_chars")),packObservationLimit:Oe(Ee(t,n,"pack_observation_limit")),packSessionLimit:Oe(Ee(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Oe(Ee(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Qc(Ee(t,n,"sync_enabled")),syncHost:Oe(Ee(t,n,"sync_host")),syncPort:Oe(Ee(t,n,"sync_port")),syncInterval:Oe(Ee(t,n,"sync_interval_s")),syncMdns:Qc(Ee(t,n,"sync_mdns")),syncCoordinatorUrl:Oe(Ee(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Oe(Ee(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Oe(Ee(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Oe(Ee(t,n,"sync_coordinator_presence_ttl_s"))}}function nF(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=X1(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Hn(t,r))?"Env override":n.source}: ${n.model}`}function rF(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 iF(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function oF(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 aF(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 sF(e){return!e}function cF(e,t,n){return t.has(e)||n.has(e)}function lF(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var Y={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:z1(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...K1}}};function dF(){Y.controller?.hideTooltip()}function ni(e){if(Y.controller){Y.controller.setRenderState(e);return}Y.renderState={...Y.renderState,...e}}function uF(e){ni({values:{...Y.renderState.values,...e}})}function pF(e){const t=["observer","queue","sync"].includes(e)?e:"observer";Y.activeTab=t,Y.controller?.setActiveTab(t)}function Zc(e,t=!0){C.settingsDirty=e,t&&Y.controller?.setDirty(e)}function fF(e){Y.showAdvanced=e,Y.controller?.setShowAdvanced(e)}function Ow(){return Y.open}function mF(e){return cF(e,Y.protectedKeys,V1)}function jw(e={}){return eF({values:Y.renderState.values,touchedKeys:Y.touchedKeys,baseline:Y.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function hF(e){ni({observerStatus:e&&typeof e=="object"?e:null})}function gF(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=tF(t);Y.envOverrides=i,Y.protectedKeys=new Set(o),C.configDefaults=n,C.configPath=t.path||"",ni({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:J1(t.providers),statusText:"No unsaved changes",values:s}),Y.touchedKeys=new Set;try{const c=jw({allowUntouchedParseErrors:!0});Y.baseline=Z1(c,r,i)}catch{Y.baseline={}}Zc(!1)}async function vF(){if(!Y.open)try{const[e,t]=await Promise.all([bC(),yC().catch(()=>null)]);gF(e),hF(t)}catch{}}function ff(e){return String(e||"").replace(/_/g," ")}function mf(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 yF(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 bF(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 _F(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function wF({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function SF({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=e.available_credentials||{},i=e.latest_failure,o=Object.entries(r).filter(([,s])=>s&&typeof s=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[n?a(z,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(n.provider||"unknown")," → ",String(n.model||"")," via"," ",yF(n.auth?.method||"none")," ",a("span",{"aria-label":n.auth?.token_present===!0?"token present":"token missing",className:n.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":n.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)"})]}),o.length?a(z,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:o.map(([s,c],l)=>{const d=c,u=Object.values(d).some(Boolean);return a("span",{className:"status-cred",children:[l>0?" · ":null,a("span",{"aria-label":u?"credential available":"no credential",className:u?"cred-ok":"cred-none",role:"img",children:u?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(s),": ",bF(d)]},s)})})]}):null,i&&typeof i=="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 i.error_message=="string"&&i.error_message.trim()?i.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof i.observer_provider=="string"?i.observer_provider.trim():"",typeof i.observer_model=="string"&&i.observer_model.trim()?`→ ${i.observer_model.trim()}`:"",typeof i.observer_runtime=="string"&&i.observer_runtime.trim()?`(${i.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${_F(i.updated_at)}`,typeof i.attempt_count=="number"&&Number.isFinite(i.attempt_count)?`Attempts ${i.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof i.impact=="string"&&i.impact.trim()?a("div",{className:"status-issue-impact",children:i.impact.trim()}):null,a(wF,{onOpenDiagnostics:t})]})]}):null]})}function Mw(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 Ea(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function CF(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 RF(){const e=Le("settingsModal");(CF(e)[0]||e)?.focus()}function IF(){const[e,t]=x({anchor:null,content:"",visible:!1}),n=B(null);return V(()=>{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=Ea(u.target);p&&r(p)},s=u=>{const p=Ea(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=Ea(u.target);p&&r(p)},l=u=>{Ea(u.target)&&i()},d=u=>{const p=Ea(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&&Mw(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),V(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&Mw(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:ke(()=>typeof document>"u"?null:sn(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 kF({DialogContent:e,onClose:t}){const[n,r]=x(Y.open),[i,o]=x(["observer","queue","sync"].includes(Y.activeTab)?Y.activeTab:"observer"),[s,c]=x(C.settingsDirty),[l,d]=x(Y.renderState),[u,p]=x(Y.showAdvanced),{tooltipPortal:f,setTooltip:m}=IF();Y.open=n,Y.activeTab=i,C.settingsDirty=s,Y.renderState=l,Y.showAdvanced=u,V(()=>(Y.controller={hideTooltip:()=>{m({anchor:null,content:"",visible:!1})},setActiveTab:g=>{const h=["observer","queue","sync"].includes(g)?g:"observer";Y.activeTab=h,o(h)},setDirty:g=>{C.settingsDirty=g,c(g)},setOpen:g=>{Y.open=g,r(g)},setRenderState:g=>{const h={...Y.renderState,...g};Y.renderState=h,d(h)},setShowAdvanced:g=>{Y.showAdvanced=g,W1(g),p(g)}},()=>{Y.controller&&(Y.controller=null)}),[]),V(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const v=ae(()=>{Y.startPolling&&Y.refresh&&t(Y.startPolling,Y.refresh)},[t]);return a(z,{children:[a(Qn,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:g=>{g.preventDefault()},onOpenAutoFocus:g=>{g.preventDefault(),RF()},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 Aa({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function hf({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 TF({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(hf,{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(ar,{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(Te,{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(ar,{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(Ki,{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(Ki,{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(Te,{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(ar,{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(Te,{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(Ki,{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(Aa,{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(Te,{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(Te,{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(Ki,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:f("observer_headers")})]})]})]})}function el({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(Gi,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function PF({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(z,{children:[a(hf,{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(Te,{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(el,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(Aa,{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(Te,{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(Te,{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(Te,{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(Te,{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(Te,{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(Te,{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(Te,{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(Te,{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(Te,{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(Aa,{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(Te,{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(Te,{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 NF({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(z,{children:[a(hf,{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(el,{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(Te,{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(Te,{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(Te,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(el,{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(Te,{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(Te,{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(Aa,{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(Te,{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(Te,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function EF({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=>Li(p,{onSubmit:s,disabled:u}),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(kr,{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(el,{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(Aa,{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(oy,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:G1,triggerClassName:"settings-tab",value:t,children:[a($r,{className:"settings-panel",forceMount:!0,value:"observer",children:a(TF,{...e,observerStatusBannerSlot:d})}),a($r,{className:"settings-panel",forceMount:!0,value:"queue",children:a(PF,{...e})}),a($r,{className:"settings-panel",forceMount:!0,value:"sync",children:a(NF,{...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 AF(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||Hn(r,c)&&!i.has(c)||Y1(l,n[c])||(s[c]=l)}),s}function xF(e){const t=s=>{const c=H1[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 DF(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=>ff(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>ff(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>ff(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: ${mf(r)}.`),i.length&&d.push(`Live settings updated: ${mf(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 ${mf(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 LF=()=>nF(Y.renderState.values,Y.envOverrides),$F=()=>rF(Y.renderState.values),OF=()=>iF(Y.renderState.values),jF=()=>oF(Y.renderState.values),MF=()=>aF(Y.renderState.values),FF=()=>sF(Y.showAdvanced),{onTextInput:BF,onSelectValueChange:qF,onSwitchInput:UF}=xF({getTouchedKeys:()=>Y.touchedKeys,getValues:()=>Y.renderState.values,updateFormState:uF,setDirty:e=>Zc(e)});function GF(){const e=Y.renderState.observerStatus;return a(SF,{status:e,onOpenDiagnostics:HF})}function HF(e){if(!Y.startPolling||!Y.refresh||(xa(Y.startPolling,Y.refresh),Y.open))return;const t=js("settingsButton");queueMicrotask(()=>Ar({...e,trigger:t}))}function VF(){const e=Y.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(Y.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:FF,onTextInput:BF,onSelectValueChange:qF,onSwitchInput:UF,getObserverModelLabel:OF,getObserverModelTooltip:jF,getObserverModelDescription:MF,getObserverModelHint:LF,getTieredRoutingHelperText:$F,protectedConfigHelp:lF};return a(EF,{panelProps:o,activeTab:Y.activeTab,showAdvanced:Y.showAdvanced,renderState:Y.renderState,settingsDirty:C.settingsDirty,onClose:()=>{Y.startPolling&&Y.refresh&&xa(Y.startPolling,Y.refresh)},onSave:()=>{Y.startPolling&&Y.refresh&&JF(Y.startPolling,Y.refresh)},onActiveTabChange:pF,onAdvancedToggle:fF,observerStatusBannerSlot:a(GF,{})})}function KF(){return a(kF,{DialogContent:VF,onClose:xa})}function zF(){const e=Le("settingsDialogMount");e&&Ue(a(KF,{}),e)}function Fw(){Le("settingsDialogMount")&&(Y.shellMounted||(zF(),Y.shellMounted=!0))}function WF(e){Y.shellMounted||Fw(),Y.open=!0,Y.previouslyFocused=document.activeElement,e(),Y.controller?.setOpen(!0)}function xa(e,t){if(C.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){Y.controller?.setOpen(!0);return}Y.open=!1,Y.controller?.setOpen(!1),dF(),(Y.previouslyFocused&&typeof Y.previouslyFocused.focus=="function"?Y.previouslyFocused:js("settingsButton"))?.focus(),Y.previouslyFocused=null,Y.touchedKeys=new Set,e(),t()}async function JF(e,t){if(!Y.renderState.isSaving){ni({isSaving:!0,statusText:"Saving changes…"});try{const n=jw({allowUntouchedParseErrors:!0}),r=AF({current:n,baseline:Y.baseline,envOverrides:Y.envOverrides,touchedKeys:Y.touchedKeys,isProtected:mF});if(Object.keys(r).length===0){ni({isSaving:!1,statusText:"No unsaved changes"}),Zc(!1),xa(e,t);return}const i=await _C(r),o=DF(i);ni({isSaving:!1,statusText:"Saved changes"}),Zc(!1),xa(e,t),Z(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";ni({isSaving:!1,statusText:`Save failed: ${r}`})}}}function YF(e,t,n){Y.startPolling=t,Y.refresh=n,Fw(),js("settingsButton")?.addEventListener("click",()=>WF(e))}function XF(e){e.dataset.syncRenderRoot="preact"}function QF(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function mt(e,t){XF(e),Ue(t,e)}function ao(e){e.dataset.syncRenderRoot==="preact"&&Ue(null,e)}function ZF(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 eB(e){return typeof e=="object"&&e!==null}function tB(e,t){return C.pairingCommandRaw="",{payloadText:e,hintText:t}}function nB(e){if(!eB(e))return tB("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 rB(){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 iB(){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 oB(){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 aB(){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 sB(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 cB({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 lB({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,n.action?a("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function Bw({text:e}){return a(z,{children:e})}function dB({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function uB(e,t){if(!t.length){ao(e);return}mt(e,a(cB,{items:t}))}function pB(e,t,n){if(!t.length){ao(e);return}mt(e,a(lB,{attempts:t,note:n}))}function ri(e,t){mt(e,a(dB,{...t}))}function qw(e,t,n){mt(e,a(Bw,{text:n.payloadText})),t&&mt(t,a(Bw,{text:n.hintText}))}function Uw({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=B(null),p=B(null),f=B(!1);It(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),V(()=>{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(Wo,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(zo,{open:e,onOpenChange:t,children:[a(Cu,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?sn(m,l):m]})}function fB({open:e,onOpenChange:t}){return a(Uw,{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(Te,{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(Te,{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(Ki,{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 mB({contentHost:e,open:t,onOpenChange:n}){return a(Uw,{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 hB(e,t){mt(e,a(fB,{...t}))}function gB(e,t){mt(e,a(mB,{...t}))}function me(e){return String(e??"").trim()}function vB(e){return me(e).replace(/\s+/g," ").toLowerCase()}function yB(e){const t=me(e);return t?t.slice(0,8):"Unnamed device"}function Gw(e){return me(e?.last_error).toLowerCase()}function Hw(e){return e.includes("401")&&e.includes("unauthorized")}function Vw(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var bB={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function Kw(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 _B(e){const t=Kw(e);return!me(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function zw(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=RB(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=>Ww(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=>Ww(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:me(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function Ww(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 wB(n)?"trust":SB(n)?"scope":null}function wB(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function SB(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function CB(e){const t=me(e?.reason);return bB[t]??(t.replaceAll("_"," ")||"sync filters")}function RB(e){const t=new Map;for(const n of e){const r=CB(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 Jw(e){const t=me(e.localName);if(t)return t;const n=me(e.coordinatorName);return n||yB(me(e.deviceId))}function IB(e){const t=me(e.localName),n=me(e.coordinatorName);return t||n?!1:!!me(e.deviceId)}function kB(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 Da(e){const t=me(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=Gw(e);return Hw(n)?"needs-repair":Vw(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function so(e){const t=e?.status||{},n=me(t.peer_state),r=Gw(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}:Hw(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}:Vw(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 TB={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 PB(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:TB[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 Yw(e){return Array.isArray(e)?e.map(t=>me(t)).filter(t=>!!t):[]}function Xw(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 tl(e,t){return e?e.replaceAll("_"," "):t}function NB(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=me(r.scope_id),o=me(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[tl(me(r.kind),"user"),tl(me(r.authority_type),"local"),`${tl(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 Qw(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 o=i||"Untitled Space",s=me(n.last_applied_cursor),c=me(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=tl(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(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 EB=["personal","private","home","mine","me"],AB=["oss","open source","opensource","community","public"],xB=["work","client"],DB=["local","legacy","review"];function LB(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>me(t)??"").join(" ").toLowerCase()}function $B(e){return[e.scope_id,e.label,e.kind].map(t=>me(t)??"").join(" ").toLowerCase()}function Zw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gf(e,t){const n=LB(e);return t.some(r=>{const i=Zw(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function eS(e){return gf(e,EB)||gf(e,AB)}function OB(e){const t=$B(e);return DB.some(n=>{const r=Zw(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function jB(e){return!eS(e)&&(!OB(e)||gf(e,xB))}function MB(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(eS),r=t.some(jB);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 FB(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function BB(e){const t=Yw(e?.effective_include),n=Yw(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${Xw(t,"all projects")}`,o=`Exclude filter: ${Xw(n,"no exclusions")}`,s=FB(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 qB(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=me(n?.display_name),i=me(n?.actor_id),o=vB(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 tS(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 o=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||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(me(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var UB=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),GB=new Set(["pending","verifying","waiting"]);function HB(e){return(Array.isArray(e?.groups)?e.groups.map(t=>me(t)).filter(Boolean):[]).join(", ")||"none"}function VB(e){return me(e?.projects?.[0]?.display_name)||"the shared Project"}function KB(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=so(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function zB(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&so(n).state==="mutual-trust"&&!Qw(n).rows.some(r=>r.status==="pending"))}function WB(e){return e.some(t=>me(t.status?.peer_state)==="online"&&so(t).state==="mutual-trust")}function JB(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=so(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function YB(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 nS(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=HB(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&&UB.has(f)}),d=i.find(p=>{const f=p.state;return f!==void 0&&GB.has(f)});if(l||d){const p=l?VB(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(YB(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(KB(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=me(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."}:JB(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&&zB(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}:WB(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 XB(e){return e.discovered?.stale?e.peer?Da(e.peer)!=="connected":!0:!1}function rS(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 vf(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 QB(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 ZB(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 eq(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=me(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=me(i?.name)}),t.forEach(i=>{const o=me(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=me(i?.display_name)}),[...n.values()]}function tq(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=eq(n,r),o=e.duplicatePersonDecisions??{},s=qB(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=Jw({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Da(l.peer):"waiting",p=l.peer?so(l.peer):null,f=me(l.discovered?.fingerprint),m=me(l.peer?.fingerprint);if(l.peer&&f&&m&&f!==m){c.push(rS({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||me(l.peer?.last_error)||"Sync needs review.";c.push(rS({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(vf({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(vf({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(vf({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&&IB({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(QB({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:nS({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Da(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>XB(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var iS={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 hr(e){const t=document.getElementById(e);t&&t.remove()}var oS=!1;function nq(e){oS=e}var yf=!1;function rq(e){yf=e}var bf=!1;function iq(e){bf=e}var oq=new Set,_f=new Set,wf=new Set,aS="codemem-sync-duplicate-person-decisions";function aq(e){const t=String(e||"").trim();t&&(_f.add(t),wf.add(t),oq.add(t))}function Sf(e){const t=String(e||"").trim();return!!t&&_f.has(t)}function sq(e){const t=String(e||"").trim();t&&_f.delete(t)}function cq(e){const t=String(e||"").trim();return!t||!wf.has(t)?!1:(wf.delete(t),!0)}function Cf(){try{const e=localStorage.getItem(aS);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function sS(e){try{localStorage.setItem(aS,JSON.stringify(e))}catch{}}function cS(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function lq(){return Cf()}function dq(e,t){const n=cS(e);if(!n)return;const r=Cf();r[n]=t,sS(r)}function uq(e){const t=cS(e);if(!t)return;const n=Cf();delete n[t],sS(n)}function lS(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function dS(e){const t=String(e||"");return t?lS(t):""}function pq(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function fq(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function nl(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 Rf(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":nl(e)}function mq(e){return(Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function hq(){return tS({actors:C.lastSyncActors,peers:C.lastSyncPeers,duplicatePeople:C.lastSyncViewModel?.duplicatePeople}).visibleActors}function uS(e){return hq().filter(t=>String(t?.actor_id||"")!==e)}function gq(e,t){const n=uS(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Rf(n)}. Assigned devices move now; existing memories keep their current provenance.`}function If(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Os("div","sync-action"),i=Os("div","sync-action-text");i.textContent=n.label,i.appendChild(Os("span","sync-action-command",n.command));const o=Os("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Uo(n.command,o)),r.append(i,o),e.appendChild(r)})}}function pS(e,t){return t&&e.error_redacted===!0}function vq(e){return e?{action:t=>Ar({severity:"error",subsystem:"sync",trigger:t})}:{}}function fS(){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){ri(e,oB());return}const r=sB(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=Ho();if(u&&o.error){const m=String(o.error);p.push(f?lS(m):m),pS(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?Vr(s):"",...vq(u),...pS(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});pB(e,i,r)}function yq(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&ri(e,iB()),t&&ri(t,aB()),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."),If(r,[])}function co(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function bq(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=co(n.would_remove),o=co(n.ambiguous),s=co(r.applied),c=co(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 mS(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;hr("syncDiagSkeleton");const r=C.lastSyncStatus;if(!r){ri(e,rB()),If(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||ZF(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??{},b=co(h.would_remove),w=co(h.ambiguous),_=v.enabled===!0,R=Number(v.last_deleted_ops||0),I=v.last_run_at||null,T=String(v.last_error||""),A=m==="offline-peers"?"Offline peers":m==="needs_attention"?"Needs attention":m==="rebootstrapping"?"Rebootstrapping":wb(m),O=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,N=!O&&F===0;if(t){const G=O?["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"]:N?["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: ${sr(zi(c))} ago`:"Last sync: never"];m==="offline-peers"&&G.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&G.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&G.push(`Detail: ${f}`),_&&G.push(I?`Retention last ran ${sr(zi(I))} ago (approx oldest-first)`:"Retention enabled"),b>0?G.push(`${b.toLocaleString()} stale peer rows pending cleanup`):w>0&&G.push(`${w.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=G.join(" · ")}const L=O?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:N?[{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?`${sr(zi(c))} ago`:"never"},{label:"Last peer ping",value:l?`${sr(zi(l))} ago`:"never"},{label:"Retention",value:_?I?`${R.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!O&&!N&&(d||u)&&L.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!O&&!N&&s.seconds_since_last&&L.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!O&&!N&&o.seconds_since_last&&L.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!O&&_&&T&&L.push({label:T,value:"Retention"}),!O&&!N&&g&&L.push({label:"Cleanup",value:bq(g)}),uB(e,L);const D=[];N||m==="offline-peers"||(m==="stopped"?(D.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),D.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?D.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?D.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(D.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),D.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!O&&!N&&p>0&&D.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!O&&w>0?D.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!O&&b>0&&D.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),If(n,D)}var _q="syncRedactMount",wq="syncRedactLabel",hS=()=>{};function Sq(e){hS=e}var kf=()=>{};function Tf(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;gB(e,{contentHost:t,open:C.syncPairingOpen,onOpenChange:r=>{if(ZN(r),Tf(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&qw(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}kf()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=C.pairingCommandRaw;r&&await Uo(r,n)})}function Pf(){Tf();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;qw(e,t,nB(C.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!C.pairingCommandRaw)}function gS(){const e=document.getElementById(_q);e&&mt(e,y(Gi,{"aria-labelledby":wq,checked:Ho(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{eE(t),gS(),kf(),mS(),hS(),fS(),Pf()},thumbClassName:"sync-redact-switch-thumb"}))}function Cq(e){kf=e,Tf(),gS()}function Rq(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function lo(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),Rq(e),e.addEventListener("input",()=>La(e),{once:!0}),!1}function La(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function _t(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 ii=new Map,Nf=null,Iq={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 kq(e){const t=e instanceof Error?e.message:String(e);return Iq[t]??"Setup could not be retried. Review diagnostics for details."}function Tq(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 Pq(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Ef(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 Nq({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=x(!1),[c,l]=x(()=>ii.get(e.operation_id)??null),d=B(null),u=e.lifecycle.primary_action;V(()=>{Nf!==e.operation_id||!d.current||(Nf=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 b={message:"Invite copied.",tone:"success"};ii.set(e.operation_id,b),l(b)}catch(h){const b={message:h instanceof Error?h.message:"Invite could not be copied.",tone:"warning"};ii.set(e.operation_id,b),l(b)}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"};ii.set(e.operation_id,h),Nf=e.operation_id,l(h),await r()}catch(g){const h={message:kq(g),tone:"warning"};ii.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"};ii.set(e.operation_id,h),l(h);return}if(!_s(g,e.person.display_name)){const h={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};ii.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":`${Ef(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:Ef(e.lifecycle.state)}),a("ul",{"aria-label":`${Ef(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 Eq({operations:e,...t}){const n=e[0].person,r=Pq(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(Nq,{operation:i,...t},i.operation_id))]})}function Aq(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:Tq(e.operations).map(t=>a(Eq,{...e,operations:t},t[0].person.actor_id))})}function xq(e,t){mt(e,a(Aq,{...t}))}function vS({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 Dq(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 Lq({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=nl(e),c=mq(o),l=uS(o),d=l.map(D=>String(D.actor_id||"")).join("|"),[u,p]=x(s),[f,m]=x(!1),[v,g]=x("Rename"),[h,b]=x(!1),[w,_]=x("Merge into selected person"),[R,I]=x(""),[T,A]=x(!1);V(()=>{p(s),m(!1),g("Rename"),b(!1),_("Merge into selected person"),I(""),A(!1)},[o,c,t,s,d]);const O=l.length?gq(R,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(D=>{const G=String(D.actor_id||"");return{label:D.is_local?Rf(D):nl(D),value:G}})];async function N(){const D=u.trim();if(!D)return;m(!0),g("Saving…");let G=!1;try{await n(o,D),G=!0}catch{g("Retry rename")}finally{m(!1),G&&g("Rename")}}async function L(){if(!R)return;const D=l.find(q=>String(q.actor_id||"")===R);if(!D||!await hn({title:`Merge ${s} into ${nl(D)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;b(!0),_("Merging…");let G=!1;try{await r(R,o),G=!0}catch{_("Retry merge")}finally{b(!1),G&&_("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:Rf(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?Dq(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(Te,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||h,type:"text",value:u,onInput:D=>p(D.currentTarget.value),onKeyDown:D=>Li(D,{onSubmit:()=>{N()},disabled:f||h||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||h,onClick:()=>{N()},children:v}),a("button",{type:"button",className:"settings-button danger",disabled:f||h,onClick:async()=>{await hn({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(D=>!D),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?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(ar,{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:I,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:R,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:h||l.length===0||!R,onClick:()=>{L()},children:w})]}),a("div",{className:"peer-meta actor-merge-note",children:O})]}):null]})})]})}function $q({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(Lq,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(vS,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function Oq(e,t){mt(e,a($q,{...t}))}function jq(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function Mq(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${Vr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function Fq({devices:e}){return a(z,{children:Mq(e)})}function Bq(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 qq(e){const t=jq(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ao(e.mount),ao(e.meta);return}const n=t.map(Bq),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,mt(e.mount,a(ar,{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"})),mt(e.meta,a(Fq,{devices:t}))}var Uq={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function Gq({state:e,size:t=8,"aria-label":n}){const r=n??Uq[e];return a("span",{"aria-label":r,className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function oi({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 Hq(){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 Vq(e){switch(Da(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var rl=null,yS=0,Af=new Set;function bS(e){if(rl!==e){rl=e,yS+=1;for(const t of Af)t(yS)}}function Kq(){const[,e]=x(0);return V(()=>(Af.add(e),()=>{Af.delete(e)}),[]),rl}var zq={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 _S(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 Wq(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: ${_S(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: ${_S(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 Jq(e){C.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function Yq(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 Xq(){window.location.hash="advanced/teams"}function xf(e=C.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function Qq({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=so(e),l=zq[kB(e)],d=e.status||{},u=NB(e),p=Sf(i),f=p&&u.total===0,m=MB(e),v=PB(e),g=Qw(e),h=e.project_scope||{},b=BB(h),w=pq(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(ne=>String(ne)))):[],R=Number(e.address_count??0),I=Number.isFinite(R)&&R>0?R:0,T=_.length?_.map(ne=>Ho()?dS(ne):ne).join(" · "):I>0?`${I} ${I===1?"address":"addresses"} hidden`:"No addresses",A=C.lastDeviceIdentityInventory?.items.find(ne=>ne.deviceId===i||ne.evidenceDeviceIds.includes(i)),O=Wq(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||""),N=String(d.last_ping_at||d.last_ping_at_utc||""),L=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,D=cq(i),G=B(null),[q,$]=x(o),[E,S]=x(()=>C.syncPeerFeedbackById.get(i)??null),[M,H]=x(!1),[U,re]=x("Save name"),[oe,ie]=x(!1),[se,ue]=x(!1),[Pe,Ie]=x("Remove device");V(()=>{p&&u.total>0&&sq(i)},[u.total,i,p]),V(()=>{$(o),S(C.syncPeerFeedbackById.get(i)??null),H(!1),re("Save name"),ie(!1),ue(!1),Ie("Remove device")},[o,e.actor_id,i]),V(()=>{!D||!G.current||queueMicrotask(()=>G.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[D]);async function le(){if(!i)return;const ne=q.trim();if(!ne){const xe={message:"Enter a friendly name for this device.",tone:"warning"};S(xe),C.syncPeerFeedbackById.set(i,xe),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}H(!0),re("Saving…");try{const xe=await n(i,ne);S(xe),C.syncPeerFeedbackById.set(i,xe),re("Save name")}catch{re("Retry")}finally{H(!1)}}async function ve(){if(f){const ne=xf();if(!await hn({title:`Sync ${o} before advanced rule review?`,description:ne?"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:ne?"Review legacy Team/Space setup first":"Cancel"}))return}ie(!0);try{const ne=await r(e,w);S(ne),ne&&C.syncPeerFeedbackById.set(i,ne)}finally{ie(!1)}}async function X(){if(!i||!await hn({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;ue(!0),Ie("Removing…");let ne=!1;try{await t(i,s),ne=!0}catch{Ie("Retry remove")}finally{ue(!1),ne&&Ie("Remove device")}}const ce=Kq()===i&&i!=="",be=`device-drawer-${i||"unknown"}`,fe=Vq(e),We=F?`Sync: ${Vr(F)}`:"Sync: never",he=xf(),W=`${ce?"Collapse":"Expand"} device ${o}`;return a(zo,{asChild:!0,open:ce,onOpenChange:ne=>{ne?bS(i):rl===i&&bS(null)},children:a("div",{ref:G,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Cu,{asChild:!0,children:a("button",{"aria-label":W,className:"device-row-head device-row-head--trigger",type:"button",children:[a(Gq,{state:fe}),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:We}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(Hq,{})})]})}),a(Wo,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:be,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:oe,onClick:()=>{ve()},title:w?void 0:"Address details are hidden; sync will target this device by ID.",children:oe?"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(Te,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:M,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:q,onInput:ne=>$(ne.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:M,onClick:()=>{le()},children:U}),a("button",{type:"button",className:"settings-button danger",disabled:se,onClick:()=>{X()},children:Pe})]}),a("div",{className:"peer-scope",children:[D?a("div",{className:"peer-meta",children:he?"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:T}),L?a("div",{className:"peer-meta",children:L}):null,a("div",{className:"peer-meta",children:[F?`Sync: ${Vr(F)}`:"Sync: never",N?`Ping: ${Vr(N)}`:"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(ne=>a("li",{className:"peer-scope-chip",title:ne.detail,children:ne.label},ne.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:b.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(ne=>a("li",{title:ne.detail,children:[a("span",{className:"peer-scope-rejection-label",children:ne.label}),a("span",{className:`badge ${ne.status==="received"?"badge-online":"actor-badge"}`,children:ne.badgeLabel})]},ne.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(ne=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:ne.label}),a("span",{className:"peer-scope-rejection-count",children:ne.count.toLocaleString()})]},ne.reason))}),v.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",Vr(v.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:O.summary}),a("div",{className:"peer-meta",children:O.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:Yq(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>Jq(A?.deviceId??i),children:O.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[b.statusLabel,". ",b.summary," ",b.note]}),he?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:Xq,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(oi,{feedback:E})]})]})]})})}function Zq(e){const t=C.syncPeersSectionFeedback,n=C.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(z,{children:[a(oi,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(Qq,{peer:i,...e},o)})]}):a(z,{children:[a(oi,{feedback:t}),a(vS,{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 eU(e,t){mt(e,a(Zq,{...t}))}var gr=async()=>{},il="";function Df(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function tU(e){gr=e}function nU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;hr("syncActorsSkeleton"),Df(!1);const n=tS({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.`)),Oq(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await jR(i,o),await gr()},onMerge:async(i,o)=>{try{await $m(i,o),Z("People combined. Assigned devices moved to the selected person."),await gr()}catch(s){throw Z(_t(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await MR(i),Z("Person removed. Assigned devices have been unassigned."),await gr()}catch(o){throw Z(_t(o,"Failed to remove person."),"warning"),o}}})}function rU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Df(!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&&ri(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function iU(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;xq(e,{operations:C.lastShareOperations,onAdvance:n=>TR(n),onLoadOperation:n=>kR(n),onReload:gr});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 Lf(){const e=document.getElementById("syncPeers");if(!e)return;hr("syncPeersSkeleton");const t=C.lastSyncPeers,n=Array.isArray(t)?t:[];fq(C.syncPeersSectionFeedback,n)&&(C.syncPeersSectionFeedback=null),eU(e,{peers:n,onRename:async(r,i)=>{try{return await wm(r,i),await gr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:_t(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await xl({address:i,peerDeviceId:o||void 0}),c=zw(s);let l;c.ok?o&&Sf(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${xf()?"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 gr()}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:_t(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await _m(r);const o={message:`Removed peer ${i}.`,tone:"success"};return C.syncPeerFeedbackById.delete(r),C.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await gr(),o}catch(o){return{message:_t(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function oU(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Df(!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&&ri(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&&ri(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 wS(){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:[];qq({devices:r,meta:n,mount:t,onValueChange:i=>{i!==il&&(il=i,wS())},panel:e,value:il})}function aU(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Li(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){lo(n,"Enter a name for the person.");return}La(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await OR(i),Z("Person created."),n.value="",await e()}catch(o){Z(_t(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(il||"").trim();if(!i||!r||!await hn({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 FR(i),Z("Old device history attached to you."),await e()}catch(s){Z(_t(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function sU(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function $f(e=sU()){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 SS=!1;function cU(){SS||(SS=!0,window.addEventListener("hashchange",()=>{$f()}))}var yn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function lU(e){yn.loadSyncData=e}var dU=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function uU(){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 Of(){const e=document.getElementById("syncAdminDisclosureMount");e&&hB(e,{open:oS,onOpenChange:t=>{nq(t),Of(),al(),jf()}})}function pU(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function jf(){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 ol(){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 al(){const e=document.getElementById("syncInvitePolicyMount");e&&mt(e,y(ar,{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!==yn.invitePolicy&&(yn.invitePolicy=n,al())},options:dU,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:yn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function fU(e,t){Of(),al();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,b=0;r?.addEventListener("click",()=>{_s()||Z("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(_,R)=>{if(!u||!m||!v)return"other";const I=await bm(_);if(R!==b||d?.value.trim()!==_)return"stale";if(h=I.kind,I.kind!=="project_share_invite")return"other";const T=(I.projects??[]).map(A=>`${A.display_name} (${A.existing_memory_count} existing ${A.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${I.inviter_name||"A teammate"} invited you${I.team_name?` through ${I.team_name}`:""} to share ${T||"selected projects"}.`),m.value=Ti(I.recipient_name),v.value=Ti(I.device_name),u.hidden=!1,g=_,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project"};d?.addEventListener("input",()=>{b+=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(),R=Number(s.value);let I=!0;if(_?La(o):I=lo(o,"Team name is required."),!R||R<1?I=lo(s,"Must be at least 1 hour."):La(s),!!I){i.disabled=!0,i.textContent="Creating…";try{const T=await hm({group_id:_,policy:yn.invitePolicy,ttl_hours:R||24});C.lastTeamInvite=T,jf(),c.value=String(T.encoded||""),c.hidden=!1,c.focus(),c.select();const A=Array.isArray(T.warnings)?T.warnings:[];Z(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(T){Z(_t(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",_=>{Li(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){lo(d,"Paste a team invite or pairing payload.");return}if(La(d),g!==_){const I=b;try{const T=await w(_,I);if(T==="project"||T==="stale")return}catch{}if(I!==b||d.value.trim()!==_)return;g=_,l.textContent="Accept invite";return}const R=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(R){const I=T=>Ti(T)==="";if(I(R.recipient_name)){m&&lo(m,"Enter a human-readable name using 120 characters or fewer.");return}if(I(R.device_name)){v&&lo(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const I=await kl(_,R,h);C.lastTeamJoin=I;const T=I,A=typeof T.type=="string"?T.type:"team_join";let O;if(A==="pair"){const F=String(I.peer_device_id??"").trim();O={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=T.restart_required===!0||T.setup_state==="pending_inviter"||I.status==="pending_setup",N=typeof T.detail=="string"?T.detail.trim():"";O=F?{message:N||(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 O={message:I.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};C.syncJoinFlowFeedback=O,ol(),d.value="",g="",u&&(u.hidden=!0);try{await t()}catch(F){O={message:_t(F,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},C.syncJoinFlowFeedback=O,ol()}}catch(I){C.syncJoinFlowFeedback={message:_t(I,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},ol(),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 xl(),R=zw(_);Z(R.message,R.warning?"warning":void 0)}catch(_){Z(_t(_,"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 Mf({element:e,hidden:t=!1,restoreParent:n=null}){const r=B(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 mU({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(Mf,{element:e,hidden:!t,restoreParent:n}):null]})}function hU(){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=>Uo("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function gU({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(Mf,{element:e,hidden:!t,restoreParent:n}):null]})}function vU({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(Mf,{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(gU,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:o,onToggle:c}),a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:a(mU,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?a(hU,{}):null]})}function sl({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 cl({children:e}){return a("div",{className:"section-meta sync-section-note",children:e})}function yU({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 bU({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(oi,{feedback:o})]})}function _U({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(oi,{feedback:s})]})}function wU(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(sl,{label:"Needs attention"}):null,r?a(cl,{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(yU,{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 SU({children:e}){return e?a(z,{children:[a(sl,{label:"Add devices & teammates"}),a(cl,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function CU({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!C.syncDiscoveredFeedback?null:sn(a(z,{children:[a(sl,{count:t.length||void 0,label:"Devices waiting for review"}),a(cl,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),a(oi,{feedback:C.syncDiscoveredFeedback}),t.map(o=>a(_U,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function RU({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!C.syncJoinRequestsFeedback?null:sn(a(z,{children:[a(sl,{count:t.length||void 0,label:"Join requests to review"}),a(cl,{children:"Approve or deny requests here before those devices become part of the team."}),a(oi,{feedback:C.syncJoinRequestsFeedback}),t.map(i=>a(bU,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function CS(e){return a(z,{children:[a(wU,{...e}),a(SU,{children:e.children}),a(RU,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(CU,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function RS(e){e&&(e.textContent="")}function ll(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 IU(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function $a(){return IU()?"auto":"smooth"}var Ff="syncTeamActionsMount",kU="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function TU(e,t,n=!1){return e.length>1&&(!t||n)}function PU(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 NU(e,t){const n=document.createElement("div");n.id=Ff,e.appendChild(n),mt(n,y(CS,{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 IS(e,t){const n=document.getElementById(Ff);n&&(ao(n),n.remove()),RS(e),t.forEach(r=>{RS(r)})}function Oa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Of(),al(),jf(),ol(),uU();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");hr("syncTeamSkeleton"),pU();const p=C.lastSyncCoordinator,f=C.lastSyncViewModel||{primaryStatus:nS({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 U=document.getElementById("syncActorsList");U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:$a()}),ll(U));return}const S=String(E.deviceId||"").trim();if(!S)return;if(E.kind==="name-device"){const U=document.querySelector(`[data-device-name-input="${CSS.escape(S)}"]`);if(U instanceof HTMLInputElement){U.scrollIntoView({block:"center",behavior:$a()}),U.focus(),U.select(),ll(U);return}}const M=document.querySelector(`[data-peer-device-id="${CSS.escape(S)}"]`);if(M instanceof HTMLElement){M.scrollIntoView({block:"center",behavior:$a()}),ll(M);return}const H=document.querySelector(`[data-discovered-device-id="${CSS.escape(S)}"]`);H instanceof HTMLElement&&(H.scrollIntoView({block:"center",behavior:$a()}),ll(H))},v=async E=>{const S=Array.isArray(E.actorIds)?E.actorIds.map(oe=>String(oe||"").trim()).filter(Boolean):[],M=(Array.isArray(C.lastSyncActors)?C.lastSyncActors:[]).filter(oe=>S.includes(String(oe?.actor_id||"").trim()));if(M.length<2){Z("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const H=await dD({title:"Review possible duplicate people",summary:E.title.replace(/^Possible duplicate person:\s*/,""),actors:M.map(oe=>({actorId:String(oe?.actor_id||""),label:String(oe?.display_name||oe?.actor_id||"Unknown person"),isLocal:!!oe?.is_local}))});if(H.action==="different-people"){dq(S,"different-people"),Z("Okay. I will keep these people separate on this device."),await yn.loadSyncData();return}if(H.action!=="merge")return;const U=M.find(oe=>String(oe?.actor_id||"")===H.primaryActorId),re=M.find(oe=>String(oe?.actor_id||"")===H.secondaryActorId);if(!U?.actor_id||!re?.actor_id){Z("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await $m(String(U.actor_id),String(re.actor_id)),uq(S),Z(`Combined duplicate people into ${String(U.display_name||U.actor_id)}.`),await yn.loadSyncData()}catch(oe){try{await yn.loadSyncData()}catch{}Z(_t(oe,"Failed to combine these people."),"warning")}},g=async E=>await rp({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,b=ZB(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?PU(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!h){IS(n,[c,u]),t.hidden=!1,n.hidden=!1,NU(n,f.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const _=String(p.presence_status||""),R=Array.isArray(C.lastSyncPeers)?C.lastSyncPeers:[],I=Array.isArray(f.attentionItems)?f.attentionItems:[],T=Array.isArray(p.discovered_devices)?p.discovered_devices:[],A=String(p.coordinator_url||"").trim(),O=T.map(E=>{const S=String(E.device_id||"").trim(),M=String(E.display_name||"").trim(),H=Jw({coordinatorName:M,deviceId:S})||"Discovered device",U=S&&H!==S?S:null,re=String(E.fingerprint||"").trim(),oe=String(E.incoming_reciprocal_request_id||"").trim(),ie=Array.isArray(E.groups)?E.groups.map(tt=>String(tt||"").trim()).filter(Boolean):[],se=R.find(tt=>String(tt?.peer_device_id||"")===S),ue=TU(ie,!!se,E.needs_local_approval===!0),Pe=Kw({device:E,pairedLocally:!!se}),Ie=String(se?.fingerprint||"").trim(),le=!!se&&!!re&&!!Ie&&Ie!==re,ve=C.pendingCoordinatorApprovalsByDeviceId.get(S),X=E.needs_local_approval===!0&&ve?.coordinatorUrl===A&&ve?.incomingRequestId===oe,ce=X?"approval-pending":E.needs_local_approval===!0?"needs-local-approval":"not-required",be=!X&&!b&&_B({device:E,hasAmbiguousCoordinatorGroup:ue,pairedLocally:!!se}),fe=Array.isArray(E.addresses)?E.addresses:[],We=Number(E.address_count??0),he=Number.isFinite(We)&&We>0?We:0,W=[fe.length?fe.map(tt=>Ho()?dS(String(tt||"")):String(tt||"")).filter(Boolean).join(" · "):he>0?`${he} ${E.stale?"last-known":"fresh"} ${he===1?"address":"addresses"} hidden`:"No fresh addresses"];!fe.length&&U&&W.push(`device id: ${S}`);let de=null,ne=be?"accept":"none",xe=null;return le?ne="conflict":X?(de="Waiting for refreshed coordinator status. You do not need to approve again.",ne="approval-pending"):b&&(!se||Pe.state==="needs-your-approval")?(de=b.message,ne="setup-blocked"):ue?(de="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",ne="ambiguous"):se&&Sf(S)?(de="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",ne="scope-pending"):se?.last_error?(W.push(`error: ${String(se.last_error)}`),be||(ne="paired")):se?.status?.peer_state?(W.push(`status: ${String(se.status.peer_state)}`),be||(ne="paired")):!se&&E.stale?(de="Wait for a fresh coordinator presence update, then review this device again here.",ne="stale"):se&&!be&&(ne="paired"),ne==="paired"&&(xe=Pe.state==="waiting-for-other-device"?Pe.description||"Waiting on the other device.":String(se?.last_error||"").toLowerCase().includes("401")&&String(se?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:de,actionLabel:Pe.actionLabel||(se?"Review device":"Pair with this device"),approvalBadgeLabel:X?"Approval sent":Pe.badgeLabel,approvalState:ce,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:le?iS.conflicts:se?iS.pairedLocally:"Not connected on this device",coordinatorUrl:A,deviceId:S,displayName:H,displayTitle:U,fingerprint:re,groupId:ie[0]??"",incomingRequestId:oe,mode:ne,note:W.join(" · "),pairedMessage:xe}}),F=new Set(O.filter(E=>E.approvalState==="approval-pending").map(E=>E.deviceId)),N=I.filter(E=>!E.deviceId||!F.has(E.deviceId)),L=[],D=O.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),G=O.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,q=N.length+L.length+G;l&&(l.hidden=D.length===0&&!C.syncDiscoveredFeedback),d&&(d.textContent=D.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=L.length===0&&!C.syncJoinRequestsFeedback),IS(n,[c,u]);const $=document.createElement("div");$.id=Ff,n.appendChild($),mt($,y(CS,{actionItems:N,actionableCount:q,children:y(vU,{invitePanel:r,invitePanelOpen:yf,inviteRestoreParent:i,joinPanel:o,joinPanelOpen:bf,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(rq(!yf),Oa())},onToggleJoinPanel:()=>{o&&(iq(!bf),Oa())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:_}),discoveredListMount:u,discoveredRows:D,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:$a()}),Z(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}Z("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await hn({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 _m(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 yn.loadSyncData(),S}catch(S){return{message:_t(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 EU(E,S):null}catch(S){return{message:_t(S,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:L,presenceStatus:_,primaryStatus:f.primaryStatus}))}async function EU(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 XC(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."}],aq(e.deviceId);let u=n?{message:kU,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&&Oa();try{t.trim()!==l.trim()&&(await wm(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.":_t(p,"Device connected, but naming did not finish."),tone:"warning"}}C.syncDiscoveredFeedback=u;try{await yn.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":_t(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 AU(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 uo(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function kS(e){return uo(e)?"Unclear project identity":e.displayProject}function Ht(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function xU(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function DU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function LU(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function $U(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function OU(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 jU(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function MU({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"," · ",OU(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:jU(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 TS(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${DU(t)}\\b`,"g"),LU(t,n))),r}function FU(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 BU({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 qU({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,b]=x(""),[w,_]=x(null),R=r.length,I=e.totalGroupCount??R,T=r.filter(uo).length,A=r.filter(S=>S.suggestedScopeId&&!uo(S)&&Ht(S)).length,O=r.filter(S=>f[S.workspaceIdentity]&&Ht(S)).length,F=r.filter(S=>f[S.workspaceIdentity]&&Ht(S)&&!!u[S.workspaceIdentity]).length,N=r.filter(S=>{const M=uo(S);return v==="suggested"&&(!S.suggestedScopeId||M)||v==="cleanup"&&!M||v==="no-suggestion"&&(S.suggestedScopeId||M)||v==="selected"&&!f[S.workspaceIdentity]?!1:!h.trim()||FU(S,i).includes(h.trim().toLowerCase())});async function L(S){const M=u[S.workspaceIdentity]||S.suggestedScopeId||"";if(!(!M||!t||w)){_(S.workspaceIdentity),d(H=>{const U={...H};return delete U[S.workspaceIdentity],U});try{const H=await t(S,M,!!s[S.workspaceIdentity],s[S.workspaceIdentity]?.confirmation_token);c(H?U=>({...U,[S.workspaceIdentity]:H}):U=>{const re={...U};return delete re[S.workspaceIdentity],re})}catch(H){d(U=>({...U,[S.workspaceIdentity]:TS(H,M,i)}))}finally{_(null)}}}function D(S,M){p(H=>({...H,[S.workspaceIdentity]:M})),c(H=>{const U={...H};return delete U[S.workspaceIdentity],U}),d(H=>{const U={...H};return delete U[S.workspaceIdentity],U})}function G(S,M){m(H=>({...H,[S.workspaceIdentity]:M}))}function q(S){m(M=>({...M,...Object.fromEntries(N.filter(Ht).map(H=>[H.workspaceIdentity,S]))}))}function $(){m(S=>({...S,...Object.fromEntries(r.filter(M=>M.suggestedScopeId&&!uo(M)&&Ht(M)).map(M=>[M.workspaceIdentity,!0]))}))}async function E(){if(!t||w||F===0)return;const S=r.filter(M=>f[M.workspaceIdentity]&&Ht(M)&&!!u[M.workspaceIdentity]);if(!S.every(M=>s[M.workspaceIdentity])){_("bulk");try{for(const M of S){if(s[M.workspaceIdentity])continue;const H=u[M.workspaceIdentity]||M.suggestedScopeId||"";if(H)try{const U=await t(M,H,!1);d(re=>{const oe={...re};return delete oe[M.workspaceIdentity],oe}),U&&c(re=>({...re,[M.workspaceIdentity]:U}))}catch(U){d(re=>({...re,[M.workspaceIdentity]:TS(U,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:[I.toLocaleString()," older"," ",I===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<I?` Showing ${R.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 ${R.toLocaleString()}`],["suggested",`Suggested ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([S,M])=>a("button",{className:v===S?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>g(S),type:"button",children:M},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=>b(S.currentTarget.value),placeholder:"Search project, signal, or destination…",value:h}),a("button",{className:"settings-button",onClick:()=>q(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:$,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>q(!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]&&Ht(S)&&!!u[S.workspaceIdentity]).every(S=>s[S.workspaceIdentity]),onClick:()=>{E()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&O>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]&&Ht(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:N.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 ${kS(S)}`,checked:!!f[S.workspaceIdentity],className:"cm-checkbox",disabled:!Ht(S),onChange:M=>G(S,M.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:kS(S)}),a("div",{className:"legacy-review-group-meta",children:[AU(S.identitySource),xU(S,i)]}),Ht(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."}),uo(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(MU,{group:S}),i.length>0&&t&&Ht(S)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:w!=null,onChange:M=>D(S,M.currentTarget.value),value:u[S.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(M=>a("option",{value:M.scopeId,children:[M.label," · ",$U(M.authorityType),M.scopeId===S.suggestedScopeId?" · suggested":""]},M.scopeId))]})]}):null,i.length>0&&t&&Ht(S)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:w!=null||!u[S.workspaceIdentity],onClick:()=>{L(S)},children:w===S.workspaceIdentity?s[S.workspaceIdentity]?"Reassigning…":"Previewing…":s[S.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},S.workspaceIdentity))}):null]})}function UU({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(z,{children:[t?a(qU,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(BU,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function GU(){Kv("mine"),C.feedQuery="",window.location.hash="feed"}function HU(){window.location.hash="projects"}async function VU(e,t,n,r){try{const i=await DR({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return C.lastSyncLegacySharedReview=i.legacy_shared_review??null,Z(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),PS(),null}catch(i){if(i instanceof Cm)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Z(o,"warning"),new Error(o)}}function PS(){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){ao(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)}));mt(n,y(UU,{items:d,legacyReview:c,onLegacyReassign:VU,onLegacyReview:HU,onReview:GU}))}var dl="";function KU(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 zU(){return[...C.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var ja=null,Bf=0,qf=null,Uf=0,Gf=null,WU=15e3;function NS(e){return`project:${e||""}|includeJoinRequests:false`}function JU(e){const t=NS(e);return!ja||ja.key!==t||Date.now()>=ja.expiresAtMs?null:ja.payload}function YU(e,t){ja={key:NS(e),expiresAtMs:Date.now()+WU,payload:t}}function XU(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function QU(){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 ZU(e,t){if(C.activeTab==="health"&&!t.requireFreshSyncStatus){const r=JU(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!Ho();return{payload:await Il(n,e,{includeJoinRequests:!1}),fetchedFreshSyncStatus:!0}}function e2(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}function ul(e={}){const t=t2(++Bf,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1});return qf=t,t}async function t2(e,t){try{const n=C.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await ZU(n,t);let o=null,s=null,c=C.lastDeviceIdentityInventory,l=C.lastShareOperations,d=!1,u=!1,p=C.deviceIdentityInventoryLoadError,f=!1;const m=lq();try{o=await JC()}catch{d=!0}try{s=await Rl()}catch{u=!0}if(C.activeTab==="advanced"){p=!1;try{c=await Al()}catch{p=!0}}try{const R=await Lm();l=Array.isArray(R.items)?R.items:[]}catch{f=!0}if(e!==Bf)return qf??!1;const v=e2({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:C.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&YU(n,XU(r)),KU(r.coordinator);const g=JSON.stringify([r,o,s,c,p,l,f,m,zU()]);if(g===dl)return v;dl=g;const h=r.status&&typeof r.status=="object"?r.status:null;h&&(C.lastSyncStatus=h),Array.isArray(o?.items)?C.lastSyncActors=o.items:C.lastSyncActors=[];const b=Array.isArray(r.peers)?r.peers:[],w=new Set(b.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),_=Array.isArray(C.pendingAcceptedSyncPeers)?C.pendingAcceptedSyncPeers.filter(R=>{const I=String(R?.peer_device_id||"").trim();return I&&!w.has(I)}):[];return C.pendingAcceptedSyncPeers=_,C.lastSyncPeers=[...b,..._],p||(C.lastDeviceIdentityInventory=c),C.deviceIdentityInventoryLoadError=p,C.lastShareOperations=l,C.shareOperationsLoadError=f,C.lastSyncSharingReview=r.sharing_review||[],C.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,C.lastSyncCoordinator=r.coordinator||null,C.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,C.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],C.lastSyncAttempts=r.attempts||[],C.lastSyncLegacyDevices=r.legacy_devices||[],C.lastSyncDuplicatePersonDecisions=m,C.lastSyncViewModel=tq({actors:C.lastSyncActors,peers:C.lastSyncPeers,coordinator:C.lastSyncCoordinator,status:h,shareOperations:C.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:C.lastSyncDuplicatePersonDecisions}),mS(),Oa(),nU(),iU(),PS(),Lf(),wS(),fS(),V_(),d&&rU(),u&&(C.lastSyncCoordinatorAdminStatus=null,Oa()),v}catch{return e!==Bf?qf??!1:(dl="",C.deviceIdentityInventoryLoadError=!0,hr("syncTeamSkeleton"),hr("syncActorsSkeleton"),hr("syncPeersSkeleton"),hr("syncDiagSkeleton"),QU(),oU(),yq(),!1)}}function n2(){dl="",C.lastSyncPeers?.length&&Lf()}async function pl(){await ul()}function r2(){const e=i2(++Uf);return Gf=e,e}async function i2(e){try{const t=await YC();return e!==Uf?Gf??!1:(C.pairingPayloadRaw=t||null,Pf(),!0)}catch{return e!==Uf?Gf??!1:(C.pairingPayloadRaw=null,Pf(),!1)}}function o2(e){QF(),fc(),lU(pl),tU(pl),Sq(Lf),fU(e,pl),aU(pl),Cq(e),$f(),cU()}function a2(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 s2(){try{const e=await BC();if(!e?.version)return;a2(e.version,"a3f0d7f")}catch{}}var Hf=null,ES=1500,AS="codemem-legacy-upgrade-notice-dismissed",vr=null,nn=!1,fl=!1,Vf=!1,Ma=null;function xS(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function DS(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=xS(n.total_group_count,r.length),o=xS(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function LS(){try{return localStorage.getItem(AS)==="1"}catch{return!1}}function ml(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(AS,"1")}catch{}}function $S(){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 c2(){const e=$S(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function OS(e){const t=Le("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),ml(),Fa(!1);return}if(e.key==="Enter"){const o=Le("legacyUpgradeReviewGroups");Li(e,{onSubmit:()=>o?.click(),disabled:!o||o.disabled});return}if(e.key!=="Tab")return;const n=$S();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 jS(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 Fa(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){Ma=document.activeElement,document.addEventListener("keydown",OS),c2(),jS(!0);return}jS(!1),document.removeEventListener("keydown",OS),Ma&&document.contains(Ma)&&Ma.focus(),Ma=null}}function MS(e){!e||Vf||LS()||(Vf=!0,uv(()=>Fa(!0,e)))}async function l2(){if(!(Vf||LS()))try{MS(DS(await Il(!1,"",{includeJoinRequests:!1})))}catch{}}function ai(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 Kf(){try{return await FC(),!0}catch{return!1}}function d2(){return document.visibilityState!=="hidden"&&!Ow()}function FS(){return`${C.activeTab}:${C.advancedSection}:${C.syncPairingOpen}`}function u2(e){C.refreshQueued||e.surface!==FS()||!e.refreshSucceeded||!fl||nn||(fl=!1,Ld("connection_restored"))}function BS(){if(nn)return;nn=!0,fl=!0,Ld("connection_lost"),zf(),uv(),si("error","(reconnecting)"),ai(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Kf()){if(vr&&(clearTimeout(vr),vr=null),nn=!1,ai(!0,"Viewer responded. Restoring your session…"),d2()){si("refreshing"),Ba();try{await hl()}catch{}}else si("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");nn||ai(!1);return}ai(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),vr=setTimeout(e,ES)};vr=setTimeout(e,ES)}function si(e,t){C.refreshState=e;const n=Le("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=Le("refreshAnnouncer");!s||Hf===e||(s.textContent=o,Hf=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}`,Hf=null}function zf(){C.refreshTimer&&(clearInterval(C.refreshTimer),C.refreshTimer=null)}function Ba(){C.refreshTimer||(C.refreshTimer=setInterval(()=>yr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(zf(),si("paused","(tab hidden)")):!Ow()&&!nn&&(Ba(),yr())});function qS(){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(/^#/,"");$f(o==="sync/diagnostics"||o==="advanced/sync/diagnostics"?"diagnostics":"main")})}var p2=rE();function US(e){const t=new Set(KN(C.lastCoordinatorAdminStatus));Dr.forEach(r=>{const i=Le(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),Dr.forEach(r=>{const i=Le(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=Le(`tabBtn-${e}`);n&&p2(n),qS()}function ci(e,t={}){const n=Go(e,C.lastCoordinatorAdminStatus);n==="advanced"&&ru(t.advancedSection??nu()??C.advancedSection),Vv(n,t.canonicalHash?{canonicalHash:!0}:{}),US(n),yr()}function f2(){Dr.forEach(e=>{Le(`tabBtn-${e}`)?.addEventListener("click",()=>ci(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Le("advancedSyncButton")?.addEventListener("click",()=>ru("sync",!0)),Le("advancedTeamsButton")?.addEventListener("click",()=>{ru("teams",!0),qS(),queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}),Le("coordinatorAdminOpenSharing")?.addEventListener("click",()=>{ci("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=tu();if(e){const t=nu();ci(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}}),ci(C.activeTab)}async function m2(){try{const e=await Va();C.knownProjects=e,n2();const t=Zd("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 h2(e){C.pendingDeviceIdentityFocus=e?.trim()||null,ci("devices",{canonicalHash:!0})}var qa=qT({},{onOpenTeamSetup:cw,onReviewDevices:h2}),GS={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Wf=0,Jf=null,Vt=null;async function g2(){const e=[];let t=0;for(;;){const n=await bo({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return ys(e)}function v2(){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=Da(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function y2(){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 HS(e){if(e==="advanced_sync"){ci("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}ci(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function Yf(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=b2(e,++Wf);return Jf=t,t}async function b2(e,t){Vt||bc(e,GS,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,o,s]=await Promise.all([g2(),El(),vR(),Al().then(u=>({inventory:u,unavailable:!1})).catch(()=>({inventory:Vt?.inventory,unavailable:!0})),ul({requiredSurface:"devices"})]);if(t!==Wf)return Jf??!1;const c=v2(),l=y2(),d=Om(C.lastSyncStatus);return!o.unavailable&&o.inventory&&(C.lastDeviceIdentityInventory=o.inventory),C.deviceIdentityInventoryLoadError=o.unavailable,bc(e,r,i,n,c,{inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:d,onCommitted:async()=>{const[u,p]=await Promise.all([Yf(),qa()]);return u&&p},onNavigate:HS,peerRuntimeMetadata:l}),Vt={projects:n,intent:r,reconciliation:i,availability:c,peerRuntimeMetadata:l,inventory:o.inventory,inventoryUnavailable:o.unavailable,coordinatorEnrollmentIssueCount:d},s}catch{return t!==Wf?Jf??!1:(Vt?bc(e,Vt.intent,Vt.reconciliation,Vt.projects,Vt.availability,{coordinatorEnrollmentIssueCount:Vt.coordinatorEnrollmentIssueCount,inventory:Vt.inventory,inventoryUnavailable:Vt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Yf(),qa()]);return n&&r},onNavigate:HS,peerRuntimeMetadata:Vt.peerRuntimeMetadata,refreshError:!0}):bc(e,GS,{version:1,items:[]},[],[],{loadError:!0}),!1)}}Zd("projectFilter")?.addEventListener("change",()=>{C.currentProject=Zd("projectFilter")?.value||"",Qr(!0),yr()});var Xf=null;async function _2(){await Promise.all([iM(),vF(),HP().catch(()=>{})])}function w2(e,t,n){if(t==="feed"){const o=qD();e.push(hb(o),zp())}if(t==="projects"&&e.push(Na().then(n)),t==="sharing"&&e.push(qa().then(n)),t==="devices"&&e.push(Yf().then(n)),t==="health"&&e.push(ul({requiredSurface:"health",requireFreshSyncStatus:fl}).then(n)),t==="advanced"&&C.advancedSection==="sync"&&e.push(ul().then(n)),t==="advanced"&&C.advancedSection==="teams"&&e.push(gc().then(n)),!C.syncPairingOpen)return;const r=t==="advanced"&&C.advancedSection==="sync",i=r2();e.push(r?i.then(n):i)}async function yr(){nn||(Xf&&clearTimeout(Xf),Xf=setTimeout(()=>hl(),80))}async function hl(){if(!nn){if(C.refreshInFlight){C.refreshQueued=!0;return}C.refreshInFlight=!0;try{si("refreshing");const e=C.activeTab,t=FS(),n=[_2()];let r=!0;w2(n,e,o=>{r=r&&o}),await Promise.all(n),MS(DS(C.lastSyncLegacySharedReview));const i=Go(C.activeTab,C.lastCoordinatorAdminStatus);i!==C.activeTab&&Vv(i),US(C.activeTab),si(r?"idle":"error"),u2({refreshSucceeded:r,surface:t})}catch{await Kf()?si("error"):BS()}finally{C.refreshInFlight=!1,C.refreshQueued&&!nn&&(C.refreshQueued=!1,hl())}}}tE();var VS=document.getElementById("toastRoot");VS&&ON(VS);var KS=document.getElementById("diagnosticsDrawerMount");KS&&GP(KS);var zS=document.getElementById("legacyTeamSetupMount");zS&&e1(zS,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(C.activeTab==="sharing"?(t=await Na(n),e=await qa(n)):(e=await qa(n),t=await Na(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),iE(js("themeToggle")),Jv(ou()),f2(),Fj(),VP(),q1(()=>yr(),{onOpenTeamSetup:cw}),o2(()=>yr()),WD(),YF(zf,Ba,()=>yr()),m2(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Ld("reconnect_requested"),ai(!0,"Checking whether the viewer server is back…"),!await Kf()){BS();return}vr&&(clearTimeout(vr),vr=null),nn=!1,ai(!0,"Viewer responded. Restoring your session…"),Ba();try{await hl()}catch{}nn||ai(!1)}),Le("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{ml(),Fa(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Le("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{ml(),Fa(!1),window.location.hash="projects"}),Le("legacyUpgradeNotNow")?.addEventListener("click",()=>{ml(),Fa(!1)}),s2(),l2(),yr(),Ba()})();
|