@codemem/server 0.43.0 → 0.43.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/helpers.d.ts +11 -0
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6549 -6190
- package/dist/index.js.map +1 -1
- package/dist/routes/raw-events.d.ts.map +1 -1
- package/dist/routes/sync.d.ts +8 -4
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/team-setup-view.d.ts +212 -0
- package/dist/routes/team-setup-view.d.ts.map +1 -0
- package/dist/routes/team-setup.d.ts +19 -134
- package/dist/routes/team-setup.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +43 -43
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +313 -20
package/static/app.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
(function(){var vp=Object.defineProperty,Pw=(e,t)=>{let n={};for(var r in e)vp(n,r,{get:e[r],enumerable:!0});return t||vp(n,Symbol.toStringTag,{value:"Module"}),n};function ye(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function $e(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function _e(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function yp(e,t,n,r,i){const a=new URLSearchParams;return a.set("project",e||""),typeof t=="number"&&a.set("limit",String(t)),typeof n=="number"&&a.set("offset",String(n)),r&&a.set("scope",r),i&&a.set("q",i),a.toString()}async function Aw(){return $e("/api/observer-status")}async function xw(){return $e("/api/config")}async function Rw(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=ye(r)||n||"request failed";throw new Error(i)}return r}async function Qa(){return $e("/api/coordinator/admin/status")}async function bp(e){return $e(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function Dw(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Lw(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function $w(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Mw(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Ow(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return $e(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function jw(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Fw(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return $e(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function Bw(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:a}=await _e(r);if(!r.ok)throw new Error(ye(a)||i||"request failed");return a}async function Uw(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await _e(i);if(!i.ok)throw new Error(ye(s)||a||"request failed");return s}async function Gw(e){const t=new URLSearchParams;return e&&t.set("group_id",e),$e(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function _p(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),$e(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function qw(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Hw(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:a}=await _e(r);if(!r.ok)throw new Error(ye(a)||i||"request failed");return a}async function Kw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Vw(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Ww(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function wp(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Sp(e,t){return $e(`/api/observations?${yp(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function zw(e,t){const n=await fetch("/api/memories/visibility",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({memory_id:e,visibility:t})}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Jw(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Yw(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Cp(e,t){return $e(`/api/summaries?${yp(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function Xw(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Qw(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 Zw(){return $e("/api/runtime")}async function Za(){return(await $e("/api/projects")).projects||[]}async function eS(){return $e("/api/stats")}async function tS(e){return $e(`/api/usage?project=${encodeURIComponent(e)}`)}async function nS(e){return $e(`/api/session?project=${encodeURIComponent(e)}`)}async function rS(e){return $e(`/api/raw-events?project=${encodeURIComponent(e)}`)}async function eo(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),$e(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function vc(e,t){const n=await fetch("/api/sync/invites/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invite:e,...t})}),{text:r,payload:i}=await _e(n);if(!n.ok){const a=typeof i?.detail=="string"?i.detail.trim():"";throw new Error(a||ye(i)||r||"request failed")}return i}async function Tp(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function iS(){return $e("/api/sync/actors")}async function aS(e=!1){return $e(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function Np(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Ip(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function oS(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let a={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(a=c)}catch{a={}}const s=typeof a.detail=="string"?a.detail:void 0;if(!r.ok)throw new Error(s||ye(a)||i||"request failed");return a}var kp=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},to=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??[]}},Ep=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},yc=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},no=1,Pp=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_failed"]),sS=new Set(["needs_setup","in_progress","stale","ready"]),Ap=new Set(["needs_setup","in_progress","stale","completed"]);function tt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tn(e){return typeof e=="string"||e===null}function nn(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Ft(e,t){return Array.isArray(e)&&e.every(t)}function xp(e){return tt(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&sS.has(e.status)&&nn(e.deviceCount)&&nn(e.projectCount)&&nn(e.unresolvedDeviceCount)&&nn(e.unresolvedProjectCount):!1}function cS(e){return tt(e)&&e.version===no&&Ft(e.candidates,xp)}function lS(e){return tt(e)?e.kind==="absent"||e.kind==="existing"&&nn(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function dS(e){return tt(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&tn(e.existingIdentityRef)&&tn(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&tn(e.targetIdentityRef)&&lS(e.expectation):!1}function uS(e){return tt(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&tn(e.canonicalProjectRef)&&tn(e.resolvedProjectRef)&&Ft(e.mappingChoices,t=>tt(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string"):!1}function pS(e){if(!tt(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return Ft(e.teamChanges,n=>tt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&t(n.change)&&[null,"person_all_devices","reviewed_allowlist"].includes(n.fromDeviceEligibilityMode)&&n.toDeviceEligibilityMode==="reviewed_allowlist")&&Ft(e.membershipChanges,n=>tt(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&Ft(e.projectChanges,n=>tt(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&tn(n.fromResolvedProjectRef)&&tn(n.fromResolvedProjectDisplayName)&&tn(n.toResolvedProjectRef)&&tn(n.toResolvedProjectDisplayName)&&t(n.change))&&Ft(e.recipientChanges,n=>tt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&n.recipientKind==="team"&&typeof n.recipientRef=="string"&&typeof n.recipientDisplayName=="string"&&t(n.change))&&Ft(e.deviceAccessChanges,n=>tt(n)&&typeof n.canonicalProjectRef=="string"&&typeof n.canonicalProjectDisplayName=="string"&&typeof n.deviceRef=="string"&&typeof n.deviceDisplayName=="string"&&typeof n.change=="string"&&["add","remove"].includes(n.change))}function mS(e){return!tt(e)||!(e.version===no&&xp(e.candidate)&&typeof e.attemptId=="string"&&typeof e.draftState=="string"&&Ap.has(e.draftState)&&nn(e.unresolvedDeviceCount)&&nn(e.unresolvedProjectCount)&&Ft(e.devices,dS)&&Ft(e.projects,uS)&&Ft(e.identityChoices,t=>tt(t)&&typeof t.identityRef=="string"&&typeof t.displayName=="string"))?!1:e.canFinish===!0?e.conflictState===null&&typeof e.finishDigest=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.viewerAccessDeltaDigest=="string"&&pS(e.accessDelta):e.canFinish===!1&&(e.conflictState===null||typeof e.conflictState=="string"&&Pp.has(e.conflictState))}function Ai(e){return tt(e)&&e.version===no&&typeof e.candidateRef=="string"&&typeof e.attemptId=="string"&&typeof e.draftState=="string"&&Ap.has(e.draftState)&&typeof e.canFinish=="boolean"&&nn(e.unresolvedDeviceCount)&&nn(e.unresolvedProjectCount)}function fS(e){return tt(e)&&e.version===no&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var Bt=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="LegacyTeamSetupApiError"}};function _n(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function wn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new Bt(0,"team_setup_failed")}let i;try{const a=await r.text();if(!a)throw new Error("empty Team setup response");i=JSON.parse(a)}catch{throw new Bt(r.status,"team_setup_failed")}if(!r.ok){const a=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=Pp.has(a)?a:"team_setup_failed";throw new Bt(r.status,s)}if(!t(i))throw new Bt(r.status,"team_setup_failed");return i}function Ar(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function Rp(){return wn(_n(),cS)}function hS(e){return wn(_n(e),mS)}function gS(e,t,n){return wn(`${_n(e)}/devices/${encodeURIComponent(t)}/assignment`,Ai,Ar("PUT",n))}function vS(e,t,n){return wn(`${_n(e)}/devices/${encodeURIComponent(t)}/decision`,Ai,Ar("PUT",n))}function yS(e,t,n){return wn(`${_n(e)}/devices/${encodeURIComponent(t)}/decision`,Ai,Ar("DELETE",n))}function bS(e,t,n){return wn(`${_n(e)}/projects/${encodeURIComponent(t)}/mapping`,Ai,Ar("PUT",n))}function _S(e){return wn(`${_n(e)}/refresh`,Ai,Ar("POST",{}))}function wS(e,t){return wn(`${_n(e)}/finish`,fS,Ar("POST",t))}var bc=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function _c(){return $e("/api/sync/recipient-policy/v1/intent")}function wc(){return $e("/api/sync/recipient-policy/v1/device-inventory")}async function Dp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok){const a=i?.errorCode||i?.error||ye(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new yc(n.status,a,s)}return i}function Lp(e){return Dp("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function $p(e){return Dp("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function SS(){return $e("/api/sync/recipient-policy/v1/reconciliation-status")}async function Mp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new bc(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const a=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(a||ye(i)||r||"request failed")}return i}function CS(e){return Mp("/api/sync/recipient-policy/v1/edges/preview",e)}function TS(e){return Mp("/api/sync/recipient-policy/v1/edges/commit",e)}async function Op(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}function NS(e){return Op("/api/sync/recipient-policy/v1/invites/preview",e)}function IS(e){return Op("/api/sync/recipient-policy/v1/invites",e)}async function kS(){const e=await $e("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function ES(){return $e("/api/sync/sharing-domains/settings")}async function ro(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 $e(`/api/sync/projects${n?`?${n}`:""}`)}async function jp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}function PS(e){return jp("/api/sync/project-invites/preview",e)}function AS(e){return jp("/api/sync/project-invites",e)}function Fp(){return $e("/api/sync/share-operations")}function xS(e){return $e(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function RS(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function DS(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 _e(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new to(r):new Error(ye(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 LS(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 _e(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new to(r):new Error(ye(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function $S(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return!!r?.deleted}async function MS(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function OS(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 _e(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new kp(r.preview):new Error(ye(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function jS(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 _e(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new Ep(r.preview):new Error(ye(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function FS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function BS(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");const a=i?.preferences;if(!a)throw new Error("response missing preferences");return a}async function US(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function GS(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function Bp(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 _e(n);if(!n.ok)throw new Error(ye(i)||r||"request failed");return i}async function qS(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function HS(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 _e(t);if(!t.ok)throw new Error(ye(r)||n||"request failed");return r}async function Sc(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await _e(i);if(!i.ok)throw new Error(ye(s)||a||"request failed");if(!a)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(a||"invalid sync response");return s}async function KS(){return $e("/api/update-status")}function VS(e){return{current_version:"unknown",latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function io(e){return e!==null&&typeof e=="object"?e:null}function Up(e){const t=io(e),n=io(t?.status),r=io(io(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var xi,he,Gp,qp,Sn,Hp,Kp,Vp,Cc,ao,Ri,Wp,Tc,Nc,Ic,zp,oo={},so=[],WS=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Di=Array.isArray;function Ut(e,t){for(var n in t)e[n]=t[n];return e}function kc(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function y(e,t,n){var r,i,a,s={};for(a in t)a=="key"?r=t[a]:a=="ref"?i=t[a]:s[a]=t[a];if(arguments.length>2&&(s.children=arguments.length>3?xi.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(a in e.defaultProps)s[a]===void 0&&(s[a]=e.defaultProps[a]);return Li(e,s,r,i,null)}function Li(e,t,n,r,i){var a={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Gp,__i:-1,__u:0};return i==null&&he.vnode!=null&&he.vnode(a),a}function Jp(){return{current:null}}function Z(e){return e.children}function Ct(e,t){this.props=e,this.context=t}function xr(e,t){if(t==null)return e.__?xr(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"?xr(e):null}function zS(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],a=Ut({},t);a.__v=t.__v+1,he.vnode&&he.vnode(a),Pc(e.__P,a,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??xr(t),!!(32&t.__u),i),a.__v=t.__v,a.__.__k[a.__i]=a,tm(r,a,i),t.__e=t.__=null,a.__e!=n&&Yp(a)}}function Yp(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}),Yp(e)}function Ec(e){(!e.__d&&(e.__d=!0)&&Sn.push(e)&&!co.__r++||Hp!=he.debounceRendering)&&((Hp=he.debounceRendering)||Kp)(co)}function co(){try{for(var e,t=1;Sn.length;)Sn.length>t&&Sn.sort(Vp),e=Sn.shift(),t=Sn.length,zS(e)}finally{Sn.length=co.__r=0}}function Xp(e,t,n,r,i,a,s,c,l,d,u){var p,m,f,g,h,v,b,_=r&&r.__k||so,S=t.length;for(l=JS(n,t,_,l,S),p=0;p<S;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&_[f.__i]||oo,f.__i=p,v=Pc(e,f,m,i,a,s,c,l,d,u),g=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&xc(m.ref,null,f),u.push(f.ref,f.__c||g,f)),h==null&&g!=null&&(h=g),(b=!!(4&f.__u))||m.__k===f.__k?(l=Qp(f,l,e,b),b&&m.__e&&(m.__e=null)):typeof f.type=="function"&&v!==void 0?l=v:g&&(l=g.nextSibling),f.__u&=-7);return n.__e=h,l}function JS(e,t,n,r,i){var a,s,c,l,d,u=n.length,p=u,m=0;for(e.__k=new Array(i),a=0;a<i;a++)(s=t[a])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[a]=Li(null,s,null,null,null):Di(s)?s=e.__k[a]=Li(Z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[a]=Li(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[a]=s,l=a+m,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=YS(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?m--:d==l+1?m++:(d>l?m--:m++,s.__u|=4))):e.__k[a]=null;if(p)for(a=0;a<u;a++)(c=n[a])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=xr(c)),rm(c,c));return r}function Qp(e,t,n,r){var i,a;if(typeof e.type=="function"){for(i=e.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=e,t=Qp(i[a],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=xr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function rn(e,t){return t=t||[],e==null||typeof e=="boolean"||(Di(e)?e.some(function(n){rn(n,t)}):t.push(e)),t}function YS(e,t,n,r){var i,a,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,a=n+1;i>=0||a<t.length;)if((d=t[s=i>=0?i--:a++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function Zp(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||WS.test(t)?n:n+"px"}function lo(e,t,n,r,i){var a,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Zp(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Zp(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")a=t!=(t=t.replace(Wp,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+a]=n,n?r?n[Ri]=r[Ri]:(n[Ri]=Tc,e.addEventListener(t,a?Ic:Nc,a)):e.removeEventListener(t,a?Ic:Nc,a);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function em(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ao]==null)t[ao]=Tc++;else if(t[ao]<n[Ri])return;return n(he.event?he.event(t):t)}}}function Pc(e,t,n,r,i,a,s,c,l,d){var u,p,m,f,g,h,v,b,_,S,C,N,E,A,M,U=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),a=[c=t.__e=n.__e]),(u=he.__b)&&u(t);e:if(typeof U=="function")try{if(b=t.props,_=U.prototype&&U.prototype.render,S=(u=U.contextType)&&r[u.__c],C=u?S?S.props.value:u.__:r,n.__c?v=(p=t.__c=n.__c).__=p.__E:(_?t.__c=p=new U(b,C):(t.__c=p=new Ct(b,C),p.constructor=U,p.render=QS),S&&S.sub(p),p.state||(p.state={}),p.__n=r,m=p.__d=!0,p.__h=[],p._sb=[]),_&&p.__s==null&&(p.__s=p.state),_&&U.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ut({},p.__s)),Ut(p.__s,U.getDerivedStateFromProps(b,p.__s))),f=p.props,g=p.state,p.__v=t,m)_&&U.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),_&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(_&&U.getDerivedStateFromProps==null&&b!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,C),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,C)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(k){k&&(k.__=t)}),so.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,C),_&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,g,h)})}if(p.context=C,p.props=b,p.__P=e,p.__e=!1,N=he.__r,E=0,_)p.state=p.__s,p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),so.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++E<25);p.state=p.__s,p.getChildContext!=null&&(r=Ut(Ut({},r),p.getChildContext())),_&&!m&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(f,g)),A=u!=null&&u.type===Z&&u.key==null?nm(u.props.children):u,c=Xp(e,Di(A)?A:[A],t,n,r,i,a,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),v&&(p.__E=p.__=null)}catch(k){if(t.__v=null,l||a!=null)if(k.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;a[a.indexOf(c)]=null,t.__e=c}else{for(M=a.length;M--;)kc(a[M]);Ac(t)}else t.__e=n.__e,t.__k=n.__k,k.then||Ac(t);he.__e(k,t,n)}else a==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=XS(n.__e,t,n,r,i,a,s,l,d);return(u=he.diffed)&&u(t),128&t.__u?void 0:c}function Ac(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Ac))}function tm(e,t,n){for(var r=0;r<n.length;r++)xc(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(a){a.call(i)})}catch(a){he.__e(a,i.__v)}})}function nm(e){return typeof e!="object"||e==null||e.__b>0?e:Di(e)?e.map(nm):e.constructor!==void 0?null:Ut({},e)}function XS(e,t,n,r,i,a,s,c,l){var d,u,p,m,f,g,h,v=n.props||oo,b=t.props,_=t.type;if(_=="svg"?i="http://www.w3.org/2000/svg":_=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),a!=null){for(d=0;d<a.length;d++)if((f=a[d])&&"setAttribute"in f==!!_&&(_?f.localName==_:f.nodeType==3)){e=f,a[d]=null;break}}if(e==null){if(_==null)return document.createTextNode(b);e=document.createElementNS(i,_,b.is&&b),c&&(he.__m&&he.__m(t,a),c=!1),a=null}if(_==null)v===b||c&&e.data==b||(e.data=b);else{if(a=_=="textarea"&&b.defaultValue!=null?null:a&&xi.call(e.childNodes),!c&&a!=null)for(v={},d=0;d<e.attributes.length;d++)v[(f=e.attributes[d]).name]=f.value;for(d in v)f=v[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||lo(e,d,null,f,i);for(d in b)f=b[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?g=f:d=="checked"?h=f:c&&typeof f!="function"||v[d]===f||lo(e,d,f,v[d],i);if(u)c||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),Xp(t.type=="template"?e.content:e,Di(m)?m:[m],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":i,a,s,a?a[0]:n.__k&&xr(n,0),c,l),a!=null)for(d=a.length;d--;)kc(a[d]);c&&_!="textarea"||(d="value",_=="progress"&&g==null?e.removeAttribute("value"):g!=null&&(g!==e[d]||_=="progress"&&!g||_=="option"&&g!=v[d])&&lo(e,d,g,v[d],i),d="checked",h!=null&&h!=e[d]&&lo(e,d,h,v[d],i))}return e}function xc(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 rm(e,t,n){var r,i;if(he.unmount&&he.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||xc(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(a){he.__e(a,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&rm(r[i],t,n||typeof e.type!="function");n||kc(e.__e),e.__c=e.__=e.__e=void 0}function QS(e,t,n){return this.constructor(e,n)}function Ge(e,t,n){var r,i,a,s;t==document&&(t=document.documentElement),he.__&&he.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,a=[],s=[],Pc(t,e=(!r&&n||t).__k=y(Z,null,[e]),i||oo,oo,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?xi.call(t.childNodes):null,a,!r&&n?n:i?i.__e:t.firstChild,r,s),tm(a,e,s)}function im(e,t){Ge(e,t,im)}function ZS(e,t,n){var r,i,a,s,c=Ut({},e.props);for(a in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)a=="key"?r=t[a]:a=="ref"?i=t[a]:c[a]=t[a]===void 0&&s!=null?s[a]:t[a];return arguments.length>2&&(c.children=arguments.length>3?xi.call(arguments,2):n),Li(e.type,c,r||e.key,i||e.ref,null)}function Wn(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(a){this.props.value!=a.value&&r.forEach(function(s){s.__e=!0,Ec(s)})},this.sub=function(a){r.add(a);var s=a.componentWillUnmount;a.componentWillUnmount=function(){r&&r.delete(a),s&&s.call(a)}}),n.children}return t.__c="__cC"+zp++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}xi=so.slice,he={__e:function(e,t,n,r){for(var i,a,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((a=i.constructor)&&a.getDerivedStateFromError!=null&&(i.setState(a.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Gp=0,qp=function(e){return e!=null&&e.constructor===void 0},Ct.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ut({},this.state);typeof e=="function"&&(e=e(Ut({},n),this.props)),e&&Ut(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ec(this))},Ct.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ec(this))},Ct.prototype.render=Z,Sn=[],Kp=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Vp=function(e,t){return e.__v.__b-t.__v.__b},co.__r=0,Cc=Math.random().toString(8),ao="__d"+Cc,Ri="__a"+Cc,Wp=/(PointerCapture)$|Capture$/i,Tc=0,Nc=em(!1),Ic=em(!0),zp=0;var an,je,Rc,am,Rr=0,om=[],qe=he,sm=qe.__b,cm=qe.__r,lm=qe.diffed,dm=qe.__c,um=qe.unmount,pm=qe.__;function zn(e,t){qe.__h&&qe.__h(je,e,Rr||t),Rr=0;var n=je.__H||(je.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function x(e){return Rr=1,$i(fm,e)}function $i(e,t,n){var r=zn(an++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):fm(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=je,!je.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!a||a.call(this,c,l,d);var p=r.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),a&&a.call(this,c,l,d)||p};je.__f=!0;var a=je.shouldComponentUpdate,s=je.componentWillUpdate;je.componentWillUpdate=function(c,l,d){if(this.__e){var u=a;a=void 0,i(c,l,d),a=u}s&&s.call(this,c,l,d)},je.shouldComponentUpdate=i}return r.__N||r.__}function z(e,t){var n=zn(an++,3);!qe.__s&&$c(n.__H,t)&&(n.__=e,n.u=t,je.__H.__h.push(n))}function yt(e,t){var n=zn(an++,4);!qe.__s&&$c(n.__H,t)&&(n.__=e,n.u=t,je.__h.push(n))}function G(e){return Rr=5,xe(function(){return{current:e}},[])}function uo(e,t,n){Rr=6,yt(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 xe(e,t){var n=zn(an++,7);return $c(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ce(e,t){return Rr=8,xe(function(){return e},t)}function Cn(e){var t=je.context[e.__c],n=zn(an++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(je)),t.props.value):e.__}function Dc(e,t){qe.useDebugValue&&qe.useDebugValue(t?t(e):e)}function eC(e){var t=zn(an++,10),n=x();return t.__=e,je.componentDidCatch||(je.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Dr(){var e=zn(an++,11);if(!e.__){for(var t=je.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function tC(){for(var e;e=om.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(po),t.__h.some(Lc),t.__h=[]}catch(n){t.__h=[],qe.__e(n,e.__v)}}}qe.__b=function(e){je=null,sm&&sm(e)},qe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),pm&&pm(e,t)},qe.__r=function(e){cm&&cm(e),an=0;var t=(je=e.__c).__H;t&&(Rc===je?(t.__h=[],je.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(po),t.__h.some(Lc),t.__h=[],an=0)),Rc=je},qe.diffed=function(e){lm&&lm(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(om.push(t)!==1&&am===qe.requestAnimationFrame||((am=qe.requestAnimationFrame)||nC)(tC)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Rc=je=null},qe.__c=function(e,t){t.some(function(n){try{n.__h.some(po),n.__h=n.__h.filter(function(r){return!r.__||Lc(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],qe.__e(r,n.__v)}}),dm&&dm(e,t)},qe.unmount=function(e){um&&um(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{po(r)}catch(i){t=i}}),n.__H=void 0,t&&qe.__e(t,n.__v))};var mm=typeof requestAnimationFrame=="function";function nC(e){var t,n=function(){clearTimeout(r),mm&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);mm&&(t=requestAnimationFrame(n))}function po(e){var t=je,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),je=t}function Lc(e){var t=je;e.__c=e.__(),je=t}function $c(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function fm(e,t){return typeof t=="function"?t(e):t}var B1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,rC=0,U1=Array.isArray;function o(e,t,n,r,i,a){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--rC,__i:-1,__u:0,__source:i,__self:a};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return he.vnode&&he.vnode(d),d}function Mi({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:a="Close"}){return o("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[o("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),o("span",{className:"modal-close-button-label",children:a})]})}var hm=Pw({Children:()=>Gt,Component:()=>Ct,Fragment:()=>Z,PureComponent:()=>mo,StrictMode:()=>Z,Suspense:()=>Oi,SuspenseList:()=>Lr,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>Dm,cloneElement:()=>$r,createContext:()=>Wn,createElement:()=>y,createFactory:()=>Lm,createPortal:()=>on,createRef:()=>Jp,default:()=>cn,findDOMNode:()=>jm,flushSync:()=>fo,forwardRef:()=>V,hydrate:()=>Em,isElement:()=>Bm,isFragment:()=>$m,isMemo:()=>Mm,isValidElement:()=>sn,lazy:()=>Tm,memo:()=>vm,render:()=>km,startTransition:()=>Fc,unmountComponentAtNode:()=>Om,unstable_batchedUpdates:()=>Fm,useCallback:()=>ce,useContext:()=>Cn,useDebugValue:()=>Dc,useDeferredValue:()=>Bc,useEffect:()=>z,useErrorBoundary:()=>eC,useId:()=>Dr,useImperativeHandle:()=>uo,useInsertionEffect:()=>Gc,useLayoutEffect:()=>yt,useMemo:()=>xe,useReducer:()=>$i,useRef:()=>G,useState:()=>x,useSyncExternalStore:()=>Oc,useTransition:()=>Uc,version:()=>fC});function gm(e,t){for(var n in t)e[n]=t[n];return e}function Mc(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 Oc(e,t){var n=t(),r=x({t:{__:n,u:t}}),i=r[0].t,a=r[1];return yt(function(){i.__=n,i.u=t,jc(i)&&a({t:i})},[e,n,t]),z(function(){return jc(i)&&a({t:i}),e(function(){jc(i)&&a({t:i})})},[e]),n}function jc(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 Fc(e){e()}function Bc(e){return e}function Uc(){return[!1,Fc]}var Gc=yt;function mo(e,t){this.props=e,this.context=t}function vm(e,t){function n(i){var a=this.props.ref;return a!=i.ref&&a&&(typeof a=="function"?a(null):a.current=null),t?!t(this.props,i)||a!=i.ref:Mc(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}(mo.prototype=new Ct).isPureReactComponent=!0,mo.prototype.shouldComponentUpdate=function(e,t){return Mc(this.props,e)||Mc(this.state,t)};var ym=he.__b;he.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),ym&&ym(e)};var iC=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function V(e){function t(n){var r=gm({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=iC,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var bm=function(e,t){return e==null?null:rn(rn(e).map(t))},Gt={map:bm,forEach:bm,count:function(e){return e?rn(e).length:0},only:function(e){var t=rn(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:rn},aC=he.__e;he.__e=function(e,t,n,r){if(e.then){for(var i,a=t;a=a.__;)if((i=a.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k),i.__c(e,t)}aC(e,t,n,r)};var _m=he.unmount;function wm(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=gm({},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 wm(r,t,n)})),e}function Sm(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Sm(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 Oi(){this.__u=0,this.o=null,this.__b=null}function Cm(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Tm(e){var t,n,r,i=null;function a(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?y(i,s):null}return a.displayName="Lazy",a.__f=!0,a}function Lr(){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),_m&&_m(e)},(Oi.prototype=new Ct).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=Cm(r.__v),a=!1,s=function(){a||r.__z||(a=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Sm(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)},Oi.prototype.componentWillUnmount=function(){this.o=[]},Oi.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]=wm(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 Nm=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 oC(e){return this.getChildContext=function(){return e.context},e.children}function sC(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Ge(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,a){this.childNodes.push(i),t.h.insertBefore(i,a)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}Ge(y(oC,{context:t.context},e.__v),t.v)}function on(e,t){var n=y(sC,{__v:e,h:t});return n.containerInfo=t,n}(Lr.prototype=new Ct).__a=function(e){var t=this,n=Cm(t.__v),r=t.l.get(e);return r[0]++,function(i){var a=function(){t.props.revealOrder?(r.push(i),Nm(t,e,r)):i()};n?n(a):a()}},Lr.prototype.render=function(e){this.i=null,this.l=new Map;var t=rn(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},Lr.prototype.componentDidUpdate=Lr.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Nm(e,n,t)})};var Im=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,cC=/^(?: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]/,lC=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,dC=/[A-Z0-9]/g,uC=typeof document<"u",pC=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function km(e,t,n){return t.__k??(t.textContent=""),Ge(e,t),typeof n=="function"&&n(),e?e.__c:null}function Em(e,t,n){return im(e,t),typeof n=="function"&&n(),e?e.__c:null}Ct.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(Ct.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Pm=he.event;he.event=function(e){return Pm&&(e=Pm(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var qc,mC={configurable:!0,get:function(){return this.class}},Am=he.vnode;he.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},a=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||uC&&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"||pC(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":lC.test(s)&&(s=l):l=s="oninput":a&&cC.test(s)?s=s.replace(dC,"-$&").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=rn(n.children).forEach(function(d){d.props.selected=i.value.indexOf(d.props.value)!=-1})),i.defaultValue!=null&&(i.value=rn(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",mC)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=Im,Am&&Am(e)};var xm=he.__r;he.__r=function(e){xm&&xm(e),qc=e.__c};var Rm=he.diffed;he.diffed=function(e){Rm&&Rm(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),qc=null};var Dm={ReactCurrentDispatcher:{current:{readContext:function(e){return qc.__n[e.__c].props.value},useCallback:ce,useContext:Cn,useDebugValue:Dc,useDeferredValue:Bc,useEffect:z,useId:Dr,useImperativeHandle:uo,useInsertionEffect:Gc,useLayoutEffect:yt,useMemo:xe,useReducer:$i,useRef:G,useState:x,useSyncExternalStore:Oc,useTransition:Uc}}},fC="18.3.1";function Lm(e){return y.bind(null,e)}function sn(e){return!!e&&e.$$typeof===Im}function $m(e){return sn(e)&&e.type===Z}function Mm(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function $r(e){return sn(e)?ZS.apply(null,arguments):e}function Om(e){return!!e.__k&&(Ge(null,e),!0)}function jm(e){return e&&(e.base||e.nodeType===1&&e)||null}var Fm=function(e,t){return e(t)},fo=function(e,t){var n=he.debounceRendering;he.debounceRendering=function(i){return i()};var r=e(t);return he.debounceRendering=n,r},Bm=sn,cn={useState:x,useId:Dr,useReducer:$i,useEffect:z,useLayoutEffect:yt,useInsertionEffect:Gc,useTransition:Uc,useDeferredValue:Bc,useSyncExternalStore:Oc,startTransition:Fc,useRef:G,useImperativeHandle:uo,useMemo:xe,useCallback:ce,useContext:Cn,useDebugValue:Dc,version:"18.3.1",Children:Gt,render:km,hydrate:Em,unmountComponentAtNode:Om,createPortal:on,createElement:y,createContext:Wn,createFactory:Lm,cloneElement:$r,createRef:Jp,Fragment:Z,isValidElement:sn,isElement:Bm,isFragment:$m,isMemo:Mm,findDOMNode:jm,Component:Ct,PureComponent:mo,memo:vm,forwardRef:V,flushSync:fo,unstable_batchedUpdates:Fm,StrictMode:Z,Suspense:Oi,SuspenseList:Lr,lazy:Tm,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Dm},G1=!!(typeof window<"u"&&window.document&&window.document.createElement);function Q(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function Um(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function ho(...e){return t=>{let n=!1;const r=e.map(i=>{const a=Um(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():Um(e[i],null)}}}}function we(...e){return ce(ho(...e),e)}function hC(e,t){const n=Wn(t),r=a=>{const{children:s,...c}=a,l=xe(()=>c,Object.values(c));return o(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(a){const s=Cn(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[r,i]}function st(e,t=[]){let n=[];function r(a,s){const c=Wn(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...g}=p,h=m?.[e]?.[l]||c,v=xe(()=>g,Object.values(g));return o(h.Provider,{value:v,children:f})};d.displayName=a+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,g=Cn(f);if(g)return g;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${a}\``)}return[d,u]}const i=()=>{const a=n.map(s=>Wn(s));return function(c){const l=c?.[e]||a;return xe(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,gC(i,...t)]}function gC(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(a){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return xe(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var We=globalThis?.document?yt:()=>{},vC=hm[" useId ".trim().toString()]||(()=>{}),yC=0;function ct(e){const[t,n]=x(vC());return We(()=>{e||n(r=>r??String(yC++))},[e]),e||(t?`radix-${t}`:"")}var bC=hm[" useInsertionEffect ".trim().toString()]||We;function Tt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,a,s]=_C({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=G(e!==void 0);z(()=>{const u=d.current;u!==c&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,r])}return[l,ce(d=>{if(c){const u=wC(d)?d(e):d;u!==e&&s.current?.(u)}else a(d)},[c,e,a,s])]}function _C({defaultProp:e,onChange:t}){const[n,r]=x(e),i=G(n),a=G(t);return bC(()=>{a.current=t},[t]),z(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}function wC(e){return typeof e=="function"}function Jn(e){const t=SC(e),n=V((r,i)=>{const{children:a,...s}=r,c=Gt.toArray(a),l=c.find(TC);if(l){const d=l.props.children,u=c.map(p=>p===l?Gt.count(d)>1?Gt.only(null):sn(d)?d.props.children:null:p);return o(t,{...s,ref:i,children:sn(d)?$r(d,void 0,u):null})}return o(t,{...s,ref:i,children:a})});return n.displayName=`${e}.Slot`,n}function SC(e){const t=V((n,r)=>{const{children:i,...a}=n;if(sn(i)){const s=IC(i),c=NC(a,i.props);return i.type!==Z&&(c.ref=r?ho(r,s):s),$r(i,c)}return Gt.count(i)>1?Gt.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Gm=Symbol("radix.slottable");function CC(e){const t=({children:n})=>o(Z,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Gm,t}function TC(e){return sn(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Gm}function NC(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...s)=>{const c=a(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}function IC(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var pe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=Jn(`Primitive.${t}`),r=V((i,a)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o(l,{...c,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Hc(e,t){e&&fo(()=>e.dispatchEvent(t))}function lt(e){const t=G(e);return z(()=>{t.current=e}),xe(()=>(...n)=>t.current?.(...n),[])}function kC(e,t=globalThis?.document){const n=lt(e);z(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var EC="DismissableLayer",Kc="dismissableLayer.update",PC="dismissableLayer.pointerDownOutside",AC="dismissableLayer.focusOutside",qm,Hm=Wn({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Yn=V((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:s,onDismiss:c,...l}=e,d=Cn(Hm),[u,p]=x(null),m=u?.ownerDocument??globalThis?.document,[,f]=x({}),g=we(t,A=>p(A)),h=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=h.indexOf(v),_=u?h.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,C=_>=b,N=RC(A=>{const M=A.target,U=[...d.branches].some(k=>k.contains(M));!C||U||(i?.(A),s?.(A),A.defaultPrevented||c?.())},m),E=DC(A=>{const M=A.target;[...d.branches].some(U=>U.contains(M))||(a?.(A),s?.(A),A.defaultPrevented||c?.())},m);return kC(A=>{_===d.layers.size-1&&(r?.(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))},m),z(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(qm=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Vm(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=qm)}},[u,m,n,d]),z(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Vm())},[u,d]),z(()=>{const A=()=>f({});return document.addEventListener(Kc,A),()=>document.removeEventListener(Kc,A)},[]),o(pe.div,{...l,ref:g,style:{pointerEvents:S?C?"auto":"none":void 0,...e.style},onFocusCapture:Q(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Q(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Q(e.onPointerDownCapture,N.onPointerDownCapture)})});Yn.displayName=EC;var xC="DismissableLayerBranch",Km=V((e,t)=>{const n=Cn(Hm),r=G(null),i=we(t,r);return z(()=>{const a=r.current;if(a)return n.branches.add(a),()=>{n.branches.delete(a)}},[n.branches]),o(pe.div,{...e,ref:i})});Km.displayName=xC;function RC(e,t=globalThis?.document){const n=lt(e),r=G(!1),i=G(()=>{});return z(()=>{const a=c=>{if(c.target&&!r.current){let l=function(){Wm(PC,n,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",a),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function DC(e,t=globalThis?.document){const n=lt(e),r=G(!1);return z(()=>{const i=a=>{a.target&&!r.current&&Wm(AC,n,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Vm(){const e=new CustomEvent(Kc);document.dispatchEvent(e)}function Wm(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Hc(i,a):i.dispatchEvent(a)}var LC=Yn,$C=Km,Vc="focusScope.autoFocusOnMount",Wc="focusScope.autoFocusOnUnmount",zm={bubbles:!1,cancelable:!0},MC="FocusScope",ji=V((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...s}=e,[c,l]=x(null),d=lt(i),u=lt(a),p=G(null),m=we(t,h=>l(h)),f=G({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;z(()=>{if(r){let h=function(S){if(f.paused||!c)return;const C=S.target;c.contains(C)?p.current=C:Tn(p.current,{select:!0})},v=function(S){if(f.paused||!c)return;const C=S.relatedTarget;C!==null&&(c.contains(C)||Tn(p.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Tn(c)};document.addEventListener("focusin",h),document.addEventListener("focusout",v);const _=new MutationObserver(b);return c&&_.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",h),document.removeEventListener("focusout",v),_.disconnect()}}},[r,c,f.paused]),z(()=>{if(c){Xm.add(f);const h=document.activeElement;if(!c.contains(h)){const v=new CustomEvent(Vc,zm);c.addEventListener(Vc,d),c.dispatchEvent(v),v.defaultPrevented||(OC(GC(Jm(c)),{select:!0}),document.activeElement===h&&Tn(c))}return()=>{c.removeEventListener(Vc,d),setTimeout(()=>{const v=new CustomEvent(Wc,zm);c.addEventListener(Wc,u),c.dispatchEvent(v),v.defaultPrevented||Tn(h??document.body,{select:!0}),c.removeEventListener(Wc,u),Xm.remove(f)},0)}}},[c,d,u,f]);const g=ce(h=>{if(!n&&!r||f.paused)return;const v=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,b=document.activeElement;if(v&&b){const _=h.currentTarget,[S,C]=jC(_);S&&C?!h.shiftKey&&b===C?(h.preventDefault(),n&&Tn(S,{select:!0})):h.shiftKey&&b===S&&(h.preventDefault(),n&&Tn(C,{select:!0})):b===_&&h.preventDefault()}},[n,r,f.paused]);return o(pe.div,{tabIndex:-1,...s,ref:m,onKeyDown:g})});ji.displayName=MC;function OC(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Tn(r,{select:t}),document.activeElement!==n)return}function jC(e){const t=Jm(e);return[Ym(t,e),Ym(t.reverse(),e)]}function Jm(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ym(e,t){for(const n of e)if(!FC(n,{upTo:t}))return n}function FC(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function BC(e){return e instanceof HTMLInputElement&&"select"in e}function Tn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&BC(e)&&t&&e.select()}}var Xm=UC();function UC(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Qm(e,t),e.unshift(t)},remove(t){e=Qm(e,t),e[0]?.resume()}}}function Qm(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function GC(e){return e.filter(t=>t.tagName!=="A")}var qC="Portal",Xn=V((e,t)=>{const{container:n,...r}=e,[i,a]=x(!1);We(()=>a(!0),[]);const s=n||i&&globalThis?.document?.body;return s?cn.createPortal(o(pe.div,{...r,ref:t}),s):null});Xn.displayName=qC;function HC(e,t){return $i((n,r)=>t[n][r]??n,e)}var nt=e=>{const{present:t,children:n}=e,r=KC(t),i=typeof n=="function"?n({present:r.isPresent}):Gt.only(n),a=we(r.ref,VC(i));return typeof n=="function"||r.isPresent?$r(i,{ref:a}):null};nt.displayName="Presence";function KC(e){const[t,n]=x(),r=G(null),i=G(e),a=G("none"),[s,c]=HC(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return z(()=>{const l=go(r.current);a.current=s==="mounted"?l:"none"},[s]),We(()=>{const l=r.current,d=i.current;if(d!==e){const u=a.current,p=go(l);e?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(d&&u!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,c]),We(()=>{if(t){let l;const d=t.ownerDocument.defaultView??window,u=m=>{const f=go(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=m=>{m.target===t&&(a.current=go(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(l),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:ce(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function go(e){return e?.animationName||"none"}function VC(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var zc=0;function vo(){z(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Zm()),document.body.insertAdjacentElement("beforeend",e[1]??Zm()),zc++,()=>{zc===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zc--}},[])}function Zm(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var qt=function(){return qt=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},qt.apply(this,arguments)};function ef(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 WC(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var yo="right-scroll-bar-position",bo="width-before-scroll-bar",zC="with-scroll-bars-hidden",JC="--removed-body-scroll-bar-size";function Jc(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function YC(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 XC=typeof window<"u"?yt:z,tf=new WeakMap;function QC(e,t){var n=YC(t||null,function(r){return e.forEach(function(i){return Jc(i,r)})});return XC(function(){var r=tf.get(n);if(r){var i=new Set(r),a=new Set(e),s=n.current;i.forEach(function(c){a.has(c)||Jc(c,null)}),a.forEach(function(c){i.has(c)||Jc(c,s)})}tf.set(n,e)},[e]),n}function ZC(e){return e}function eT(e,t){t===void 0&&(t=ZC);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var c=function(){var d=a;a=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){a.push(d),l()},filter:function(d){return a=a.filter(d),n}}}}}function tT(e){e===void 0&&(e={});var t=eT(null);return t.options=qt({async:!0,ssr:!1},e),t}var nf=function(e){var t=e.sideCar,n=ef(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,qt({},n))};nf.isSideCarExport=!0;function nT(e,t){return e.useMedium(t),nf}var rf=tT(),Yc=function(){},_o=V(function(e,t){var n=G(null),r=x({onScrollCapture:Yc,onWheelCapture:Yc,onTouchMoveCapture:Yc}),i=r[0],a=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,g=e.noIsolation,h=e.inert,v=e.allowPinchZoom,b=e.as,_=b===void 0?"div":b,S=e.gapMode,C=ef(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=m,E=QC([n,t]),A=qt(qt({},C),i);return y(Z,null,u&&y(N,{sideCar:rf,removeScrollBar:d,shards:p,noRelative:f,noIsolation:g,inert:h,setCallbacks:a,allowPinchZoom:!!v,lockRef:n,gapMode:S}),s?$r(Gt.only(c),qt(qt({},A),{ref:E})):y(_,qt({},A,{className:l,ref:E}),c))});_o.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},_o.classNames={fullWidth:bo,zeroRight:yo};var af,rT=function(){if(af)return af;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function iT(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=rT();return t&&e.setAttribute("nonce",t),e}function aT(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function oT(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var sT=function(){var e=0,t=null;return{add:function(n){e==0&&(t=iT())&&(aT(t,n),oT(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},cT=function(){var e=sT();return function(t,n){z(function(){return e.add(t),function(){e.remove()}},[t&&n])}},of=function(){var e=cT(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},lT={left:0,top:0,right:0,gap:0},Xc=function(e){return parseInt(e||"",10)||0},dT=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[Xc(n),Xc(r),Xc(i)]},uT=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return lT;var t=dT(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])}},pT=of(),Fi="data-scroll-locked",mT=function(e,t,n,r){var i=e.left,a=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
|
|
2
|
-
.`.concat(
|
|
1
|
+
(function(){var sm=Object.defineProperty,qS=(e,t)=>{let n={};for(var r in e)sm(n,r,{get:e[r],enumerable:!0});return t||sm(n,Symbol.toStringTag,{value:"Module"}),n};function ge(e){if(!e||typeof e!="object")return;const t=e.error;return typeof t=="string"?t:void 0}async function Me(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e}: ${t.status} ${t.statusText}`);return t.json()}async function ve(e){const t=await e.text();try{return{text:t,payload:t?JSON.parse(t):{}}}catch{return{text:t,payload:{}}}}function cm(e,t,n,r,i){const a=new URLSearchParams;return a.set("project",e||""),typeof t=="number"&&a.set("limit",String(t)),typeof n=="number"&&a.set("offset",String(n)),r&&a.set("scope",r),i&&a.set("q",i),a.toString()}async function GS(){return Me("/api/observer-status")}async function HS(){return Me("/api/config")}async function KS(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=ge(r)||n||"request failed";throw new Error(i)}return r}async function Vc(){return Me("/api/coordinator/admin/status")}async function lm(e){return Me(`/api/coordinator/admin/groups${e?"?include_archived=1":""}`)}async function VS(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function WS(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function zS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/archive`,{method:"POST"}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function JS(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/unarchive`,{method:"POST"}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function YS(e,t=!1){const n=new URLSearchParams;t&&n.set("include_inactive","1");const r=n.size?`?${n.toString()}`:"";return Me(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes${r}`)}async function XS(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function dm(e,t,n=!1){const r=new URLSearchParams;n&&r.set("include_revoked","1");const i=r.size?`?${r.toString()}`:"";return Me(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members${i}`)}async function QS(e,t,n){const r=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),{text:i,payload:a}=await ve(r);if(!r.ok)throw new Error(ge(a)||i||"request failed");return a}async function ZS(e,t,n,r={}){const i=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/scopes/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await ve(i);if(!i.ok)throw new Error(ge(s)||a||"request failed");return s}async function eC(e){const t=new URLSearchParams;return e&&t.set("group_id",e),Me(`/api/coordinator/admin/join-requests${t.size?`?${t.toString()}`:""}`)}async function um(e,t=!0){const n=new URLSearchParams;return e&&n.set("group_id",e),t&&n.set("include_disabled","1"),Me(`/api/coordinator/admin/devices${n.size?`?${n.toString()}`:""}`)}async function tC(e,t){const n=await fetch(`/api/coordinator/admin/join-requests/${encodeURIComponent(e)}/${t}`,{method:"POST"}),{text:r,payload:i}=await ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function nC(e,t,n){const r=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({group_id:t,display_name:n})}),{text:i,payload:a}=await ve(r);if(!r.ok)throw new Error(ge(a)||i||"request failed");return a}async function rC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/disable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function iC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/enable?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function aC(e,t){const n=await fetch(`/api/coordinator/admin/devices/${encodeURIComponent(e)}/remove?group_id=${encodeURIComponent(t)}`,{method:"POST"}),{text:r,payload:i}=await ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function pm(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function mm(e,t){return Me(`/api/observations?${cm(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function oC(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function sC(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function cC(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function fm(e,t){return Me(`/api/summaries?${cm(e,t?.limit,t?.offset,t?.scope,t?.q)}`)}async function lC(e){const t=await fetch("/api/pack/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function dC(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 uC(){return Me("/api/runtime")}async function wo(){return(await Me("/api/projects")).projects||[]}async function pC(){return Me("/api/stats")}async function mC(e){return Me(`/api/usage?project=${encodeURIComponent(e)}`)}async function fC(e){return Me(`/api/session?project=${encodeURIComponent(e)}`)}async function hC(e){return Me(`/api/raw-events?project=${encodeURIComponent(e)}`)}var So=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="RecipientPolicyTeamRenameApiError"}},gC=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 vC(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 So(0,"team_rename_failed")}const{payload:n}=await ve(t);if(!t.ok){const r=n&&typeof n=="object"&&"error"in n?String(n.error):"";throw new So(t.status,gC.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 So(t.status,"team_rename_failed");return n}var yC=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"]),hm=class extends Error{errorCode;constructor(e,t){super(e),this.errorCode=t,this.name="ProjectInviteAcceptanceError"}};async function Co(e,t="",n){const r=new URLSearchParams;return e&&r.set("includeDiagnostics","1"),t&&r.set("project",t),n?.includeJoinRequests&&r.set("includeJoinRequests","1"),Me(`/api/sync/status${r.size?`?${r.toString()}`:""}`)}async function Wc(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:a}=await ve(r);if(!r.ok){const s=typeof a?.detail=="string"?a.detail.trim():"",c=ge(a),l=s||c||i||"request failed";throw n==="project_share_invite"&&c&&yC.has(c)?new hm(l,c):new Error(l)}return a}async function gm(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function bC(){return Me("/api/sync/actors")}async function _C(e=!1){return Me(`/api/sync/pairing${e?"?includeDiagnostics=1":""}`)}async function vm(e){const t=await fetch(`/api/sync/peers/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function ym(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function wC(e,t){const n={peer_device_id:e};t?.fingerprint&&(n.fingerprint=t.fingerprint),t?.expectedGroupId&&(n.expected_group_id=t.expectedGroupId),t?.expectedIncomingRequestId&&(n.expected_incoming_request_id=t.expectedIncomingRequestId);const r=await fetch("/api/sync/peers/accept-discovered",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.text();let a={};try{const c=i?JSON.parse(i):null;c&&typeof c=="object"&&!Array.isArray(c)&&(a=c)}catch{a={}}const s=typeof a.detail=="string"?a.detail:void 0;if(!r.ok)throw new Error(s||ge(a)||i||"request failed");return a}var bm=class extends Error{preview;constructor(e){super("Project forget confirmation required"),this.name="ProjectForgetConfirmationError",this.preview=e}},No=class extends Error{requiredGuardrails;requiredGuardrailTokens;guardrailWarnings;constructor(e){super("Sharing domain guardrail confirmation required"),this.name="SharingDomainGuardrailConfirmationError",this.requiredGuardrails=e.required_guardrails??[],this.requiredGuardrailTokens=e.required_guardrail_tokens??[],this.guardrailWarnings=e.guardrail_warnings??[]}},_m=class extends Error{preview;constructor(e){super("Legacy shared review confirmation required"),this.name="LegacySharedReviewConfirmationError",this.preview=e}},zc=class extends Error{statusCode;errorCode;result;constructor(e,t,n){super(t),this.statusCode=e,this.errorCode=t,this.result=n,this.name="DeviceIdentityBindingApiError"}},Jc=1,wm=new Set(["team_setup_incomplete","team_setup_roster_changed","team_setup_assignment_changed","team_setup_roster_unavailable","team_setup_conflict","team_setup_confirmation_stale","team_setup_failed"]),SC=new Set(["needs_setup","in_progress","stale","ready"]),CC=new Set(["reviewing","ready_to_finish","unavailable","completed"]),NC=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 ze(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pn(e,t){const n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,a)=>i===r[a])}function Lt(e){return typeof e=="string"||e===null}function sr(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Gt(e,t){return Array.isArray(e)&&e.every(t)}function Sm(e){return ze(e)?typeof e.candidateRef=="string"&&typeof e.displayName=="string"&&typeof e.status=="string"&&SC.has(e.status)&&sr(e.deviceCount)&&sr(e.projectCount)&&sr(e.unresolvedDeviceCount)&&sr(e.unresolvedProjectCount):!1}function IC(e){return ze(e)&&e.version===Jc&&Gt(e.candidates,t=>Sm(t)&&t.status!=="ready")}function kC(e){return ze(e)?e.kind==="absent"||e.kind==="existing"&&sr(e.assignmentVersion)&&typeof e.identityRef=="string":!1}function An(e){return!ze(e)||!Pn(e,["blockedReason","enabled"])?!1:e.enabled===!0?e.blockedReason===null:e.enabled===!1&&typeof e.blockedReason=="string"&&NC.has(e.blockedReason)}function TC(e){return!ze(e)||!Pn(e,["assignIdentity","clearDecision","exclude","include","remove"])?!1:An(e.assignIdentity)&&An(e.include)&&An(e.exclude)&&An(e.remove)&&An(e.clearDecision)}function RC(e){return ze(e)?typeof e.deviceRef=="string"&&typeof e.displayName=="string"&&typeof e.enabled=="boolean"&&Lt(e.existingIdentityRef)&&Lt(e.suggestedIdentityRef)&&(e.verifiedEvidenceKind==="active_assignment"||e.verifiedEvidenceKind===null)&&typeof e.decision=="string"&&["unresolved","included","excluded","removed"].includes(e.decision)&&Lt(e.targetIdentityRef)&&kC(e.expectation)&&TC(e.actions):!1}function PC(e){return ze(e)?typeof e.projectRef=="string"&&typeof e.displayName=="string"&&typeof e.resolution=="string"&&["unresolved","deterministic","explicit"].includes(e.resolution)&&Lt(e.canonicalProjectRef)&&Lt(e.resolvedProjectRef)&&Gt(e.mappingChoices,t=>ze(t)&&typeof t.resolvedProjectRef=="string"&&typeof t.displayName=="string")&&ze(e.actions)&&Pn(e.actions,["map"])&&An(e.actions.map):!1}function AC(e){if(!ze(e))return!1;const t=n=>typeof n=="string"&&["add","update","remove"].includes(n);return Gt(e.teamChanges,n=>ze(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")&&Gt(e.membershipChanges,n=>ze(n)&&typeof n.teamRef=="string"&&typeof n.teamDisplayName=="string"&&typeof n.identityRef=="string"&&typeof n.identityDisplayName=="string"&&t(n.change))&&Gt(e.projectChanges,n=>ze(n)&&typeof n.projectRef=="string"&&typeof n.projectDisplayName=="string"&&Lt(n.fromCanonicalProjectRef)&&Lt(n.fromResolvedProjectRef)&&Lt(n.fromResolvedProjectDisplayName)&&Lt(n.toCanonicalProjectRef)&&Lt(n.toResolvedProjectRef)&&Lt(n.toResolvedProjectDisplayName)&&t(n.change))&&Gt(e.recipientChanges,n=>ze(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))&&Gt(e.deviceAccessChanges,n=>ze(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 EC(e){return ze(e)&&Pn(e,["finish","refresh"])&&An(e.refresh)&&An(e.finish)}function Cm(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 Jr(e){if(!ze(e)||!(e.version===Jc&&Sm(e.candidate)&&typeof e.attemptId=="string"&&typeof e.state=="string"&&CC.has(e.state)&&sr(e.unresolvedDeviceCount)&&sr(e.unresolvedProjectCount)&&Gt(e.devices,RC)&&Gt(e.projects,PC)&&EC(e.actions)&&Gt(e.identityChoices,a=>ze(a)&&typeof a.identityRef=="string"&&typeof a.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"?Pn(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"&&AC(e.accessDelta):e.state==="unavailable"?Pn(e,[...i,"unavailableReason"])&&typeof e.unavailableReason=="string"&&wm.has(e.unavailableReason)&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_unavailable"&&Cm(n,r,"setup_unavailable"):e.state==="completed"?Pn(e,i)&&t.refresh.enabled===!1&&t.refresh.blockedReason==="setup_completed"&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_completed"&&Cm(n,r,"setup_completed"):Pn(e,i)&&e.state==="reviewing"&&t.refresh.enabled===!0&&t.finish.enabled===!1&&t.finish.blockedReason==="setup_incomplete"}function xC(e){return ze(e)&&e.version===Jc&&e.status==="completed"&&typeof e.teamRef=="string"&&typeof e.attemptId=="string"&&typeof e.accessDeltaDigest=="string"&&typeof e.completedAt=="string"}var cr=class extends Error{statusCode;errorCode;constructor(e,t){super(t),this.statusCode=e,this.errorCode=t,this.name="LegacyTeamSetupApiError"}};function En(e){return e?`/api/sync/team-setup/v1/${encodeURIComponent(e)}`:"/api/sync/team-setup/v1"}async function xn(e,t,n){let r;try{r=await fetch(e,n)}catch{throw new cr(0,"team_setup_failed")}let i;try{const a=await r.text();if(!a)throw new Error("empty Team setup response");i=JSON.parse(a)}catch{throw new cr(r.status,"team_setup_failed")}if(!r.ok){const a=i&&typeof i=="object"&&"error"in i&&typeof i.error=="string"?i.error:"",s=wm.has(a)?a:"team_setup_failed";throw new cr(r.status,s)}if(!t(i))throw new cr(r.status,"team_setup_failed");return i}function Yr(e,t){return{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}function Nm(){return xn(En(),IC)}function DC(e){return xn(En(e),Jr)}function LC(e,t,n){return xn(`${En(e)}/devices/${encodeURIComponent(t)}/assignment`,Jr,Yr("PUT",n))}function $C(e,t,n){return xn(`${En(e)}/devices/${encodeURIComponent(t)}/decision`,Jr,Yr("PUT",n))}function MC(e,t,n){return xn(`${En(e)}/devices/${encodeURIComponent(t)}/decision`,Jr,Yr("DELETE",n))}function jC(e,t,n){return xn(`${En(e)}/projects/${encodeURIComponent(t)}/mapping`,Jr,Yr("PUT",n))}function OC(e){return xn(`${En(e)}/refresh`,Jr,Yr("POST",{}))}function FC(e,t){return xn(`${En(e)}/finish`,xC,Yr("POST",t))}var Yc=class extends Error{result;constructor(e){super("Recipient policy changed after review"),this.name="RecipientPolicyEdgesStaleError",this.result=e}};function Xc(){return Me("/api/sync/recipient-policy/v1/intent")}function Qc(){return Me("/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 ve(n);if(!n.ok){const a=i?.errorCode||i?.error||ge(i)||r||"request_failed",s=i&&"status"in i?i:null;throw new zc(n.status,a,s)}return i}function km(e){return Im("/api/sync/recipient-policy/v1/device-bindings/preview",e)}function Tm(e){return Im("/api/sync/recipient-policy/v1/device-bindings/commit",e)}function BC(){return Me("/api/sync/recipient-policy/v1/reconciliation-status")}async function Rm(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ve(n);if(!n.ok){if(n.status===409&&i&&typeof i=="object"&&i.status==="stale")throw new Yc(i);if(n.status===409&&i&&typeof i=="object"&&i.status==="conflict")return i;const a=i&&typeof i=="object"&&"errorCode"in i?String(i.errorCode??""):"";throw new Error(a||ge(i)||r||"request failed")}return i}function UC(e){return Rm("/api/sync/recipient-policy/v1/edges/preview",e)}function qC(e){return Rm("/api/sync/recipient-policy/v1/edges/commit",e)}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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}function GC(e){return Pm("/api/sync/recipient-policy/v1/invites/preview",e)}function HC(e){return Pm("/api/sync/recipient-policy/v1/invites",e)}async function KC(){const e=await Me("/api/sync/recipient-policy/v1/review");return e.continuity!==void 0?{...e,continuity:e.continuity}:{...e,continuity:e.reviewItems.length>0?{state:"legacy_access_preserved",findingCount:e.reviewItems.length}:null}}async function VC(){return Me("/api/sync/sharing-domains/settings")}async function Wi(e={}){const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i==null||i===""||t.set(r,String(i));const n=t.toString();return Me(`/api/sync/projects${n?`?${n}`:""}`)}async function Am(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),{text:r,payload:i}=await ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}function WC(e){return Am("/api/sync/project-invites/preview",e)}function zC(e){return Am("/api/sync/project-invites",e)}function Em(){return Me("/api/sync/share-operations")}function JC(e){return Me(`/api/sync/share-operations/${encodeURIComponent(e)}`)}async function YC(e){const t=await fetch(`/api/sync/share-operations/${encodeURIComponent(e)}/advance`,{method:"POST"}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");if(!r?.operation)throw new Error("response missing share operation");return r.operation}async function XC(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 ve(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new No(r):new Error(ge(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 QC(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 ve(t);if(!t.ok)throw r?.error==="guardrail_confirmation_required"?new No(r):new Error(ge(r)||n||"request failed");if(!Array.isArray(r?.mappings))throw new Error("response missing mappings");return r.mappings}async function ZC(e){const t=await fetch(`/api/sync/sharing-domains/project-mappings/${encodeURIComponent(e)}`,{method:"DELETE"}),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return!!r?.deleted}async function eN(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project reassignment");return r}async function tN(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 ve(t);if(!t.ok)throw r?.error==="project_forget_confirmation_required"&&r.preview?new bm(r.preview):new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing project forget result");return r}async function nN(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 ve(t);if(!t.ok)throw r?.error==="legacy_review_confirmation_required"&&r.preview?new _m(r.preview):new Error(ge(r)||n||"request failed");if(!r?.workspace_identity)throw new Error("response missing legacy review reassignment");return r}async function rN(e){const t=await fetch(`/api/coordinator/admin/groups/${encodeURIComponent(e)}/preferences`),{text:n,payload:r}=await ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");const i=r?.preferences;if(!i)throw new Error("response missing preferences");return i}async function iN(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");const a=i?.preferences;if(!a)throw new Error("response missing preferences");return a}async function aN(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function oN(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function xm(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 ve(n);if(!n.ok)throw new Error(ge(i)||r||"request failed");return i}async function sN(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function cN(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 ve(t);if(!t.ok)throw new Error(ge(r)||n||"request failed");return r}async function Zc(e){const t=typeof e=="string"?e.trim():e?.address?.trim(),n=typeof e=="string"?"":e?.peerDeviceId?.trim(),r={};t&&(r.address=t),n&&(r.peer_device_id=n);const i=await fetch("/api/sync/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),{text:a,payload:s}=await ve(i);if(!i.ok)throw new Error(ge(s)||a||"request failed");if(!a)throw new Error("empty sync response");if(!Array.isArray(s?.items))throw new Error(a||"invalid sync response");return s}async function lN(){return Me("/api/update-status")}function dN(e){return{current_version:"unknown",latest_version:null,update_available:!1,first_seen_at:null,checked_at:null,stale:!1,install_kind:"unknown",auto_update_eligible:!1,recommended_action:"Check network access and try again.",error:e instanceof Error?e.message:"Update status request failed."}}function Io(e){return e!==null&&typeof e=="object"?e:null}function Dm(e){const t=Io(e),n=Io(t?.status),r=Io(Io(t?.coordinator_enrollment_reconciliation_issues??n?.coordinator_enrollment_reconciliation_issues)?.counts)?.open;return typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0}var zi,me,Lm,$m,Dn,Mm,jm,Om,el,ko,Ji,Fm,tl,nl,rl,Bm,To={},Ro=[],uN=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Yi=Array.isArray;function Ht(e,t){for(var n in t)e[n]=t[n];return e}function il(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function v(e,t,n){var r,i,a,s={};for(a in t)a=="key"?r=t[a]:a=="ref"?i=t[a]:s[a]=t[a];if(arguments.length>2&&(s.children=arguments.length>3?zi.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(a in e.defaultProps)s[a]===void 0&&(s[a]=e.defaultProps[a]);return Xi(e,s,r,i,null)}function Xi(e,t,n,r,i){var a={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Lm,__i:-1,__u:0};return i==null&&me.vnode!=null&&me.vnode(a),a}function Um(){return{current:null}}function z(e){return e.children}function It(e,t){this.props=e,this.context=t}function Xr(e,t){if(t==null)return e.__?Xr(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"?Xr(e):null}function pN(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],i=[],a=Ht({},t);a.__v=t.__v+1,me.vnode&&me.vnode(a),ol(e.__P,a,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Xr(t),!!(32&t.__u),i),a.__v=t.__v,a.__.__k[a.__i]=a,Wm(r,a,i),t.__e=t.__=null,a.__e!=n&&qm(a)}}function qm(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}),qm(e)}function al(e){(!e.__d&&(e.__d=!0)&&Dn.push(e)&&!Po.__r++||Mm!=me.debounceRendering)&&((Mm=me.debounceRendering)||jm)(Po)}function Po(){try{for(var e,t=1;Dn.length;)Dn.length>t&&Dn.sort(Om),e=Dn.shift(),t=Dn.length,pN(e)}finally{Dn.length=Po.__r=0}}function Gm(e,t,n,r,i,a,s,c,l,d,u){var p,m,f,y,g,h,b,w=r&&r.__k||Ro,_=t.length;for(l=mN(n,t,w,l,_),p=0;p<_;p++)(f=n.__k[p])!=null&&(m=f.__i!=-1&&w[f.__i]||To,f.__i=p,h=ol(e,f,m,i,a,s,c,l,d,u),y=f.__e,f.ref&&m.ref!=f.ref&&(m.ref&&cl(m.ref,null,f),u.push(f.ref,f.__c||y,f)),g==null&&y!=null&&(g=y),(b=!!(4&f.__u))||m.__k===f.__k?(l=Hm(f,l,e,b),b&&m.__e&&(m.__e=null)):typeof f.type=="function"&&h!==void 0?l=h:y&&(l=y.nextSibling),f.__u&=-7);return n.__e=g,l}function mN(e,t,n,r,i){var a,s,c,l,d,u=n.length,p=u,m=0;for(e.__k=new Array(i),a=0;a<i;a++)(s=t[a])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[a]=Xi(null,s,null,null,null):Yi(s)?s=e.__k[a]=Xi(z,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[a]=Xi(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[a]=s,l=a+m,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=fN(s,n,l,p))!=-1&&(p--,(c=n[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(i>u?m--:i<u&&m++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?m--:d==l+1?m++:(d>l?m--:m++,s.__u|=4))):e.__k[a]=null;if(p)for(a=0;a<u;a++)(c=n[a])!=null&&(2&c.__u)==0&&(c.__e==r&&(r=Xr(c)),Jm(c,c));return r}function Hm(e,t,n,r){var i,a;if(typeof e.type=="function"){for(i=e.__k,a=0;i&&a<i.length;a++)i[a]&&(i[a].__=e,t=Hm(i[a],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Xr(e)),n.insertBefore(e.__e,t||null)),t=e.__e);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"||(Yi(e)?e.some(function(n){cn(n,t)}):t.push(e)),t}function fN(e,t,n,r){var i,a,s,c=e.key,l=e.type,d=t[n],u=d!=null&&(2&d.__u)==0;if(d===null&&c==null||u&&c==d.key&&l==d.type)return n;if(r>(u?1:0)){for(i=n-1,a=n+1;i>=0||a<t.length;)if((d=t[s=i>=0?i--:a++])!=null&&(2&d.__u)==0&&c==d.key&&l==d.type)return s}return-1}function Km(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||uN.test(t)?n:n+"px"}function Ao(e,t,n,r,i){var a,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Km(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Km(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")a=t!=(t=t.replace(Fm,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+a]=n,n?r?n[Ji]=r[Ji]:(n[Ji]=tl,e.addEventListener(t,a?rl:nl,a)):e.removeEventListener(t,a?rl:nl,a);else{if(i=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Vm(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[ko]==null)t[ko]=tl++;else if(t[ko]<n[Ji])return;return n(me.event?me.event(t):t)}}}function ol(e,t,n,r,i,a,s,c,l,d){var u,p,m,f,y,g,h,b,w,_,I,N,T,x,j,B=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),a=[c=t.__e=n.__e]),(u=me.__b)&&u(t);e:if(typeof B=="function")try{if(b=t.props,w=B.prototype&&B.prototype.render,_=(u=B.contextType)&&r[u.__c],I=u?_?_.props.value:u.__:r,n.__c?h=(p=t.__c=n.__c).__=p.__E:(w?t.__c=p=new B(b,I):(t.__c=p=new It(b,I),p.constructor=B,p.render=gN),_&&_.sub(p),p.state||(p.state={}),p.__n=r,m=p.__d=!0,p.__h=[],p._sb=[]),w&&p.__s==null&&(p.__s=p.state),w&&B.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ht({},p.__s)),Ht(p.__s,B.getDerivedStateFromProps(b,p.__s))),f=p.props,y=p.state,p.__v=t,m)w&&B.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),w&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(w&&B.getDerivedStateFromProps==null&&b!==f&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(b,I),t.__v==n.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(b,p.__s,I)===!1){t.__v!=n.__v&&(p.props=b,p.state=p.__s,p.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(P){P&&(P.__=t)}),Ro.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&s.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(b,p.__s,I),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(f,y,g)})}if(p.context=I,p.props=b,p.__P=e,p.__e=!1,N=me.__r,T=0,w)p.state=p.__s,p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),Ro.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,N&&N(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++T<25);p.state=p.__s,p.getChildContext!=null&&(r=Ht(Ht({},r),p.getChildContext())),w&&!m&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(f,y)),x=u!=null&&u.type===z&&u.key==null?zm(u.props.children):u,c=Gm(e,Yi(x)?x:[x],t,n,r,i,a,s,c,l,d),p.base=t.__e,t.__u&=-161,p.__h.length&&s.push(p),h&&(p.__E=p.__=null)}catch(P){if(t.__v=null,l||a!=null)if(P.then){for(t.__u|=l?160:128;c&&c.nodeType==8&&c.nextSibling;)c=c.nextSibling;a[a.indexOf(c)]=null,t.__e=c}else{for(j=a.length;j--;)il(a[j]);sl(t)}else t.__e=n.__e,t.__k=n.__k,P.then||sl(t);me.__e(P,t,n)}else a==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):c=t.__e=hN(n.__e,t,n,r,i,a,s,l,d);return(u=me.diffed)&&u(t),128&t.__u?void 0:c}function sl(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(sl))}function Wm(e,t,n){for(var r=0;r<n.length;r++)cl(n[r],n[++r],n[++r]);me.__c&&me.__c(t,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(a){a.call(i)})}catch(a){me.__e(a,i.__v)}})}function zm(e){return typeof e!="object"||e==null||e.__b>0?e:Yi(e)?e.map(zm):e.constructor!==void 0?null:Ht({},e)}function hN(e,t,n,r,i,a,s,c,l){var d,u,p,m,f,y,g,h=n.props||To,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"),a!=null){for(d=0;d<a.length;d++)if((f=a[d])&&"setAttribute"in f==!!w&&(w?f.localName==w:f.nodeType==3)){e=f,a[d]=null;break}}if(e==null){if(w==null)return document.createTextNode(b);e=document.createElementNS(i,w,b.is&&b),c&&(me.__m&&me.__m(t,a),c=!1),a=null}if(w==null)h===b||c&&e.data==b||(e.data=b);else{if(a=w=="textarea"&&b.defaultValue!=null?null:a&&zi.call(e.childNodes),!c&&a!=null)for(h={},d=0;d<e.attributes.length;d++)h[(f=e.attributes[d]).name]=f.value;for(d in h)f=h[d],d=="dangerouslySetInnerHTML"?p=f:d=="children"||d in b||d=="value"&&"defaultValue"in b||d=="checked"&&"defaultChecked"in b||Ao(e,d,null,f,i);for(d in b)f=b[d],d=="children"?m=f:d=="dangerouslySetInnerHTML"?u=f:d=="value"?y=f:d=="checked"?g=f:c&&typeof f!="function"||h[d]===f||Ao(e,d,f,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=""),Gm(t.type=="template"?e.content:e,Yi(m)?m:[m],t,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,a,s,a?a[0]:n.__k&&Xr(n,0),c,l),a!=null)for(d=a.length;d--;)il(a[d]);c&&w!="textarea"||(d="value",w=="progress"&&y==null?e.removeAttribute("value"):y!=null&&(y!==e[d]||w=="progress"&&!y||w=="option"&&y!=h[d])&&Ao(e,d,y,h[d],i),d="checked",g!=null&&g!=e[d]&&Ao(e,d,g,h[d],i))}return e}function cl(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){me.__e(i,n)}}function Jm(e,t,n){var r,i;if(me.unmount&&me.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||cl(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(a){me.__e(a,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Jm(r[i],t,n||typeof e.type!="function");n||il(e.__e),e.__c=e.__=e.__e=void 0}function gN(e,t,n){return this.constructor(e,n)}function He(e,t,n){var r,i,a,s;t==document&&(t=document.documentElement),me.__&&me.__(e,t),i=(r=typeof n=="function")?null:n&&n.__k||t.__k,a=[],s=[],ol(t,e=(!r&&n||t).__k=v(z,null,[e]),i||To,To,t.namespaceURI,!r&&n?[n]:i?null:t.firstChild?zi.call(t.childNodes):null,a,!r&&n?n:i?i.__e:t.firstChild,r,s),Wm(a,e,s)}function Ym(e,t){He(e,t,Ym)}function vN(e,t,n){var r,i,a,s,c=Ht({},e.props);for(a in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)a=="key"?r=t[a]:a=="ref"?i=t[a]:c[a]=t[a]===void 0&&s!=null?s[a]:t[a];return arguments.length>2&&(c.children=arguments.length>3?zi.call(arguments,2):n),Xi(e.type,c,r||e.key,i||e.ref,null)}function lr(e){function t(n){var r,i;return this.getChildContext||(r=new Set,(i={})[t.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(a){this.props.value!=a.value&&r.forEach(function(s){s.__e=!0,al(s)})},this.sub=function(a){r.add(a);var s=a.componentWillUnmount;a.componentWillUnmount=function(){r&&r.delete(a),s&&s.call(a)}}),n.children}return t.__c="__cC"+Bm++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}zi=Ro.slice,me={__e:function(e,t,n,r){for(var i,a,s;t=t.__;)if((i=t.__c)&&!i.__)try{if((a=i.constructor)&&a.getDerivedStateFromError!=null&&(i.setState(a.getDerivedStateFromError(e)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(e,r||{}),s=i.__d),s)return i.__E=i}catch(c){e=c}throw e}},Lm=0,$m=function(e){return e!=null&&e.constructor===void 0},It.prototype.setState=function(e,t){var n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ht({},this.state);typeof e=="function"&&(e=e(Ht({},n),this.props)),e&&Ht(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),al(this))},It.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),al(this))},It.prototype.render=z,Dn=[],jm=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Om=function(e,t){return e.__v.__b-t.__v.__b},Po.__r=0,el=Math.random().toString(8),ko="__d"+el,Ji="__a"+el,Fm=/(PointerCapture)$|Capture$/i,tl=0,nl=Vm(!1),rl=Vm(!0),Bm=0;var ln,je,ll,Xm,Qr=0,Qm=[],Ke=me,Zm=Ke.__b,ef=Ke.__r,tf=Ke.diffed,nf=Ke.__c,rf=Ke.unmount,af=Ke.__;function dr(e,t){Ke.__h&&Ke.__h(je,e,Qr||t),Qr=0;var n=je.__H||(je.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function D(e){return Qr=1,Qi(sf,e)}function Qi(e,t,n){var r=dr(ln++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):sf(void 0,t),function(c){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,c);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=je,!je.__f)){var i=function(c,l,d){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(m){return m.__c});if(u.every(function(m){return!m.__N}))return!a||a.call(this,c,l,d);var p=r.__c.props!==c;return u.some(function(m){if(m.__N){var f=m.__[0];m.__=m.__N,m.__N=void 0,f!==m.__[0]&&(p=!0)}}),a&&a.call(this,c,l,d)||p};je.__f=!0;var a=je.shouldComponentUpdate,s=je.componentWillUpdate;je.componentWillUpdate=function(c,l,d){if(this.__e){var u=a;a=void 0,i(c,l,d),a=u}s&&s.call(this,c,l,d)},je.shouldComponentUpdate=i}return r.__N||r.__}function W(e,t){var n=dr(ln++,3);!Ke.__s&&pl(n.__H,t)&&(n.__=e,n.u=t,je.__H.__h.push(n))}function gt(e,t){var n=dr(ln++,4);!Ke.__s&&pl(n.__H,t)&&(n.__=e,n.u=t,je.__h.push(n))}function q(e){return Qr=5,Se(function(){return{current:e}},[])}function Eo(e,t,n){Qr=6,gt(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 Se(e,t){var n=dr(ln++,7);return pl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function oe(e,t){return Qr=8,Se(function(){return e},t)}function Ln(e){var t=je.context[e.__c],n=dr(ln++,9);return n.c=e,t?(n.__??(n.__=!0,t.sub(je)),t.props.value):e.__}function dl(e,t){Ke.useDebugValue&&Ke.useDebugValue(t?t(e):e)}function yN(e){var t=dr(ln++,10),n=D();return t.__=e,je.componentDidCatch||(je.componentDidCatch=function(r,i){t.__&&t.__(r,i),n[1](r)}),[n[0],function(){n[1](void 0)}]}function ur(){var e=dr(ln++,11);if(!e.__){for(var t=je.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function bN(){for(var e;e=Qm.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(xo),t.__h.some(ul),t.__h=[]}catch(n){t.__h=[],Ke.__e(n,e.__v)}}}Ke.__b=function(e){je=null,Zm&&Zm(e)},Ke.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),af&&af(e,t)},Ke.__r=function(e){ef&&ef(e),ln=0;var t=(je=e.__c).__H;t&&(ll===je?(t.__h=[],je.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(xo),t.__h.some(ul),t.__h=[],ln=0)),ll=je},Ke.diffed=function(e){tf&&tf(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Qm.push(t)!==1&&Xm===Ke.requestAnimationFrame||((Xm=Ke.requestAnimationFrame)||_N)(bN)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ll=je=null},Ke.__c=function(e,t){t.some(function(n){try{n.__h.some(xo),n.__h=n.__h.filter(function(r){return!r.__||ul(r)})}catch(r){t.some(function(i){i.__h&&(i.__h=[])}),t=[],Ke.__e(r,n.__v)}}),nf&&nf(e,t)},Ke.unmount=function(e){rf&&rf(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{xo(r)}catch(i){t=i}}),n.__H=void 0,t&&Ke.__e(t,n.__v))};var of=typeof requestAnimationFrame=="function";function _N(e){var t,n=function(){clearTimeout(r),of&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);of&&(t=requestAnimationFrame(n))}function xo(e){var t=je,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),je=t}function ul(e){var t=je;e.__c=e.__(),je=t}function pl(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function sf(e,t){return typeof t=="function"?t(e):t}var JB=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,wN=0,YB=Array.isArray;function o(e,t,n,r,i,a){t||(t={});var s,c,l=t;if("ref"in l)for(c in l={},t)c=="ref"?s=t[c]:l[c]=t[c];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--wN,__i:-1,__u:0,__source:i,__self:a};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return me.vnode&&me.vnode(d),d}function Zr({ariaDisabled:e=!1,ariaLabel:t,className:n="modal-close-button",disabled:r=!1,onClick:i,label:a="Close"}){return o("button",{"aria-disabled":e?"true":void 0,"aria-label":t,className:n,disabled:r,onClick:()=>{e||i()},type:"button",children:[o("i",{"aria-hidden":"true",className:"modal-close-button-icon","data-lucide":"x"}),o("span",{className:"modal-close-button-label",children:a})]})}var cf=qS({Children:()=>Kt,Component:()=>It,Fragment:()=>z,PureComponent:()=>Do,StrictMode:()=>z,Suspense:()=>Zi,SuspenseList:()=>ei,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:()=>kf,cloneElement:()=>ti,createContext:()=>lr,createElement:()=>v,createFactory:()=>Tf,createPortal:()=>dn,createRef:()=>Um,default:()=>pn,findDOMNode:()=>Ef,flushSync:()=>Lo,forwardRef:()=>K,hydrate:()=>wf,isElement:()=>Df,isFragment:()=>Rf,isMemo:()=>Pf,isValidElement:()=>un,lazy:()=>vf,memo:()=>df,render:()=>_f,startTransition:()=>gl,unmountComponentAtNode:()=>Af,unstable_batchedUpdates:()=>xf,useCallback:()=>oe,useContext:()=>Ln,useDebugValue:()=>dl,useDeferredValue:()=>vl,useEffect:()=>W,useErrorBoundary:()=>yN,useId:()=>ur,useImperativeHandle:()=>Eo,useInsertionEffect:()=>bl,useLayoutEffect:()=>gt,useMemo:()=>Se,useReducer:()=>Qi,useRef:()=>q,useState:()=>D,useSyncExternalStore:()=>fl,useTransition:()=>yl,version:()=>xN});function lf(e,t){for(var n in t)e[n]=t[n];return e}function ml(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 fl(e,t){var n=t(),r=D({t:{__:n,u:t}}),i=r[0].t,a=r[1];return gt(function(){i.__=n,i.u=t,hl(i)&&a({t:i})},[e,n,t]),W(function(){return hl(i)&&a({t:i}),e(function(){hl(i)&&a({t:i})})},[e]),n}function hl(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 gl(e){e()}function vl(e){return e}function yl(){return[!1,gl]}var bl=gt;function Do(e,t){this.props=e,this.context=t}function df(e,t){function n(i){var a=this.props.ref;return a!=i.ref&&a&&(typeof a=="function"?a(null):a.current=null),t?!t(this.props,i)||a!=i.ref:ml(this.props,i)}function r(i){return this.shouldComponentUpdate=n,v(e,i)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Do.prototype=new It).isPureReactComponent=!0,Do.prototype.shouldComponentUpdate=function(e,t){return ml(this.props,e)||ml(this.state,t)};var uf=me.__b;me.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),uf&&uf(e)};var SN=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function K(e){function t(n){var r=lf({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=SN,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var pf=function(e,t){return e==null?null:cn(cn(e).map(t))},Kt={map:pf,forEach:pf,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},CN=me.__e;me.__e=function(e,t,n,r){if(e.then){for(var i,a=t;a=a.__;)if((i=a.__c)&&i.__c)return t.__e??(t.__e=n.__e,t.__k=n.__k),i.__c(e,t)}CN(e,t,n,r)};var mf=me.unmount;function ff(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=lf({},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 ff(r,t,n)})),e}function hf(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return hf(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 Zi(){this.__u=0,this.o=null,this.__b=null}function gf(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function vf(e){var t,n,r,i=null;function a(s){if(t||(t=e()).then(function(c){c&&(i=c.default||c),r=!0},function(c){n=c,r=!0}),n)throw n;if(!r)throw t;return i?v(i,s):null}return a.displayName="Lazy",a.__f=!0,a}function ei(){this.i=null,this.l=null}me.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),mf&&mf(e)},(Zi.prototype=new It).__c=function(e,t){var n=t.__c,r=this;r.o??=[],r.o.push(n);var i=gf(r.__v),a=!1,s=function(){a||r.__z||(a=!0,n.__R=null,i?i(l):l())};n.__R=s;var c=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=hf(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)},Zi.prototype.componentWillUnmount=function(){this.o=[]},Zi.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]=ff(this.__b,n,r.__O=r.__P)}this.__b=null}var i=t.__a&&v(z,null,e.fallback);return i&&(i.__u&=-33),[v(z,null,t.__a?null:e.children),i]};var yf=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 NN(e){return this.getChildContext=function(){return e.context},e.children}function IN(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){He(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(i,a){this.childNodes.push(i),t.h.insertBefore(i,a)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),t.h.removeChild(i)}}}He(v(NN,{context:t.context},e.__v),t.v)}function dn(e,t){var n=v(IN,{__v:e,h:t});return n.containerInfo=t,n}(ei.prototype=new It).__a=function(e){var t=this,n=gf(t.__v),r=t.l.get(e);return r[0]++,function(i){var a=function(){t.props.revealOrder?(r.push(i),yf(t,e,r)):i()};n?n(a):a()}},ei.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},ei.prototype.componentDidUpdate=ei.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){yf(e,n,t)})};var bf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,kN=/^(?: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]/,TN=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,RN=/[A-Z0-9]/g,PN=typeof document<"u",AN=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function _f(e,t,n){return t.__k??(t.textContent=""),He(e,t),typeof n=="function"&&n(),e?e.__c:null}function wf(e,t,n){return Ym(e,t),typeof n=="function"&&n(),e?e.__c:null}It.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(It.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Sf=me.event;me.event=function(e){return Sf&&(e=Sf(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var _l,EN={configurable:!0,get:function(){return this.class}},Cf=me.vnode;me.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,i={},a=r.indexOf("-")==-1;for(var s in n){var c=n[s];if(!(s==="value"&&"defaultValue"in n&&c==null||PN&&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"||AN(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":TN.test(s)&&(s=l):l=s="oninput":a&&kN.test(s)?s=s.replace(RN,"-$&").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",EN)):n.className&&(i.class=i.className=n.className),t.props=i})(e),e.$$typeof=bf,Cf&&Cf(e)};var Nf=me.__r;me.__r=function(e){Nf&&Nf(e),_l=e.__c};var If=me.diffed;me.diffed=function(e){If&&If(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),_l=null};var kf={ReactCurrentDispatcher:{current:{readContext:function(e){return _l.__n[e.__c].props.value},useCallback:oe,useContext:Ln,useDebugValue:dl,useDeferredValue:vl,useEffect:W,useId:ur,useImperativeHandle:Eo,useInsertionEffect:bl,useLayoutEffect:gt,useMemo:Se,useReducer:Qi,useRef:q,useState:D,useSyncExternalStore:fl,useTransition:yl}}},xN="18.3.1";function Tf(e){return v.bind(null,e)}function un(e){return!!e&&e.$$typeof===bf}function Rf(e){return un(e)&&e.type===z}function Pf(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function ti(e){return un(e)?vN.apply(null,arguments):e}function Af(e){return!!e.__k&&(He(null,e),!0)}function Ef(e){return e&&(e.base||e.nodeType===1&&e)||null}var xf=function(e,t){return e(t)},Lo=function(e,t){var n=me.debounceRendering;me.debounceRendering=function(i){return i()};var r=e(t);return me.debounceRendering=n,r},Df=un,pn={useState:D,useId:ur,useReducer:Qi,useEffect:W,useLayoutEffect:gt,useInsertionEffect:bl,useTransition:yl,useDeferredValue:vl,useSyncExternalStore:fl,startTransition:gl,useRef:q,useImperativeHandle:Eo,useMemo:Se,useCallback:oe,useContext:Ln,useDebugValue:dl,version:"18.3.1",Children:Kt,render:_f,hydrate:wf,unmountComponentAtNode:Af,createPortal:dn,createElement:v,createContext:lr,createFactory:Tf,cloneElement:ti,createRef:Um,Fragment:z,isValidElement:un,isElement:Df,isFragment:Rf,isMemo:Pf,findDOMNode:Ef,Component:It,PureComponent:Do,memo:df,forwardRef:K,flushSync:Lo,unstable_batchedUpdates:xf,StrictMode:z,Suspense:Zi,SuspenseList:ei,lazy:vf,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:kf},XB=!!(typeof window<"u"&&window.document&&window.document.createElement);function X(e,t,{checkForDefaultPrevented:n=!0}={}){return function(i){if(e?.(i),n===!1||!i.defaultPrevented)return t?.(i)}}function Lf(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function $o(...e){return t=>{let n=!1;const r=e.map(i=>{const a=Lf(i,t);return!n&&typeof a=="function"&&(n=!0),a});if(n)return()=>{for(let i=0;i<r.length;i++){const a=r[i];typeof a=="function"?a():Lf(e[i],null)}}}}function be(...e){return oe($o(...e),e)}function DN(e,t){const n=lr(t),r=a=>{const{children:s,...c}=a,l=Se(()=>c,Object.values(c));return o(n.Provider,{value:l,children:s})};r.displayName=e+"Provider";function i(a){const s=Ln(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return[r,i]}function dt(e,t=[]){let n=[];function r(a,s){const c=lr(s),l=n.length;n=[...n,s];const d=p=>{const{scope:m,children:f,...y}=p,g=m?.[e]?.[l]||c,h=Se(()=>y,Object.values(y));return o(g.Provider,{value:h,children:f})};d.displayName=a+"Provider";function u(p,m){const f=m?.[e]?.[l]||c,y=Ln(f);if(y)return y;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${a}\``)}return[d,u]}const i=()=>{const a=n.map(s=>lr(s));return function(c){const l=c?.[e]||a;return Se(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return i.scopeName=e,[r,LN(i,...t)]}function LN(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(a){const s=r.reduce((c,{useScope:l,scopeName:d})=>{const u=l(a)[`__scope${d}`];return{...c,...u}},{});return Se(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}var Je=globalThis?.document?gt:()=>{},$N=cf[" useId ".trim().toString()]||(()=>{}),MN=0;function ut(e){const[t,n]=D($N());return Je(()=>{e||n(r=>r??String(MN++))},[e]),e||(t?`radix-${t}`:"")}var jN=cf[" useInsertionEffect ".trim().toString()]||Je;function kt({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[i,a,s]=ON({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:i;{const d=q(e!==void 0);W(()=>{const u=d.current;u!==c&&console.warn(`${r} is changing from ${u?"controlled":"uncontrolled"} to ${c?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=c},[c,r])}return[l,oe(d=>{if(c){const u=FN(d)?d(e):d;u!==e&&s.current?.(u)}else a(d)},[c,e,a,s])]}function ON({defaultProp:e,onChange:t}){const[n,r]=D(e),i=q(n),a=q(t);return jN(()=>{a.current=t},[t]),W(()=>{i.current!==n&&(a.current?.(n),i.current=n)},[n,i]),[n,r,a]}function FN(e){return typeof e=="function"}function pr(e){const t=BN(e),n=K((r,i)=>{const{children:a,...s}=r,c=Kt.toArray(a),l=c.find(qN);if(l){const d=l.props.children,u=c.map(p=>p===l?Kt.count(d)>1?Kt.only(null):un(d)?d.props.children:null:p);return o(t,{...s,ref:i,children:un(d)?ti(d,void 0,u):null})}return o(t,{...s,ref:i,children:a})});return n.displayName=`${e}.Slot`,n}function BN(e){const t=K((n,r)=>{const{children:i,...a}=n;if(un(i)){const s=HN(i),c=GN(a,i.props);return i.type!==z&&(c.ref=r?$o(r,s):s),ti(i,c)}return Kt.count(i)>1?Kt.only(null):null});return t.displayName=`${e}.SlotClone`,t}var $f=Symbol("radix.slottable");function UN(e){const t=({children:n})=>o(z,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=$f,t}function qN(e){return un(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===$f}function GN(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...s)=>{const c=a(...s);return i(...s),c}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}function HN(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var le=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const n=pr(`Primitive.${t}`),r=K((i,a)=>{const{asChild:s,...c}=i,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o(l,{...c,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wl(e,t){e&&Lo(()=>e.dispatchEvent(t))}function pt(e){const t=q(e);return W(()=>{t.current=e}),Se(()=>(...n)=>t.current?.(...n),[])}function KN(e,t=globalThis?.document){const n=pt(e);W(()=>{const r=i=>{i.key==="Escape"&&n(i)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var VN="DismissableLayer",Sl="dismissableLayer.update",WN="dismissableLayer.pointerDownOutside",zN="dismissableLayer.focusOutside",Mf,jf=lr({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),mr=K((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:s,onDismiss:c,...l}=e,d=Ln(jf),[u,p]=D(null),m=u?.ownerDocument??globalThis?.document,[,f]=D({}),y=be(t,x=>p(x)),g=Array.from(d.layers),[h]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(h),w=u?g.indexOf(u):-1,_=d.layersWithOutsidePointerEventsDisabled.size>0,I=w>=b,N=YN(x=>{const j=x.target,B=[...d.branches].some(P=>P.contains(j));!I||B||(i?.(x),s?.(x),x.defaultPrevented||c?.())},m),T=XN(x=>{const j=x.target;[...d.branches].some(B=>B.contains(j))||(a?.(x),s?.(x),x.defaultPrevented||c?.())},m);return KN(x=>{w===d.layers.size-1&&(r?.(x),!x.defaultPrevented&&c&&(x.preventDefault(),c()))},m),W(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Mf=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Ff(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Mf)}},[u,m,n,d]),W(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Ff())},[u,d]),W(()=>{const x=()=>f({});return document.addEventListener(Sl,x),()=>document.removeEventListener(Sl,x)},[]),o(le.div,{...l,ref:y,style:{pointerEvents:_?I?"auto":"none":void 0,...e.style},onFocusCapture:X(e.onFocusCapture,T.onFocusCapture),onBlurCapture:X(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:X(e.onPointerDownCapture,N.onPointerDownCapture)})});mr.displayName=VN;var JN="DismissableLayerBranch",Of=K((e,t)=>{const n=Ln(jf),r=q(null),i=be(t,r);return W(()=>{const a=r.current;if(a)return n.branches.add(a),()=>{n.branches.delete(a)}},[n.branches]),o(le.div,{...e,ref:i})});Of.displayName=JN;function YN(e,t=globalThis?.document){const n=pt(e),r=q(!1),i=q(()=>{});return W(()=>{const a=c=>{if(c.target&&!r.current){let l=function(){Bf(WN,n,d,{discrete:!0})};const d={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",i.current),i.current=l,t.addEventListener("click",i.current,{once:!0})):l()}else t.removeEventListener("click",i.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",a),t.removeEventListener("click",i.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function XN(e,t=globalThis?.document){const n=pt(e),r=q(!1);return W(()=>{const i=a=>{a.target&&!r.current&&Bf(zN,n,{originalEvent:a},{discrete:!1})};return t.addEventListener("focusin",i),()=>t.removeEventListener("focusin",i)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Ff(){const e=new CustomEvent(Sl);document.dispatchEvent(e)}function Bf(e,t,n,{discrete:r}){const i=n.originalEvent.target,a=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?wl(i,a):i.dispatchEvent(a)}var QN=mr,ZN=Of,Cl="focusScope.autoFocusOnMount",Nl="focusScope.autoFocusOnUnmount",Uf={bubbles:!1,cancelable:!0},eI="FocusScope",ea=K((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...s}=e,[c,l]=D(null),d=pt(i),u=pt(a),p=q(null),m=be(t,g=>l(g)),f=q({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;W(()=>{if(r){let g=function(_){if(f.paused||!c)return;const I=_.target;c.contains(I)?p.current=I:$n(p.current,{select:!0})},h=function(_){if(f.paused||!c)return;const I=_.relatedTarget;I!==null&&(c.contains(I)||$n(p.current,{select:!0}))},b=function(_){if(document.activeElement===document.body)for(const I of _)I.removedNodes.length>0&&$n(c)};document.addEventListener("focusin",g),document.addEventListener("focusout",h);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",h),w.disconnect()}}},[r,c,f.paused]),W(()=>{if(c){Hf.add(f);const g=document.activeElement;if(!c.contains(g)){const h=new CustomEvent(Cl,Uf);c.addEventListener(Cl,d),c.dispatchEvent(h),h.defaultPrevented||(tI(oI(qf(c)),{select:!0}),document.activeElement===g&&$n(c))}return()=>{c.removeEventListener(Cl,d),setTimeout(()=>{const h=new CustomEvent(Nl,Uf);c.addEventListener(Nl,u),c.dispatchEvent(h),h.defaultPrevented||$n(g??document.body,{select:!0}),c.removeEventListener(Nl,u),Hf.remove(f)},0)}}},[c,d,u,f]);const y=oe(g=>{if(!n&&!r||f.paused)return;const h=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,b=document.activeElement;if(h&&b){const w=g.currentTarget,[_,I]=nI(w);_&&I?!g.shiftKey&&b===I?(g.preventDefault(),n&&$n(_,{select:!0})):g.shiftKey&&b===_&&(g.preventDefault(),n&&$n(I,{select:!0})):b===w&&g.preventDefault()}},[n,r,f.paused]);return o(le.div,{tabIndex:-1,...s,ref:m,onKeyDown:y})});ea.displayName=eI;function tI(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if($n(r,{select:t}),document.activeElement!==n)return}function nI(e){const t=qf(e);return[Gf(t,e),Gf(t.reverse(),e)]}function qf(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Gf(e,t){for(const n of e)if(!rI(n,{upTo:t}))return n}function rI(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function iI(e){return e instanceof HTMLInputElement&&"select"in e}function $n(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&iI(e)&&t&&e.select()}}var Hf=aI();function aI(){let e=[];return{add(t){const n=e[0];t!==n&&n?.pause(),e=Kf(e,t),e.unshift(t)},remove(t){e=Kf(e,t),e[0]?.resume()}}}function Kf(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function oI(e){return e.filter(t=>t.tagName!=="A")}var sI="Portal",fr=K((e,t)=>{const{container:n,...r}=e,[i,a]=D(!1);Je(()=>a(!0),[]);const s=n||i&&globalThis?.document?.body;return s?pn.createPortal(o(le.div,{...r,ref:t}),s):null});fr.displayName=sI;function cI(e,t){return Qi((n,r)=>t[n][r]??n,e)}var ot=e=>{const{present:t,children:n}=e,r=lI(t),i=typeof n=="function"?n({present:r.isPresent}):Kt.only(n),a=be(r.ref,dI(i));return typeof n=="function"||r.isPresent?ti(i,{ref:a}):null};ot.displayName="Presence";function lI(e){const[t,n]=D(),r=q(null),i=q(e),a=q("none"),[s,c]=cI(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return W(()=>{const l=Mo(r.current);a.current=s==="mounted"?l:"none"},[s]),Je(()=>{const l=r.current,d=i.current;if(d!==e){const u=a.current,p=Mo(l);e?c("MOUNT"):p==="none"||l?.display==="none"?c("UNMOUNT"):c(d&&u!==p?"ANIMATION_OUT":"UNMOUNT"),i.current=e}},[e,c]),Je(()=>{if(t){let l;const d=t.ownerDocument.defaultView??window,u=m=>{const f=Mo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&f&&(c("ANIMATION_END"),!i.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",l=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=m=>{m.target===t&&(a.current=Mo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{d.clearTimeout(l),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:oe(l=>{r.current=l?getComputedStyle(l):null,n(l)},[])}}function Mo(e){return e?.animationName||"none"}function dI(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Il=0;function jo(){W(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Vf()),document.body.insertAdjacentElement("beforeend",e[1]??Vf()),Il++,()=>{Il===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Il--}},[])}function Vf(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Vt=function(){return Vt=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},Vt.apply(this,arguments)};function Wf(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 uI(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||(a=Array.prototype.slice.call(t,0,r)),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var Oo="right-scroll-bar-position",Fo="width-before-scroll-bar",pI="with-scroll-bars-hidden",mI="--removed-body-scroll-bar-size";function kl(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function fI(e,t){var n=D(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 hI=typeof window<"u"?gt:W,zf=new WeakMap;function gI(e,t){var n=fI(t||null,function(r){return e.forEach(function(i){return kl(i,r)})});return hI(function(){var r=zf.get(n);if(r){var i=new Set(r),a=new Set(e),s=n.current;i.forEach(function(c){a.has(c)||kl(c,null)}),a.forEach(function(c){i.has(c)||kl(c,s)})}zf.set(n,e)},[e]),n}function vI(e){return e}function yI(e,t){t===void 0&&(t=vI);var n=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var a=t(i,r);return n.push(a),function(){n=n.filter(function(s){return s!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(s){return i(s)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var s=n;n=[],s.forEach(i),a=n}var c=function(){var d=a;a=[],d.forEach(i)},l=function(){return Promise.resolve().then(c)};l(),n={push:function(d){a.push(d),l()},filter:function(d){return a=a.filter(d),n}}}}}function bI(e){e===void 0&&(e={});var t=yI(null);return t.options=Vt({async:!0,ssr:!1},e),t}var Jf=function(e){var t=e.sideCar,n=Wf(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 v(r,Vt({},n))};Jf.isSideCarExport=!0;function _I(e,t){return e.useMedium(t),Jf}var Yf=bI(),Tl=function(){},Bo=K(function(e,t){var n=q(null),r=D({onScrollCapture:Tl,onWheelCapture:Tl,onTouchMoveCapture:Tl}),i=r[0],a=r[1],s=e.forwardProps,c=e.children,l=e.className,d=e.removeScrollBar,u=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,y=e.noIsolation,g=e.inert,h=e.allowPinchZoom,b=e.as,w=b===void 0?"div":b,_=e.gapMode,I=Wf(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=m,T=gI([n,t]),x=Vt(Vt({},I),i);return v(z,null,u&&v(N,{sideCar:Yf,removeScrollBar:d,shards:p,noRelative:f,noIsolation:y,inert:g,setCallbacks:a,allowPinchZoom:!!h,lockRef:n,gapMode:_}),s?ti(Kt.only(c),Vt(Vt({},x),{ref:T})):v(w,Vt({},x,{className:l,ref:T}),c))});Bo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Bo.classNames={fullWidth:Fo,zeroRight:Oo};var Xf,wI=function(){if(Xf)return Xf;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function SI(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=wI();return t&&e.setAttribute("nonce",t),e}function CI(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function NI(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}var II=function(){var e=0,t=null;return{add:function(n){e==0&&(t=SI())&&(CI(t,n),NI(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},kI=function(){var e=II();return function(t,n){W(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Qf=function(){var e=kI(),t=function(n){var r=n.styles,i=n.dynamic;return e(r,i),null};return t},TI={left:0,top:0,right:0,gap:0},Rl=function(e){return parseInt(e||"",10)||0},RI=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[Rl(n),Rl(r),Rl(i)]},PI=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return TI;var t=RI(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])}},AI=Qf(),ta="data-scroll-locked",EI=function(e,t,n,r){var i=e.left,a=e.top,s=e.right,c=e.gap;return n===void 0&&(n="margin"),`
|
|
2
|
+
.`.concat(pI,` {
|
|
3
3
|
overflow: hidden `).concat(r,`;
|
|
4
4
|
padding-right: `).concat(c,"px ").concat(r,`;
|
|
5
5
|
}
|
|
6
|
-
body[`).concat(
|
|
6
|
+
body[`).concat(ta,`] {
|
|
7
7
|
overflow: hidden `).concat(r,`;
|
|
8
8
|
overscroll-behavior: contain;
|
|
9
9
|
`).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
|
|
@@ -16,67 +16,67 @@
|
|
|
16
16
|
`),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
.`).concat(
|
|
19
|
+
.`).concat(Oo,` {
|
|
20
20
|
right: `).concat(c,"px ").concat(r,`;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
.`).concat(
|
|
23
|
+
.`).concat(Fo,` {
|
|
24
24
|
margin-right: `).concat(c,"px ").concat(r,`;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
.`).concat(
|
|
27
|
+
.`).concat(Oo," .").concat(Oo,` {
|
|
28
28
|
right: 0 `).concat(r,`;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
.`).concat(
|
|
31
|
+
.`).concat(Fo," .").concat(Fo,` {
|
|
32
32
|
margin-right: 0 `).concat(r,`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
body[`).concat(
|
|
36
|
-
`).concat(
|
|
35
|
+
body[`).concat(ta,`] {
|
|
36
|
+
`).concat(mI,": ").concat(c,`px;
|
|
37
37
|
}
|
|
38
|
-
`)},
|
|
38
|
+
`)},Zf=function(){var e=parseInt(document.body.getAttribute("data-scroll-locked")||"0",10);return isFinite(e)?e:0},xI=function(){W(function(){return document.body.setAttribute(ta,(Zf()+1).toString()),function(){var e=Zf()-1;e<=0?document.body.removeAttribute(ta):document.body.setAttribute(ta,e.toString())}},[])},DI=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?"margin":r;xI();var a=Se(function(){return PI(i)},[i]);return v(AI,{styles:EI(a,!t,i,n?"":"!important")})},Pl=!1;if(typeof window<"u")try{var Uo=Object.defineProperty({},"passive",{get:function(){return Pl=!0,!0}});window.addEventListener("test",Uo,Uo),window.removeEventListener("test",Uo,Uo)}catch{Pl=!1}var ni=Pl?{passive:!1}:!1,LI=function(e){return e.tagName==="TEXTAREA"},eh=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LI(e)&&n[t]==="visible")},$I=function(e){return eh(e,"overflowY")},MI=function(e){return eh(e,"overflowX")},th=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host),nh(e,r)){var i=rh(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},jI=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},OI=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},nh=function(e,t){return e==="v"?$I(t):MI(t)},rh=function(e,t){return e==="v"?jI(t):OI(t)},FI=function(e,t){return e==="h"&&t==="rtl"?-1:1},BI=function(e,t,n,r,i){var a=FI(e,window.getComputedStyle(t).direction),s=a*r,c=n.target,l=t.contains(c),d=!1,u=s>0,p=0,m=0;do{if(!c)break;var f=rh(e,c),y=f[0],g=f[1]-f[2]-a*y;(y||g)&&nh(e,c)&&(p+=g,m+=y);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(m)<1||!i&&-s>m))&&(d=!0),d},qo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ih=function(e){return[e.deltaX,e.deltaY]},ah=function(e){return e&&"current"in e?e.current:e},UI=function(e,t){return e[0]===t[0]&&e[1]===t[1]},qI=function(e){return`
|
|
39
39
|
.block-interactivity-`.concat(e,` {pointer-events: none;}
|
|
40
40
|
.allow-interactivity-`).concat(e,` {pointer-events: all;}
|
|
41
|
-
`)},
|
|
41
|
+
`)},GI=0,ri=[];function HI(e){var t=q([]),n=q([0,0]),r=q(),i=D(GI++)[0],a=D(Qf)[0],s=q(e);W(function(){s.current=e},[e]),W(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var g=uI([e.lockRef.current],(e.shards||[]).map(ah),!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=oe(function(g,h){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!s.current.allowPinchZoom;var b=qo(g),w=n.current,_="deltaX"in g?g.deltaX:w[0]-b[0],I="deltaY"in g?g.deltaY:w[1]-b[1],N,T=g.target,x=Math.abs(_)>Math.abs(I)?"h":"v";if("touches"in g&&x==="h"&&T.type==="range")return!1;var j=window.getSelection(),B=j&&j.anchorNode;if(B&&(B===T||B.contains(T)))return!1;var P=th(x,T);if(!P)return!0;if(P?N=x:(N=x==="v"?"h":"v",P=th(x,T)),!P)return!1;if(!r.current&&"changedTouches"in g&&(_||I)&&(r.current=N),!N)return!0;var F=r.current||N;return BI(F,h,g,F==="h"?_:I,!0)},[]),l=oe(function(g){var h=g;if(!(!ri.length||ri[ri.length-1]!==a)){var b="deltaY"in h?ih(h):qo(h),w=t.current.filter(function(I){return I.name===h.type&&(I.target===h.target||h.target===I.shadowParent)&&UI(I.delta,b)})[0];if(w&&w.should){h.cancelable&&h.preventDefault();return}if(!w){var _=(s.current.shards||[]).map(ah).filter(Boolean).filter(function(I){return I.contains(h.target)});(_.length>0?c(h,_[0]):!s.current.noIsolation)&&h.cancelable&&h.preventDefault()}}},[]),d=oe(function(g,h,b,w){var _={name:g,delta:h,target:b,should:w,shadowParent:KI(b)};t.current.push(_),setTimeout(function(){t.current=t.current.filter(function(I){return I!==_})},1)},[]),u=oe(function(g){n.current=qo(g),r.current=void 0},[]),p=oe(function(g){d(g.type,ih(g),g.target,c(g,e.lockRef.current))},[]),m=oe(function(g){d(g.type,qo(g),g.target,c(g,e.lockRef.current))},[]);W(function(){return ri.push(a),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:m}),document.addEventListener("wheel",l,ni),document.addEventListener("touchmove",l,ni),document.addEventListener("touchstart",u,ni),function(){ri=ri.filter(function(g){return g!==a}),document.removeEventListener("wheel",l,ni),document.removeEventListener("touchmove",l,ni),document.removeEventListener("touchstart",u,ni)}},[]);var f=e.removeScrollBar,y=e.inert;return v(z,null,y?v(a,{styles:qI(i)}):null,f?v(DI,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function KI(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var VI=_I(Yf,HI),na=K(function(e,t){return v(Bo,Vt({},e,{ref:t,sideCar:VI}))});na.classNames=Bo.classNames;var WI=function(e){return typeof document>"u"?null:(Array.isArray(e)?e[0]:e).ownerDocument.body},ii=new WeakMap,Go=new WeakMap,Ho={},Al=0,oh=function(e){return e&&(e.host||oh(e.parentNode))},zI=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=oh(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})},JI=function(e,t,n,r){var i=zI(t,Array.isArray(e)?e:[e]);Ho[n]||(Ho[n]=new WeakMap);var a=Ho[n],s=[],c=new Set,l=new Set(i),d=function(p){!p||c.has(p)||(c.add(p),d(p.parentNode))};i.forEach(d);var u=function(p){!p||l.has(p)||Array.prototype.forEach.call(p.children,function(m){if(c.has(m))u(m);else try{var f=m.getAttribute(r),y=f!==null&&f!=="false",g=(ii.get(m)||0)+1,h=(a.get(m)||0)+1;ii.set(m,g),a.set(m,h),s.push(m),g===1&&y&&Go.set(m,!0),h===1&&m.setAttribute(n,"true"),y||m.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",m,b)}})};return u(t),c.clear(),Al++,function(){s.forEach(function(p){var m=ii.get(p)-1,f=a.get(p)-1;ii.set(p,m),a.set(p,f),m||(Go.has(p)||p.removeAttribute(r),Go.delete(p)),f||p.removeAttribute(n)}),Al--,Al||(ii=new WeakMap,ii=new WeakMap,Go=new WeakMap,Ho={})}},Ko=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),i=t||WI(e);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),JI(r,i,n,"aria-hidden")):function(){return null}},Vo="Dialog",[sh,QB]=dt(Vo),[YI,$t]=sh(Vo),ch=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!0}=e,c=q(null),l=q(null),[d,u]=kt({prop:r,defaultProp:i??!1,onChange:a,caller:Vo});return o(YI,{scope:t,triggerRef:c,contentRef:l,contentId:ut(),titleId:ut(),descriptionId:ut(),open:d,onOpenChange:u,onOpenToggle:oe(()=>u(p=>!p),[u]),modal:s,children:n})};ch.displayName=Vo;var lh="DialogTrigger",XI=K((e,t)=>{const{__scopeDialog:n,...r}=e,i=$t(lh,n),a=be(t,i.triggerRef);return o(le.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Dl(i.open),...r,ref:a,onClick:X(e.onClick,i.onOpenToggle)})});XI.displayName=lh;var El="DialogPortal",[QI,dh]=sh(El,{forceMount:void 0}),uh=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:i}=e,a=$t(El,t);return o(QI,{scope:t,forceMount:n,children:Kt.map(r,s=>o(ot,{present:n||a.open,children:o(fr,{asChild:!0,container:i,children:s})}))})};uh.displayName=El;var Wo="DialogOverlay",ph=K((e,t)=>{const n=dh(Wo,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=$t(Wo,e.__scopeDialog);return a.modal?o(ot,{present:r||a.open,children:o(ek,{...i,ref:t})}):null});ph.displayName=Wo;var ZI=pr("DialogOverlay.RemoveScroll"),ek=K((e,t)=>{const{__scopeDialog:n,...r}=e,i=$t(Wo,n);return o(na,{as:ZI,allowPinchZoom:!0,shards:[i.contentRef],children:o(le.div,{"data-state":Dl(i.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),hr="DialogContent",mh=K((e,t)=>{const n=dh(hr,e.__scopeDialog),{forceMount:r=n.forceMount,...i}=e,a=$t(hr,e.__scopeDialog);return o(ot,{present:r||a.open,children:a.modal?o(tk,{...i,ref:t}):o(nk,{...i,ref:t})})});mh.displayName=hr;var tk=K((e,t)=>{const n=$t(hr,e.__scopeDialog),r=q(null),i=be(t,n.contentRef,r);return W(()=>{const a=r.current;if(a)return Ko(a)},[]),o(fh,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:X(e.onCloseAutoFocus,a=>{a.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:X(e.onPointerDownOutside,a=>{const s=a.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&a.preventDefault()}),onFocusOutside:X(e.onFocusOutside,a=>a.preventDefault())})}),nk=K((e,t)=>{const n=$t(hr,e.__scopeDialog),r=q(!1),i=q(!1);return o(fh,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||n.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;n.triggerRef.current?.contains(s)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),fh=K((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,...s}=e,c=$t(hr,n),l=q(null),d=be(t,l);return jo(),o(z,{children:[o(ea,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o(mr,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":Dl(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),o(z,{children:[o(ak,{titleId:c.titleId}),o(sk,{contentRef:l,descriptionId:c.descriptionId})]})]})}),xl="DialogTitle",hh=K((e,t)=>{const{__scopeDialog:n,...r}=e,i=$t(xl,n);return o(le.h2,{id:i.titleId,...r,ref:t})});hh.displayName=xl;var gh="DialogDescription",rk=K((e,t)=>{const{__scopeDialog:n,...r}=e,i=$t(gh,n);return o(le.p,{id:i.descriptionId,...r,ref:t})});rk.displayName=gh;var vh="DialogClose",ik=K((e,t)=>{const{__scopeDialog:n,...r}=e,i=$t(vh,n);return o(le.button,{type:"button",...r,ref:t,onClick:X(e.onClick,()=>i.onOpenChange(!1))})});ik.displayName=vh;function Dl(e){return e?"open":"closed"}var yh="DialogTitleWarning",[ZB,bh]=DN(yh,{contentName:hr,titleName:xl,docsSlug:"dialog"}),ak=({titleId:e})=>{const t=bh(yh),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
|
|
42
42
|
|
|
43
43
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
44
44
|
|
|
45
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return z(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},qT="DialogDescriptionWarning",HT=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${If(qT).contentName}}.`;return z(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},KT=gf,VT=bf,WT=_f,zT=wf;function Fr({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:a=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:m,overlayId:f,slotId:g}){return o(KT,{modal:a,open:p,onOpenChange:u,children:p?o(VT,{children:[o(WT,{asChild:!0,children:o("div",{className:m,id:f})}),o(zT,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:o("div",{role:"dialog",className:r,id:i,onClick:h=>{h.target===h.currentTarget&&u(!1)},tabIndex:-1,children:n??(g?o("div",{id:g}):null)})})]}):null})}var kf=500,Eo=null,Ui=null,Gi=null;function qi(e){return Ui?Ui(e)?(Gi=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(Gi=document.activeElement instanceof HTMLElement?document.activeElement:null,Eo=e,!0)}function rt(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Ef(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 rl(e){return e.recipientKind==="identity"?rt({recipientKind:"identity",identityId:e.identityId}):rt({recipientKind:"team",teamId:e.teamId})}function JT(e,t){return rl(e)===rt(t)}function Pf(e,t){return e instanceof bc?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Af({checked:e,description:t,disabled:n,label:r,onChange:i}){const a=`recipient-policy-choice-${Dr()}`;return o("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:a,children:[o("input",{checked:e,disabled:n,id:a,onChange:i,type:"checkbox"}),o("span",{children:[o("strong",{className:"recipient-policy-management-name",children:r}),o("span",{className:"small recipient-policy-management-description",children:t})]})]})}function YT(e,t){const n=e.teamMemberships.filter(s=>s.status==="active"),r=new Map(e.identities.map(s=>[s.identityId,s])),i=[...e.teams.filter(s=>s.status==="active").map(s=>{const c=n.filter(l=>l.teamId===s.teamId).map(l=>r.get(l.identityId)?.displayName).filter(l=>!!l);return{key:rt({recipientKind:"team",teamId:s.teamId}),label:s.displayName,description:`Team · ${c.length.toLocaleString()} current ${c.length===1?"member":"members"}${c.length?`: ${c.join(", ")}`:""}`}}),...e.identities.filter(s=>s.status==="active"||s.status==="pending").map(s=>({key:rt({recipientKind:"identity",identityId:s.identityId}),label:s.displayName,description:`Identity · ${s.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return i;const a=new Set(i.map(s=>s.key));for(const s of e.projectRecipients){if(s.status!=="active"||s.canonicalProjectIdentity!==t.projectId)continue;const c=rl(s);if(!a.has(c)){if(s.recipientKind==="team"){const l=e.teams.find(d=>d.teamId===s.teamId);i.push({key:c,label:l?.displayName??"Unavailable Team",description:`${l?.status==="archived"?"Archived Team":"Unavailable Team"} · existing access can only be removed`})}else{const l=r.get(s.identityId);i.push({key:c,label:l?.displayName??"Unavailable Identity",description:`${l?.status==="merged"?"Merged Identity":"Unavailable Identity"} · existing access can only be removed`})}a.add(c)}}return i}function xf(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function XT(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(rl):n.filter(r=>JT(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function QT(e,t,n){const r=t.mode==="recipient-add"?e.filter(s=>!n.includes(s.canonicalProjectIdentity)):e,i=r.map(s=>({...s,description:`${s.existingMemoryCount.toLocaleString()} existing memories`}));if(t.mode!=="recipient-manage")return i;const a=new Set(r.map(s=>s.canonicalProjectIdentity));for(const s of n)a.has(s)||i.push({canonicalProjectIdentity:s,displayName:s,existingMemoryCount:0,description:"Unavailable Project · existing access can only be removed"});return i}function ZT(e,t,n){return e.mode==="project-add"?xf(e).flatMap(r=>t.flatMap(i=>{const a=Ef(i);return a?[{canonicalProjectIdentity:r,recipient:a,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Ef(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 eN(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 Rf(e,t){let n=!1,r=!1,i=!1,a=!1;const s=rt(t);for(const c of e){const{change:l,outcome:d}=c;rt(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(a=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!a?"Already has access":a&&!i?"Already without access":"No changes"}function tN(e){const t=new Set(e.selectedRecipients.map(rt)),n=new Map;for(const r of e.normalizedChanges){const i=rt(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function nN(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function rN({preview:e,recipientLabels:t}){const n=nN(e.effectiveDevices),r=tN(e);return o("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[o("section",{"aria-labelledby":"recipient-policy-review-projects",children:[o("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),o("ul",{children:e.projects.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:i.displayName}),o("span",{children:[" ","— Access changes affect ",i.existingMemoryCount.toLocaleString()," existing memories",i.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},i.canonicalProjectIdentity))})]}),o("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[o("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),o("ul",{children:[e.selectedRecipients.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:i.displayName})," ",o("span",{children:["— ",Rf(e.outcomes,i)," · "]}),i.recipientKind==="identity"?o("span",{children:"Identity · locally verified"}):o("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",i.currentMembers.length.toLocaleString()," current"," ",i.currentMembers.length===1?"member":"members",i.currentMembers.length?o(Z,{children:[":"," ",o("span",{className:"recipient-policy-management-member-names",children:i.currentMembers.map(a=>a.displayName).join(", ")})]}):null,". Future Team members"," ",i.futureMembersInherit?"inherit":"do not inherit"," access."]})]},rt(i))),r.map(i=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:t.get(rt(i))??(i.recipientKind==="team"?i.teamId:i.identityId)})," ",o("span",{children:["— ",Rf(e.outcomes,i)," ·"," ",i.recipientKind==="team"?"Team":"Identity"]})]},rt(i)))]})]}),o("section",{"aria-labelledby":"recipient-policy-review-availability",children:[o("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),n.length?o(Z,{children:[o("p",{children:["After the update, the affected Projects will be available on"," ",n.length.toLocaleString()," current"," ",n.length===1?"device":"devices"," across all recipients."]}),o("ul",{children:n.map(i=>o("li",{className:"recipient-policy-management-name",children:i.displayName},i.deviceId))})]}):o("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Change details"}),o("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?o(Z,{children:[o("p",{className:"small recipient-policy-management-detail-label",children:o("strong",{children:"Unchanged Projects"})}),o("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(i=>o("li",{className:"recipient-policy-management-name",children:i.displayName},i.canonicalProjectIdentity))})]}):null]})]})}function iN({preview:e,result:t}){const n=t.status==="applied"?"Applied":t.status==="not_found"?"Not found":`${t.status.charAt(0).toUpperCase()}${t.status.slice(1)}`;return o("div",{className:"sync-dialog-stack recipient-policy-management-result",children:o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Technical details"}),o("p",{children:["Status: ",n,". Writes: ",t.writeCount.toLocaleString(),"."]}),t.errorCode?o("p",{children:["Error code: ",t.errorCode.replaceAll("_"," "),"."]}):null,t.outcomes.length?o("ul",{children:t.outcomes.map(r=>{const i=e.projects.find(s=>s.canonicalProjectIdentity===r.change.canonicalProjectIdentity)?.displayName??"Selected Project",a=e.selectedRecipients.find(s=>rt(s)===rt(r.change.recipient))?.displayName??(r.change.recipient.recipientKind==="team"?"Team":"Identity");return o("li",{children:[r.change.action==="add"?"Add":"Remove"," ",a," ",r.change.action==="add"?"to":"from"," ",i,":"," ",r.outcome.replaceAll("_"," ")]},`${r.change.canonicalProjectIdentity}:${rt(r.change.recipient)}`)})}):null]})})}function aN({intent:e,options:t,projects:n}){const[r,i]=x(null),[a,s]=x([]),[c,l]=x([]),[d,u]=x(null),[p,m]=x(null),[f,g]=x(null),[h,v]=x(""),[b,_]=x(!1),S=G(!1),C=xe(()=>YT(e,r),[e,r]),N=xe(()=>new Map([...e.teams.map(Y=>[`team:${Y.teamId}`,Y.displayName]),...e.identities.map(Y=>[`identity:${Y.identityId}`,Y.displayName])]),[e]),E=xe(()=>new Set(n.map(Y=>Y.canonicalProjectIdentity)),[n]);if(z(()=>{if(Ui=Y=>{if(S.current)return!1;const fe=XT(Y,e);return i(Y),l(fe),s(Y.mode==="recipient-add"?[]:fe),u(null),m(null),g(null),v(""),_(!1),S.current=!1,!0},Eo){const Y=Eo;Eo=null,Ui(Y)}return()=>{Ui=null}},[e]),z(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const A=eN(r),M=xf(r),U=r.mode==="recipient-manage"?!1:M.some(Y=>!E.has(Y)),k=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!C.some(Y=>Y.key===rt(r.recipient)),F=t.loading||t.loadError||U||k,j=ZT(r,a,c),H=j.length>kf,L=(r.mode==="project-add"||r.mode==="recipient-add")&&a.length===0,R=r.mode!=="project-add"&&r.mode!=="recipient-add"&&j.length===0,P=QT(n,r,c),I=p?.status==="applied",D=p?I?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":A.title,O=p?I?"The reviewed recipient access changes are applied.":"Some reviewed recipient access changes were not applied. Review the technical details.":d?"Confirm the exact Projects, recipients, and resulting access.":A.description,W=()=>{S.current||(i(null),u(null),m(null),g(null),v(""))},ue=Y=>{s(fe=>fe.includes(Y)?fe.filter(ne=>ne!==Y):[...fe,Y]),g(null),v("")},re=async()=>{if(!(F||L||R||H||S.current)){S.current=!0,_(!0),g(null),v("Reviewing exact recipient access changes.");try{u(await CS({version:1,changes:j})),v("Review ready. Confirm the exact changes.")}catch(Y){g(Pf(Y,"Unable to review recipient access changes.")),v("")}finally{S.current=!1,_(!1)}}},ie=async()=>{if(!(!d||S.current)){S.current=!0,_(!0),g(null),v("Saving recipient access changes.");try{const Y=await TS({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(Y),v("");try{await t.onCommitted?.(Y)}catch{g("Recipient access was saved, but this view could not refresh.")}}catch(Y){Y instanceof bc&&(u(null),v("")),g(Pf(Y,"Unable to save recipient access changes."))}finally{S.current=!1,_(!1)}}};let be=null;return t.loading?be="Loading the complete recipient access inventory…":t.loadError?be="The complete recipient access inventory is unavailable. Refresh and try again.":U?be="One selected Project is no longer available. Refresh and try again.":k&&(be="This recipient is no longer available. Refresh and try again."),o(Fr,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:Y=>{Y.preventDefault();const fe=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ne=Gi?.isConnected?Gi:document.getElementById(fe);ne instanceof HTMLElement&&ne.focus(),Gi=null},onOpenAutoFocus:Y=>{const fe=document.getElementById("recipient-policy-management-title");fe&&(Y.preventDefault(),fe.focus())},onOpenChange:Y=>{Y||W()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:o("div",{"aria-busy":b||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:D}),o(Mi,{ariaLabel:`Close ${D}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:W})]}),o("div",{className:"modal-body recipient-policy-management-selection",children:[o("p",{className:"small",id:"recipient-policy-management-description",children:O}),be?o("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:be}):p&&d?o(iN,{preview:d,result:p}):d?o(rN,{preview:d,recipientLabels:N}):r.mode==="recipient-add"||r.mode==="recipient-manage"?o("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[o("legend",{children:A.legend}),P.length?P.map(Y=>o(Af,{checked:a.includes(Y.canonicalProjectIdentity),description:Y.description,disabled:b,label:Y.displayName,onChange:()=>ue(Y.canonicalProjectIdentity)},Y.canonicalProjectIdentity)):o("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):o("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[o("legend",{children:A.legend}),C.length?C.map(Y=>o(Af,{checked:a.includes(Y.key),description:Y.description,disabled:b,label:Y.label,onChange:()=>ue(Y.key)},Y.key)):o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:o("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:h}),f?o("p",{"aria-live":"assertive",role:"alert",children:f}):null,H?o("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",j.length.toLocaleString()," access changes. Review at most ",kf.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),o("div",{className:"modal-footer recipient-policy-management-actions",children:[o("button",{className:"settings-button recipient-policy-management-target",disabled:b,onClick:d&&!p?()=>{u(null),v("")}:W,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!be?o("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(L||R||H),onClick:()=>{d?ie():re()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Df(e,t,n,r={}){Ge(o(aN,{intent:n,options:r,projects:t}),e)}function Po(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function oN(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 Ao(e){const t=new Map;for(const n of e)Po(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 Lf({detailRowCount:e=3,label:t}){return o(Z,{children:[o("span",{className:"sr-only",role:"status",children:t}),o("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>o("div",{"aria-hidden":"true",className:"loading-card",children:[o("div",{className:"loading-card-header",children:[o("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),o("span",{className:"loading-card-badge"})]}),o("div",{className:"loading-card-details",children:Array.from({length:e},(i,a)=>o("div",{className:"loading-card-detail",children:[o("span",{className:"loading-card-line loading-card-label"}),o("span",{className:`loading-card-line ${(r+a)%2?"w-45":"w-60"}`})]},a))})]},r))})]})}function sN(e){return e.state!=="configured"}function $f(e){return e?.items.filter(sN)??[]}function xo(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 cN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,lN=/^(?:actor|device|identity|local):\S+$/iu,dN=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,uN=/^pending[_-]\S+$/iu,pN=/^[a-f0-9]{12,64}$/iu;function Mf(e){return[cN,lN,dN,uN,pN].some(t=>t.test(e))}function Br(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||Mf(t)?"":t}var Ur=null,Gr=null;function Ro(e=[],t=""){if(Gr){const n=Gr(e,t);return n||(Ur=null),n}return Ur={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Of(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function jf(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 mN(e){const t=`share-project-${Dr()}`,n=Of(e.project);return o("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[o("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),o("span",{children:[o("strong",{children:e.project.display_project}),o("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function fN({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?o("p",{className:"small",children:"This invitation will use the existing teammate."}):null,o("ul",{children:e.projects.map(t=>o("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),o("p",{children:o("strong",{children:"No other projects will be shared."})})]})}function hN({projects:e,inventoryError:t}){const[n,r]=x(!1),[i,a]=x(""),[s,c]=x([]),[l,d]=x(null),[u,p]=x(null),[m,f]=x(null),[g,h]=x(!1),[v,b]=x(null),[_,S]=x(!1),C=xe(()=>e.filter(Of),[e]);z(()=>{if(Gr=(k,F="")=>{if(t)return!1;const j=[...new Set(k)],H=j.some(L=>!C.some(R=>R.workspace_identity===L));return a(F.trim()),c(H?[]:j),S(H),d(null),p(null),f(H?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},Ur){const k=Ur;Ur=null,Gr(k.projectIds,k.teammateName)}return()=>{Gr=null}},[C,t]),z(()=>{t&&(Ur=null,r(!1),a(""),c([]),d(null),p(null),f(null),b(null),S(!1))},[t]);const N=()=>{g||r(!1)},E=k=>{c(F=>F.includes(k)?F.filter(j=>j!==k):[...F,k])},A=async()=>{if(f(null),!i.trim()){f("Enter your teammate's name.");return}if(s.length===0){f("Select at least one project.");return}h(!0);try{d(await PS({teammate_name:i.trim(),project_ids:s}))}catch(k){f(jf(k,"Unable to review this invitation."))}finally{h(!1)}},M=async()=>{if(l){f(null),h(!0);try{p(await AS({teammate_name:l.teammate.display_name,project_ids:l.projects.map(k=>k.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(k){k instanceof Error&&k.message==="reviewed_project_set_changed"&&d(null),f(jf(k,"Unable to create this invitation."))}finally{h(!1)}}},U=async()=>{if(u){f(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(k){f(k instanceof Error?k.message:"Unable to copy the invitation.")}}};return o(Z,{children:[o("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||C.length===0,onClick:()=>Gr?.([]),type:"button",children:"Share projects"}),t?o("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?o(Fr,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:k=>{k||N()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"project-share-title",children:"Share projects"}),o("button",{"aria-label":"Close Share projects",disabled:g,onClick:N,type:"button",children:"×"})]}),o("div",{"aria-busy":g,className:"modal-body",children:[o("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?o("div",{children:[o("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),o("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(k=>k.display_name).join(", "),"."]}),o("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),o("button",{className:"settings-button",onClick:()=>{U()},type:"button",children:"Copy invite"}),v?o("p",{role:"status",children:v}):null]}):l?o(fN,{preview:l}):o(Z,{children:[o("label",{className:"field",htmlFor:"project-share-teammate",children:[o("span",{children:"Who are you sharing with?"}),o("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:k=>a(k.currentTarget.value),type:"text",value:i})]}),o("fieldset",{className:"sync-dialog-radio-list",children:[o("legend",{children:"Select exact projects"}),e.map(k=>o(mN,{onToggle:E,project:k,selected:s.includes(k.workspace_identity)},k.workspace_identity))]})]}),m?o("p",{role:"alert",children:m}):null]}),o("div",{className:"modal-footer",children:[o("button",{className:"settings-button",disabled:g,onClick:N,type:"button",children:u?"Done":"Cancel"}),u?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:g||_,onClick:()=>{l?M():A()},type:"button",children:g?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function Ff(e,t,n={}){Ge(o(hN,{inventoryError:n.inventoryError===!0,projects:t}),e)}function il(e){return Br(String(e??"").trim())}function qr(e,t){const n=e.trim();return n?[...n].length>120?`${t} must use 120 characters or fewer.`:[...n].some(r=>/[\p{Cc}\p{Cf}]/u.test(r))?`${t} cannot include control or format characters.`:Mf(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function gN(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 Do(e,t){return e instanceof Error?e.message==="reviewed_onboarding_stale"?"Invitation details changed. Review them again before creating it.":e.message==="recipient_invite_review_unavailable"?"The invitation review is unavailable. Ask the owner to create a new invitation.":e.message==="recipient_invite_intent_mismatch"?"The invitation details do not match the reviewed access. Ask the owner to create a new invitation.":e.message==="invite_identity_conflict"?"This device already belongs to a different Identity. Use a fresh device or ask the owner for the correct invitation.":e.message==="recipient_display_name_invalid"?"Enter a human-readable Identity name instead of an internal identifier.":e.message==="recipient_display_name_required"?"Enter an Identity display name before accepting.":e.message==="recipient_display_name_too_long"?"Use an Identity display name with 120 characters or fewer.":t:t}function Hi(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function vN({preview:e}){return e.projects.length===0?o("p",{className:"small",children:"No Projects are currently shared with this Team."}):o("ul",{children:e.projects.map(t=>o("li",{children:[o("strong",{children:t.displayName})," — ",Hi(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function yN({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),o(vN,{preview:e}),o("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),o("p",{children:o("strong",{children:"No other Projects will be shared through this invitation."})})]})}function bN({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"add-device-direct-projects",children:[o("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?o("ul",{children:t.map(r=>o("li",{children:[r.displayName," — ",Hi(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No Projects are shared directly."})]}),o("section",{"aria-labelledby":"add-device-team-projects",children:[o("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?o("ul",{children:n.map(r=>{const i=r.sources.filter(a=>a.kind==="team").map(a=>a.displayName);return o("li",{children:[r.displayName," — ",Hi(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):o("p",{className:"small",children:"No Projects are inherited through Teams."})]}),o("section",{"aria-labelledby":"add-device-excluded-projects",children:[o("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?o("ul",{children:e.excludedProjects.map(r=>o("li",{children:[r.displayName," — ",Hi(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No other Projects are excluded."}),o("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?o("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function Bf({preview:e}){return e.journey==="team"?o(yN,{preview:e}):o(bN,{preview:e})}function _N({error:e,name:t,onChange:n}){return o("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[o("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),o("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?o("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function wN({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:a,recipientNameError:s}){const c=n.projects??[];return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"project-share-invitation-recipient",children:[o("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),o("p",{children:"Review these display names before importing the invitation."}),o("label",{className:"field",htmlFor:"project-share-recipient-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:a})]}),s?o("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,o("label",{className:"field",htmlFor:"project-share-device-name",children:[o("span",{children:"Device display name"}),o("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?o("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),o("section",{"aria-labelledby":"project-share-invitation-projects",children:[o("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?o("p",{children:["Invitation from ",n.inviter_name,"."]}):null,o("p",{children:["You will receive ",o("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?o("ul",{children:c.map((l,d)=>o("li",{children:[o("strong",{children:l.display_name})," —"," ",Hi(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):o("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),o("p",{children:o("strong",{children:"Accepting this invitation does not join a Team."})}),o("p",{children:o("strong",{children:"No other Projects are included."})})]})}function SN({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return o("div",{className:"sync-dialog-stack",children:[o("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):o("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function CN({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added";return o("section",{"aria-describedby":[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[o("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),o("div",{className:"recipient-policy-invitation-result-copy",children:[o("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?o("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?o("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Uf(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function TN({intent:e}){const t=e.teams.filter(K=>K.status==="active"),n=e.identities.filter(K=>K.status==="active"),[r,i]=x(null),[a,s]=x("team_member"),[c,l]=x(t[0]?.teamId??""),[d,u]=x(""),[p,m]=x(null),[f,g]=x(null),[h,v]=x(null),[b,_]=x(null),[S,C]=x(""),[N,E]=x(""),[A,M]=x(""),[U,k]=x(null),[F,j]=x(!1),[H,L]=x(""),[R,P]=x(""),I=G(null),D=G(0),O=G(""),W=G(!1);z(()=>{if(b){document.getElementById("recipient-invitation-result")?.focus();return}if(h){document.getElementById("project-share-invitation-result")?.focus();return}f?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[f,h,b]);const ue=()=>{D.current+=1,O.current="",W.current=!1,u(""),m(null),g(null),v(null),_(null),C(""),E(""),M(""),k(null),L(""),P("")},re=(K,J)=>{ue(),I.current=J,i(K)},ie=()=>{F||(i(null),ue())},be=K=>{D.current+=1,O.current=K,u(K)},Y=K=>{s(K),l(K==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),ue()},fe=async()=>{if(c){j(!0),P(""),L("Reviewing invitation…");try{m((await NS(Uf(a,c))).preview),L("Review ready. Confirm the invitation details.")}catch(K){P(Do(K,"Unable to review this invitation.")),L("")}finally{j(!1)}}},ne=async()=>{if(p){j(!0),P(""),L("Creating invitation…");try{k(await IS({...Uf(a,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),L("Invitation created.")}catch(K){K instanceof Error&&K.message==="reviewed_onboarding_stale"&&m(null),P(Do(K,"Unable to create this invitation.")),L("")}finally{j(!1)}}},Pe=async()=>{const K=O.current.trim(),J=D.current;if(!K){P("Paste an invitation first.");return}const Oe=()=>D.current===J&&O.current.trim()===K;j(!0),P(""),L("Reviewing invitation…");try{const Ae=await Tp(K);if(!Oe())return;g(Ae),Ae.kind==="team_member"?C(il(Ae.recipient_name)):Ae.kind==="project_share_invite"&&(E(il(Ae.recipient_name)),M(il(Ae.device_name))),L(Ae.kind==="add_device"?(Ae.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.":Ae.kind==="team_member"?"Review ready. Confirm before accepting.":Ae.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced Team administration to continue with this invitation.")}catch(Ae){if(!Oe())return;P(Do(Ae,"Unable to review this invitation.")),L("")}finally{j(!1)}},ge=async()=>{if(!(F||W.current||b)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(qr(N,"Identity display name")||qr(A,"Device display name")))&&!(f.kind==="team_member"&&qr(S,"Identity display name"))){W.current=!0,j(!0),P(""),L("Accepting invitation…");try{const K=f.kind==="project_share_invite"?await vc(d.trim(),{recipient_name:N.trim(),device_name:A.trim()}):await vc(d.trim(),{...f.kind==="team_member"?{recipient_name:S.trim()}:{},device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest});if(f.kind==="project_share_invite")v(gN(K)),L("");else{const J=f.kind;_({kind:J,restartRequired:K.restart_required===!0||K.setup_state==="restart_required",detail:(typeof K.detail=="string"?K.detail.trim():"")||"Restart codemem before continuing.",deliveryPending:J==="add_device"&&(f.onboarding?.projects?.length??0)>0}),L("")}}catch(K){W.current=!1;const J=K instanceof Error?K.message.trim():"";P(Do(K,f.kind==="project_share_invite"&&J?J:"Unable to accept this invitation.")),L("")}finally{j(!1)}}},ae=async()=>{const K=U?.invite.link||U?.invite.encoded||"";if(!K){P("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(K),L("Invitation copied.")}catch{P("Unable to copy the invitation.")}},Ee=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,le=f?.kind==="project_share_invite"?f:null,Te=f?.kind==="team_member"?qr(S,"Identity display name"):"",B=le?qr(N,"Identity display name"):"",oe=le?qr(A,"Device display name"):"";return o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Create an invitation"}),o("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),o("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:K=>{Y("team_member"),re("create",K.currentTarget)},type:"button",children:"Invite Team member"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:K=>{Y("add_device"),re("create",K.currentTarget)},type:"button",children:"Add a device"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>Ro(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Accept an invitation"}),o("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:K=>re("accept",K.currentTarget),type:"button",children:"Review invitation"}),o("p",{className:"small",children:"Legacy invitation import remains under Advanced Team administration."})]}),r?o(Fr,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:K=>{K.preventDefault(),I.current?.focus(),I.current=null},onOpenAutoFocus:K=>{K.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:K=>{K||ie()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:o("div",{"aria-busy":F,className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-invitation-title",tabIndex:-1,children:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),o(Mi,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:F,onClick:ie})]}),o("div",{className:"modal-body",children:[o("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&&!U?o("label",{className:"field",htmlFor:"recipient-invitation-target",children:[o("span",{children:a==="team_member"?"Team":"Identity"}),o("select",{id:"recipient-invitation-target",onChange:K=>l(K.currentTarget.value),value:c,children:(a==="team_member"?t:n).map(K=>o("option",{value:"teamId"in K?K.teamId:K.identityId,children:K.displayName},"teamId"in K?K.teamId:K.identityId))})]}):r==="accept"&&!f&&!b?o("label",{className:"field",htmlFor:"recipient-invitation-value",children:[o("span",{children:"Invitation"}),o("textarea",{id:"recipient-invitation-value",onInput:K=>{be(K.currentTarget.value),g(null),v(null),L(""),P("")},rows:5,value:d})]}):null,p?o(Bf,{preview:p}):null,Ee&&!b?o(Bf,{preview:Ee}):null,f?.kind==="team_member"&&!b?o(_N,{error:Te,name:S,onChange:K=>{C(K),P("")}}):null,le&&!h?o(wN,{deviceName:A,deviceNameError:oe,invite:le,onDeviceNameChange:K=>{M(K),P("")},onRecipientNameChange:K=>{E(K),P("")},recipientName:N,recipientNameError:B}):null,h?o(SN,{result:h}):null,b?o(CN,{result:b}):null,U?o("div",{children:[o("p",{children:"Share the invitation with the recipient."}),o("button",{className:"settings-button",onClick:()=>{ae()},type:"button",children:"Copy invitation"})]}):null,f?.kind==="legacy_team_invite"?o("p",{children:"Use Advanced Team administration to review and import this invitation."}):null,o("p",{"aria-live":"polite",className:"small",role:"status",children:H}),R?o("p",{"aria-live":"assertive",role:"alert",children:R}):null]}),o("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button",disabled:F,onClick:ie,type:"button",children:U||h||b?"Done":"Cancel"}),r==="create"&&!U?o("button",{className:"settings-button sync-dialog-confirm",disabled:F||!c,onClick:()=>{p?ne():fe()},type:"button",children:F?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!f&&!b?o("button",{className:"settings-button sync-dialog-confirm",disabled:F,onClick:()=>{Pe()},type:"button",children:F?"Reviewing…":"Review invitation"}):Ee&&!b||le&&!h?o("button",{className:"settings-button sync-dialog-confirm",disabled:F||!!(f?.kind==="team_member"&&Te)||!!(le&&(!le.projects?.length||B||oe)),onClick:()=>{ge()},type:"button",children:F?"Accepting…":le?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}var Gf={needs_setup:"Needs setup",in_progress:"In progress",stale:"Needs setup",ready:"Ready"},qf={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention",ready:""};function NN(e){return typeof e=="string"&&Object.hasOwn(Gf,e)?Gf[e]:"Needs setup"}function IN(e){return typeof e=="string"&&Object.hasOwn(qf,e)?qf[e]:"needs_attention"}function kN({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=e.filter(r=>r.status!=="ready");return o("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-team-setup-heading",children:n.length>0?`${n.length} ${n.length===1?"Team needs":"Teams need"} setup`:"Team setup"}),n.length>0?o("p",{children:"Tell Codemem who uses each device before using these Teams for sharing."}):null,o("ul",{className:"recipient-policy-sharing-details","aria-label":"Team setup status",children:e.map(r=>o("li",{children:[o("strong",{children:r.displayName})," —"," ",o("span",{className:`project-status-badge ${IN(r.status)}`.trim(),children:NN(r.status)}),r.status!=="ready"&&t?o("button",{"aria-label":`Continue setup for ${r.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t(r.candidateRef),type:"button",children:"Continue setup"}):null]},r.candidateRef))})]})}var Zn=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function er(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function Ki(e,t){return e.length?e.join(", "):t}function Hf(e,t){return[...new Set(e)].flatMap(n=>{const r=t.get(n);return r?[r.displayName]:[]})}function Kf({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{qi({mode:"recipient-manage",recipient:r})},a=()=>{qi({mode:"recipient-add",recipient:r})};return o(Z,{children:[o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[o("button",{"aria-describedby":e,"aria-label":`Add Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick:a,type:"button",children:"Add projects"}),o("button",{"aria-label":`Manage Projects for ${n}`,className:"settings-button recipient-policy-sharing-target recipient-policy-sharing-target-24",disabled:t,onClick:i,type:"button",children:"Manage projects"})]}),o("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function EN({disableMutations:e,intent:t,projects:n}){const r=t.teams.filter(s=>s.status==="active"),i=new Map(t.identities.filter(s=>s.status==="active").map(s=>[s.identityId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=[...new Set(t.teamMemberships.filter(g=>g.status==="active"&&g.teamId===s.teamId&&i.has(g.identityId)).map(g=>g.identityId))],d=l.map(g=>i.get(g)?.displayName??""),u=new Set(t.identityDevices.filter(g=>g.status==="active"&&l.includes(g.identityId)).map(g=>g.deviceId)).size,p=Hf(t.projectRecipients.filter(g=>g.status==="active"&&g.recipientKind==="team"&&g.teamId===s.teamId).map(g=>g.canonicalProjectIdentity),a),m=`recipient-policy-sharing-team-title-${c}`,f=`recipient-policy-sharing-team-add-description-${c}`;return o("article",{"aria-labelledby":m,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:m,children:s.displayName}),o("span",{className:"badge actor-badge",children:"Team"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Current member Identities"}),o("dd",{children:[er(d.length,"active member")," —"," ",Ki(d,"No active members")]})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:er(u,"active registered device")})]}),o("div",{children:[o("dt",{children:"Shared Projects"}),o("dd",{children:[er(p.length,"active shared Project")," —"," ",Ki(p,"No Projects shared")]})]}),o("div",{children:[o("dt",{children:"Future Team members"}),o("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),o(Kf,{descriptionId:f,disabled:e,displayName:s.displayName,recipient:{recipientKind:"team",teamId:s.teamId}})]},s.teamId)})})}function PN({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(f=>f.status==="active"&&f.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(f=>f.status==="active"&&f.identityId===s.identityId&&i.has(f.teamId)).map(f=>f.teamId))].map(f=>i.get(f)?.displayName??""),u=Hf(t.projectRecipients.filter(f=>f.status==="active"&&f.recipientKind==="identity"&&f.identityId===s.identityId).map(f=>f.canonicalProjectIdentity),a),p=`recipient-policy-sharing-identity-title-${c}`,m=`recipient-policy-sharing-identity-add-description-${c}`;return o("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:p,children:s.displayName}),o("span",{className:"badge actor-badge local",children:"Local identity"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Verification"}),o("dd",{children:"Local identity"})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:[er(l.length,"active registered device")," —"," ",Ki(l.map(f=>f.displayName),"No active devices")]})]}),o("div",{children:[o("dt",{children:"Team memberships"}),o("dd",{children:[er(d.length,"active Team membership")," —"," ",Ki(d,"No active Team memberships")]})]}),o("div",{children:[o("dt",{children:"Directly shared Projects"}),o("dd",{children:[er(u.length,"directly shared active Project")," —"," ",Ki(u,"No Projects shared directly")]})]})]}),o("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),o(Kf,{descriptionId:m,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function AN({received:e}){return e.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return o("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:r,children:t.displayName}),o("span",{className:"badge actor-badge",children:"Received"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Memories on this device"}),o("dd",{children:er(t.existingMemoryCount,"memory","memories")})]}),o("div",{children:[o("dt",{children:"Latest activity"}),o("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),o("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function xN({intent:e,options:t,projects:n}){const[r,i]=x(()=>e.teams.some(f=>f.status==="active")?"teams":"identities"),a=G(t.loading===!0||t.loadError===!0),s=G([]),c=$f(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(f=>f.status==="active");z(()=>{if(a.current&&!t.loading&&!t.loadError){a.current=!1,i(u?"teams":"identities");return}u||i(f=>f==="teams"?"identities":f)},[u,t.loadError,t.loading]);const p=f=>{const g=Zn[f];g&&(i(g.id),s.current[f]?.focus())},m=(f,g)=>{let h=null;f.key==="ArrowRight"?h=(g+1)%Zn.length:f.key==="ArrowLeft"?h=(g-1+Zn.length)%Zn.length:f.key==="Home"?h=0:f.key==="End"&&(h=Zn.length-1),h!==null&&(f.preventDefault(),p(h))};return o("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("header",{className:"recipient-policy-sharing-header",children:[o("h2",{children:"Sharing"}),o("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),o(kN,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is being refreshed. The previous Team setup status is being shown.":"Team setup status is loading."}):null,t.teamSetupUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?o("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),o("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),o("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review Devices"}):null]}):null,d>0?o("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),o("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),o("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review Devices"}):null]}):null,t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous Sharing details. Team and Identity Project changes are disabled until a refresh succeeds."}):null,o("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:Zn.map((f,g)=>o("button",{"aria-controls":`recipient-policy-sharing-panel-${f.id}`,"aria-selected":r===f.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===f.id?" active":""}`,id:`recipient-policy-sharing-tab-${f.id}`,onClick:()=>i(f.id),onKeyDown:h=>m(h,g),ref:h=>{s.current[g]=h},role:"tab",tabIndex:r===f.id?0:-1,type:"button",children:f.label},f.id))}),Zn.map(f=>o("div",{"aria-labelledby":`recipient-policy-sharing-tab-${f.id}`,className:"recipient-policy-sharing-panel",hidden:r!==f.id,id:`recipient-policy-sharing-panel-${f.id}`,role:"tabpanel",children:t.loading?r===f.id?o(Lf,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===f.id?o("p",{"aria-live":"assertive",role:"alert",children:"Sharing details are unavailable. Refresh and try again."}):null:f.id==="teams"?o(EN,{disableMutations:t.refreshError===!0,intent:e,projects:n}):f.id==="identities"?o(PN,{disableMutations:t.refreshError===!0,intent:e,projects:n}):f.id==="received"?o(AN,{received:t.received??[]}):o(TN,{intent:e})},f.id))]})}function RN(e,t,n,r={}){Ge(o(xN,{intent:n,options:r,projects:t}),e)}var al={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function DN(){const e=[];let t=0;for(;;){const n=await ro({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:Ao(e),received:oN(e)}}var LN={loadDeviceInventory:wc,loadIntent:_c,loadProjects:DN,loadSyncStatus:eo,loadTeamSetupSummary:Rp,mountManagement:Df,mountSharing:RN};function $N(e={},t={}){const n={...LN,...e};let r=0,i=null,a=0,s,c,l=!1,d=!1,u=!1,p=!1,m=null;const f=(h={})=>{const v=g(++r,h);return i=v,v};async function g(h,v){const b=document.getElementById("recipientPolicySharingMount");if(!b){if(!v.requireTeamSetupSummary)return!0;try{return await n.loadTeamSetupSummary(),!0}catch{return!1}}const _=document.getElementById("recipientPolicyManagementMount");l=!0,d=!1;let S=()=>{const P=m;n.mountSharing(b,P?.inventory.manageable??[],P?.intent??al,P?{coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:P.inventory.received,...u?{refreshError:!0}:{},teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d}:{loading:!0,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};S();const C=Promise.resolve().then(()=>n.loadTeamSetupSummary()).then(P=>(h!==r||(c=P,l=!1,d=!1,S()),!0),()=>(h!==r||(l=!1,d=!0,S()),!1)),[N,E,A,M]=await Promise.allSettled([n.loadProjects(),n.loadIntent(),n.loadDeviceInventory(),n.loadSyncStatus(!1,"",{includeJoinRequests:!1})]);if(h!==r)return v.requireTeamSetupSummary?(await C,!1):i??!1;const U=A.status==="rejected";A.status==="fulfilled"&&(s=A.value),M.status==="fulfilled"&&(a=Up(M.value));let k,F,j;const H=N.status==="fulfilled"&&E.status==="fulfilled";if(u=!H,p=U,H){const P=N.value,I=E.value;m={intent:I,inventory:P},k=P.manageable,F=I,j={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:U,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:P.received},_&&n.mountManagement(_,P.manageable,I,{onCommitted:async()=>{await f()}})}else if(m){const P=m;k=P.inventory.manageable,F=P.intent,j={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:U,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,received:P.inventory.received,refreshError:!0}}else k=[],F=al,j={deviceInventoryUnavailable:U,loadError:!0};const L=()=>{n.mountSharing(b,k,F,{...j,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if(L(),S=L,!H&&_&&n.mountManagement(_,[],al,{loadError:!0}),!v.requireTeamSetupSummary)return H;const R=await C;return h!==r?!1:H&&R}return f}var MN=Symbol.for("preact-signals");function Lo(){if(ln>1)ln--;else{var e,t=!1;for((function(){var i=Mo;for(Mo=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();Vi!==void 0;){var n=Vi;for(Vi=void 0,$o++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&zf(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if($o=0,ln--,t)throw e}}function ON(e){if(ln>0)return e();sl=++jN,ln++;try{return e()}finally{Lo()}}var Fe=void 0;function ol(e){var t=Fe;Fe=void 0;try{return e()}finally{Fe=t}}var Vf,Vi=void 0,ln=0,$o=0,jN=0,sl=0,Mo=void 0,Oo=0;function Wf(e){if(Fe!==void 0){var t=e.n;if(t===void 0||t.t!==Fe)return t={i:0,S:e,p:Fe.s,n:void 0,t:Fe,e:void 0,x:void 0,r:t},Fe.s!==void 0&&(Fe.s.n=t),Fe.s=t,e.n=t,32&Fe.f&&e.S(t),t;if(t.i===-1)return t.i=0,t.n!==void 0&&(t.n.p=t.p,t.p!==void 0&&(t.p.n=t.n),t.p=Fe.s,t.n=void 0,Fe.s.n=t,Fe.s=t),t}}function Ye(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}Ye.prototype.brand=MN,Ye.prototype.h=function(){return!0},Ye.prototype.S=function(e){var t=this,n=this.t;n!==e&&e.e===void 0&&(e.x=n,this.t=e,n!==void 0?n.e=e:ol(function(){var r;(r=t.W)==null||r.call(t)}))},Ye.prototype.U=function(e){var t=this;if(this.t!==void 0){var n=e.e,r=e.x;n!==void 0&&(n.x=r,e.e=void 0),r!==void 0&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,r===void 0&&ol(function(){var i;(i=t.Z)==null||i.call(t)}))}},Ye.prototype.subscribe=function(e){var t=this;return Wi(function(){var n=t.value,r=Fe;Fe=void 0;try{e(n)}finally{Fe=r}},{name:"sub"})},Ye.prototype.valueOf=function(){return this.value},Ye.prototype.toString=function(){return this.value+""},Ye.prototype.toJSON=function(){return this.value},Ye.prototype.peek=function(){var e=this;return ol(function(){return e.value})},Object.defineProperty(Ye.prototype,"value",{get:function(){var e=Wf(this);return e!==void 0&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if($o>100)throw new Error("Cycle detected");(function(n){ln!==0&&$o===0&&n.l!==sl&&(n.l=sl,Mo={S:n,v:n.v,i:n.i,o:Mo})})(this),this.v=e,this.i++,Oo++,ln++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{Lo()}}}});function cl(e,t){return new Ye(e,t)}function zf(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 Jf(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 Yf(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 tr(e,t){Ye.call(this,void 0),this.x=e,this.s=void 0,this.g=Oo-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}tr.prototype=new Ye,tr.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Oo))return!0;if(this.g=Oo,this.f|=1,this.i>0&&!zf(this))return this.f&=-2,!0;var e=Fe;try{Jf(this),Fe=this;var t=this.x();(16&this.f||this.v!==t||this.i===0)&&(this.v=t,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return Fe=e,Yf(this),this.f&=-2,!0},tr.prototype.S=function(e){if(this.t===void 0){this.f|=36;for(var t=this.s;t!==void 0;t=t.n)t.S.S(t)}Ye.prototype.S.call(this,e)},tr.prototype.U=function(e){if(this.t!==void 0&&(Ye.prototype.U.call(this,e),this.t===void 0)){this.f&=-33;for(var t=this.s;t!==void 0;t=t.n)t.S.U(t)}},tr.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(tr.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Wf(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Xf(e,t){return new tr(e,t)}function Qf(e){var t=e.m;if(e.m=void 0,typeof t=="function"){ln++;var n=Fe;Fe=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,ll(e),r}finally{Fe=n,Lo()}}}function ll(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,Qf(e)}function FN(e){if(Fe!==this)throw new Error("Out-of-order effect");Yf(this),Fe=e,this.f&=-2,8&this.f&&ll(this),Lo()}function Hr(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,Vf&&Vf.push(this)}Hr.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()}},Hr.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Qf(this),Jf(this),ln++;var e=Fe;return Fe=this,FN.bind(this,e)},Hr.prototype.N=function(){2&this.f||(this.f|=2,this.u=Vi,Vi=this)},Hr.prototype.d=function(){this.f|=8,1&this.f||ll(this)},Hr.prototype.dispose=function(){this.d()};function Wi(e,t){var n=new Hr(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var Zf,dl,jo,BN=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,K1=[],eh=[];Wi(function(){Zf=this.N})();function Kr(e,t){he[e]=t.bind(null,he[e]||function(){})}function Fo(e){if(jo){var t=jo;jo=void 0,t()}jo=e&&e.S()}function th(e){var t=this,n=e.data,r=GN(n);r.value=n;var i=xe(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Xf(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=Xf(function(){return!Array.isArray(d.value)&&!qp(d.value)}),p=Wi(function(){if(this.N=nh,u.value){var f=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=f)}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[u,d]},[]),a=i[0],s=i[1];return a.value?s.peek():s.value}th.displayName="ReactiveTextNode",Object.defineProperties(Ye.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:th},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),Kr("__b",function(e,t){if(typeof t.type=="string"){var n,r=t.props;for(var i in r)if(i!=="children"){var a=r[i];a instanceof Ye&&(n||(t.__np=n={}),n[i]=a,r[i]=a.peek())}}e(t)}),Kr("__r",function(e,t){if(e(t),t.type!==Z){Fo();var n,r=t.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,a){var s;return Wi(function(){s=this},{name:a}),s.c=i,s})(function(){var i;BN&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),dl=r,Fo(n)}}),Kr("__e",function(e,t,n,r){Fo(),dl=void 0,e(t,n,r)}),Kr("diffed",function(e,t){Fo(),dl=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props;if(r){var a=n.U;if(a)for(var s in a){var c=a[s];c!==void 0&&!(s in r)&&(c.d(),a[s]=void 0)}else a={},n.U=a;for(var l in r){var d=a[l],u=r[l];d===void 0?(d=UN(n,l,u),a[l]=d):d.o(u,i)}}}e(t)});function UN(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,a=cl(n),s=n.peek();return{o:function(c,l){a.value=c,s=c.peek()},d:Wi(function(){this.N=nh;var c=a.value.value;s!==c?(s=void 0,i?e[t]=c:c!=null&&(c!==!1||t[4]==="-")?e.setAttribute(t,c):e.removeAttribute(t)):s=void 0})}}Kr("unmount",function(e,t){if(typeof t.type=="string"){var n=t.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var a=r[i];a&&a.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),Kr("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)}),Ct.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(r||a||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function GN(e,t){return xe(function(){return cl(e,t)},[])}var V1=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},qN=function(e){queueMicrotask(function(){queueMicrotask(e)})};function HN(){ON(function(){for(var e;e=eh.shift();)Zf.call(e)})}function nh(){eh.push(this)===1&&(he.requestAnimationFrame||qN)(HN)}function Bo(e){const t=e+"CollectionProvider",[n,r]=st(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=h=>{const{scope:v,children:b}=h,_=cn.useRef(null),S=cn.useRef(new Map).current;return o(i,{scope:v,itemMap:S,collectionRef:_,children:b})};s.displayName=t;const c=e+"CollectionSlot",l=Jn(c),d=cn.forwardRef((h,v)=>{const{scope:b,children:_}=h;return o(l,{ref:we(v,a(c,b).collectionRef),children:_})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=Jn(u),f=cn.forwardRef((h,v)=>{const{scope:b,children:_,...S}=h,C=cn.useRef(null),N=we(v,C),E=a(u,b);return cn.useEffect(()=>(E.itemMap.set(C,{ref:C,...S}),()=>{E.itemMap.delete(C)})),o(m,{[p]:"",ref:N,children:_})});f.displayName=u;function g(h){const v=a(e+"CollectionConsumer",h);return cn.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const _=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(v.itemMap.values()).sort((S,C)=>_.indexOf(S.ref.current)-_.indexOf(C.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},g,r]}var rh=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"}),KN="VisuallyHidden",Uo=V((e,t)=>o(pe.span,{...e,ref:t,style:{...rh,...e.style}}));Uo.displayName=KN;var VN=Uo,ul="ToastProvider",[pl,WN,zN]=Bo("Toast"),[ih,W1]=st("Toast",[zN]),[JN,Go]=ih(ul),ah=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:a=50,children:s}=e,[c,l]=x(null),[d,u]=x(0),p=G(!1),m=G(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${ul}\`. Expected non-empty \`string\`.`),o(pl.Provider,{scope:t,children:o(JN,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:d,viewport:c,onViewportChange:l,onToastAdd:ce(()=>u(f=>f+1),[]),onToastRemove:ce(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:m,children:s})})};ah.displayName=ul;var oh="ToastViewport",YN=["F8"],ml="toast.viewportPause",fl="toast.viewportResume",sh=V((e,t)=>{const{__scopeToast:n,hotkey:r=YN,label:i="Notifications ({hotkey})",...a}=e,s=Go(oh,n),c=WN(n),l=G(null),d=G(null),u=G(null),p=G(null),m=we(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=s.toastCount>0;z(()=>{const v=b=>{r.length!==0&&r.every(_=>b[_]||b.code===_)&&p.current?.focus()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),z(()=>{const v=l.current,b=p.current;if(g&&v&&b){const _=()=>{if(!s.isClosePausedRef.current){const E=new CustomEvent(ml);b.dispatchEvent(E),s.isClosePausedRef.current=!0}},S=()=>{if(s.isClosePausedRef.current){const E=new CustomEvent(fl);b.dispatchEvent(E),s.isClosePausedRef.current=!1}},C=E=>{v.contains(E.relatedTarget)||S()},N=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",_),v.addEventListener("focusout",C),v.addEventListener("pointermove",_),v.addEventListener("pointerleave",N),window.addEventListener("blur",_),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",_),v.removeEventListener("focusout",C),v.removeEventListener("pointermove",_),v.removeEventListener("pointerleave",N),window.removeEventListener("blur",_),window.removeEventListener("focus",S)}}},[g,s.isClosePausedRef]);const h=ce(({tabbingDirection:v})=>{const b=c().map(_=>{const S=_.ref.current,C=[S,...uI(S)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?b.reverse():b).flat()},[c]);return z(()=>{const v=p.current;if(v){const b=_=>{const S=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!S){const C=document.activeElement,N=_.shiftKey;if(_.target===v&&N){d.current?.focus();return}const E=h({tabbingDirection:N?"backwards":"forwards"}),A=E.findIndex(M=>M===C);vl(E.slice(A+1))?_.preventDefault():N?d.current?.focus():u.current?.focus()}};return v.addEventListener("keydown",b),()=>v.removeEventListener("keydown",b)}},[c,h]),o($C,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&o(hl,{ref:d,onFocusFromOutsideViewport:()=>{vl(h({tabbingDirection:"forwards"}))}}),o(pl.Slot,{scope:n,children:o(pe.ol,{tabIndex:-1,...a,ref:m})}),g&&o(hl,{ref:u,onFocusFromOutsideViewport:()=>{vl(h({tabbingDirection:"backwards"}))}})]})});sh.displayName=oh;var ch="ToastFocusProxy",hl=V((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,a=Go(ch,n);return o(Uo,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;a.viewport?.contains(c)||r()}})});hl.displayName=ch;var zi="Toast",XN="toast.swipeStart",QN="toast.swipeMove",ZN="toast.swipeCancel",eI="toast.swipeEnd",lh=V((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:a,...s}=e,[c,l]=Tt({prop:r,defaultProp:i??!0,onChange:a,caller:zi});return o(nt,{present:n||c,children:o(rI,{open:c,...s,ref:t,onClose:()=>l(!1),onPause:lt(e.onPause),onResume:lt(e.onResume),onSwipeStart:Q(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Q(e.onSwipeMove,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:Q(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Q(e.onSwipeEnd,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});lh.displayName=zi;var[tI,nI]=ih(zi,{onClose(){}}),rI=V((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:a,onClose:s,onEscapeKeyDown:c,onPause:l,onResume:d,onSwipeStart:u,onSwipeMove:p,onSwipeCancel:m,onSwipeEnd:f,...g}=e,h=Go(zi,n),[v,b]=x(null),_=we(t,L=>b(L)),S=G(null),C=G(null),N=i||h.duration,E=G(0),A=G(N),M=G(0),{onToastAdd:U,onToastRemove:k}=h,F=lt(()=>{v?.contains(document.activeElement)&&h.viewport?.focus(),s()}),j=ce(L=>{!L||L===1/0||(window.clearTimeout(M.current),E.current=new Date().getTime(),M.current=window.setTimeout(F,L))},[F]);z(()=>{const L=h.viewport;if(L){const R=()=>{j(A.current),d?.()},P=()=>{const I=new Date().getTime()-E.current;A.current=A.current-I,window.clearTimeout(M.current),l?.()};return L.addEventListener(ml,P),L.addEventListener(fl,R),()=>{L.removeEventListener(ml,P),L.removeEventListener(fl,R)}}},[h.viewport,N,l,d,j]),z(()=>{a&&!h.isClosePausedRef.current&&j(N)},[a,N,h.isClosePausedRef,j]),z(()=>(U(),()=>k()),[U,k]);const H=xe(()=>v?fh(v):null,[v]);return h.viewport?o(Z,{children:[H&&o(iI,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:H}),o(tI,{scope:n,onClose:F,children:on(o(pl.ItemSlot,{scope:n,children:o(LC,{asChild:!0,onEscapeKeyDown:Q(c,()=>{h.isFocusedToastEscapeKeyDownRef.current||F(),h.isFocusedToastEscapeKeyDownRef.current=!1}),children:o(pe.li,{tabIndex:0,"data-state":a?"open":"closed","data-swipe-direction":h.swipeDirection,...g,ref:_,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:Q(e.onKeyDown,L=>{L.key==="Escape"&&(c?.(L.nativeEvent),L.nativeEvent.defaultPrevented||(h.isFocusedToastEscapeKeyDownRef.current=!0,F()))}),onPointerDown:Q(e.onPointerDown,L=>{L.button===0&&(S.current={x:L.clientX,y:L.clientY})}),onPointerMove:Q(e.onPointerMove,L=>{if(!S.current)return;const R=L.clientX-S.current.x,P=L.clientY-S.current.y,I=!!C.current,D=["left","right"].includes(h.swipeDirection),O=["left","up"].includes(h.swipeDirection)?Math.min:Math.max,W=D?O(0,R):0,ue=D?0:O(0,P),re=L.pointerType==="touch"?10:2,ie={x:W,y:ue},be={originalEvent:L,delta:ie};I?(C.current=ie,qo(QN,p,be,{discrete:!1})):hh(ie,h.swipeDirection,re)?(C.current=ie,qo(XN,u,be,{discrete:!1}),L.target.setPointerCapture(L.pointerId)):(Math.abs(R)>re||Math.abs(P)>re)&&(S.current=null)}),onPointerUp:Q(e.onPointerUp,L=>{const R=C.current,P=L.target;if(P.hasPointerCapture(L.pointerId)&&P.releasePointerCapture(L.pointerId),C.current=null,S.current=null,R){const I=L.currentTarget,D={originalEvent:L,delta:R};hh(R,h.swipeDirection,h.swipeThreshold)?qo(eI,f,D,{discrete:!0}):qo(ZN,m,D,{discrete:!0}),I.addEventListener("click",O=>O.preventDefault(),{once:!0})}})})})}),h.viewport)})]}):null}),iI=e=>{const{__scopeToast:t,children:n,...r}=e,i=Go(zi,t),[a,s]=x(!1),[c,l]=x(!1);return lI(()=>s(!0)),z(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:o(Xn,{asChild:!0,children:o(Uo,{...r,children:a&&o(Z,{children:[i.label," ",n]})})})},aI="ToastTitle",oI=V((e,t)=>{const{__scopeToast:n,...r}=e;return o(pe.div,{...r,ref:t})});oI.displayName=aI;var sI="ToastDescription",dh=V((e,t)=>{const{__scopeToast:n,...r}=e;return o(pe.div,{...r,ref:t})});dh.displayName=sI;var uh="ToastAction",cI=V((e,t)=>{const{altText:n,...r}=e;return n.trim()?o(mh,{altText:n,asChild:!0,children:o(gl,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${uh}\`. Expected non-empty \`string\`.`),null)});cI.displayName=uh;var ph="ToastClose",gl=V((e,t)=>{const{__scopeToast:n,...r}=e,i=nI(ph,n);return o(mh,{asChild:!0,children:o(pe.button,{type:"button",...r,ref:t,onClick:Q(e.onClick,i.onClose)})})});gl.displayName=ph;var mh=V((e,t)=>{const{__scopeToast:n,altText:r,...i}=e;return o(pe.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:t})});function fh(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),dI(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const a=n.dataset.radixToastAnnounceAlt;a&&t.push(a)}else t.push(...fh(n))}}),t}function qo(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?Hc(i,a):i.dispatchEvent(a)}var hh=(e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t==="left"||t==="right"?a&&r>n:!a&&i>n};function lI(e=()=>{}){const t=lt(e);We(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function dI(e){return e.nodeType===e.ELEMENT_NODE}function uI(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function vl(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var pI=ah,mI=sh,fI=lh,hI=dh,gI=gl,Ji=cl([]),vI=1;function yI(e,t="success",n=8e3){if(!e)return;const r=vI++;Ji.value=[...Ji.value,{id:r,message:e,variant:t,durationMs:n}]}function bI(e){Ji.value=Ji.value.filter(t=>t.id!==e)}function _I(){const e=Ji.value;return o(pI,{duration:8e3,swipeDirection:"right",children:[e.map(t=>o(fI,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||bI(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[o(hI,{className:"toast-message",children:t.message}),o(gI,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),o(mI,{className:"toast-viewport"})]})}function wI(e){Ge(o(_I,{}),e)}function Ho(e,t,n){const r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=String(n)),r}function Me(e){return document.getElementById(e)}function yl(e){return document.getElementById(e)}function bl(e){return document.getElementById(e)}function gh(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function SI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function CI(e,t){const n=t.trim();if(!n)return gh(e);const r=gh(e);try{const i=new RegExp(`(${SI(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function Yi(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 TI=new Set(["BUTTON","A","SELECT"]),NI=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function II(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function kI(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function EI(e){return e?TI.has(e.tagName)?!0:e instanceof HTMLInputElement&&NI.has(e.type):!1}function PI(e){return e.metaKey||e.ctrlKey}function Vr(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(!II(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}EI(n)||kI(n)&&!PI(e)||(e.preventDefault(),t.onSubmit())}}var nr=["feed","projects","sharing","devices","health","advanced"],vh=["sync","coordinator-admin"],_l="codemem-tab",yh="codemem-advanced-section",bh="codemem-feed-filter",_h="codemem-feed-scope",AI="codemem-sync-diagnostics",wh="codemem-sync-pairing",Sh="codemem-sync-redact",Ch=["all","observations","summaries"],Th=["all","mine","theirs"],w={activeTab:"feed",advancedSection:"sync",currentProject:"",refreshState:"idle",refreshInFlight:!1,refreshQueued:!1,refreshTimer:null,feedTypeFilter:"all",feedScopeFilter:"all",feedQuery:"",lastFeedItems:[],lastFeedFilteredCount:0,lastFeedSignature:"",pendingFeedItems:null,itemViewState:new Map,itemExpandState:new Map,newItemKeys:new Set,lastStatsPayload:null,lastUsagePayload:null,lastRawEventsPayload:null,lastUpdateStatus:null,lastSyncStatus:null,lastDeviceIdentityInventory:null,deviceIdentityInventoryLoadError:!1,pendingDeviceIdentityFocus:void 0,lastSyncActors:[],lastSyncPeers:[],lastShareOperations:[],shareOperationsLoadError:!1,pendingAcceptedSyncPeers:[],lastSyncSharingReview:[],lastSyncLegacySharedReview:null,lastSyncCoordinator:null,lastCoordinatorAdminStatus:null,coordinatorAdminTargetGroup:"",knownProjects:[],lastCoordinatorAdminGroups:[],lastCoordinatorAdminJoinRequests:[],lastCoordinatorAdminDevices:[],lastSyncJoinRequests:[],lastTeamInvite:null,lastTeamJoin:null,syncJoinFlowFeedback:null,syncPeerFeedbackById:new Map,syncPeersSectionFeedback:null,syncJoinRequestsFeedback:null,syncDiscoveredFeedback:null,pendingCoordinatorApprovalsByDeviceId:new Map,lastSyncAttempts:[],lastSyncLegacyDevices:[],lastSyncViewModel:null,lastSyncDuplicatePersonDecisions:{},pairingPayloadRaw:null,pairingCommandRaw:"",configDefaults:{},configPath:"",settingsDirty:!1,syncDiagnosticsOpen:!1,syncPairingOpen:!1};function xI(e){return[...nr]}function Xi(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":nr.includes(e)?e:"feed"}function wl(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return vh.includes(t)?"advanced":nr.includes(t)?t:null}function Sl(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 RI(){const e=wl();if(e)return Xi(e,w.lastCoordinatorAdminStatus);const t=localStorage.getItem(_l);return t&&(nr.includes(t)||vh.includes(t))?Xi(t,w.lastCoordinatorAdminStatus):"feed"}function DI(){const e=Sl();if(e)return e;const t=localStorage.getItem(_l);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(yh)==="teams"?"teams":"sync"}function Cl(e,t=!1){w.advancedSection=e,localStorage.setItem(yh,e),t&&(window.location.hash=`advanced/${e}`)}function Nh(e,t={}){const n=Xi(e,w.lastCoordinatorAdminStatus);w.activeTab=n,localStorage.setItem(_l,n);const r=wl();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${w.advancedSection}`:n)}function LI(){const e=localStorage.getItem(bh)||"all";return Ch.includes(e)?e:"all"}function $I(){const e=localStorage.getItem(_h)||"all";return Th.includes(e)?e:"all"}function MI(e){w.feedTypeFilter=Ch.includes(e)?e:"all",localStorage.setItem(bh,w.feedTypeFilter)}function Ih(e){w.feedScopeFilter=Th.includes(e)?e:"all",localStorage.setItem(_h,w.feedScopeFilter)}function OI(){return localStorage.getItem(AI)==="1"}function jI(e){w.syncPairingOpen=e;try{localStorage.setItem(wh,e?"1":"0")}catch{}}function Qi(){return localStorage.getItem(Sh)!=="0"}function FI(e){localStorage.setItem(Sh,e?"1":"0")}function BI(){w.activeTab=RI(),w.advancedSection=DI(),w.feedTypeFilter=LI(),w.feedScopeFilter=$I(),w.syncDiagnosticsOpen=OI();try{w.syncPairingOpen=localStorage.getItem(wh)==="1"}catch{w.syncPairingOpen=!1}}var Tl=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],kh="codemem-theme";function Eh(e){const t=Tl.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return Tl.find(r=>r.id===n)||Tl[0]}function Nl(){const e=localStorage.getItem(kh);return e?Eh(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Ph(e){const t=Eh(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(kh,t.id)}function UI(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const a=document.createElement("i");a.setAttribute("data-lucide",r),a.setAttribute("aria-hidden","true"),e.appendChild(a),globalThis.lucide?.createIcons?.()};t(Nl()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=Nl()==="dark"?"light":"dark";Ph(n),t(n)})}var GI=Wn(void 0);function Zi(e){const t=Cn(GI);return e||t||"ltr"}var Il="rovingFocusGroup.onEntryFocus",qI={bubbles:!1,cancelable:!0},ea="RovingFocusGroup",[kl,Ah,HI]=Bo(ea),[KI,Wr]=st(ea,[HI]),[VI,WI]=KI(ea),xh=V((e,t)=>o(kl.Provider,{scope:e.__scopeRovingFocusGroup,children:o(kl.Slot,{scope:e.__scopeRovingFocusGroup,children:o(zI,{...e,ref:t})})}));xh.displayName=ea;var zI=V((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...p}=e,m=G(null),f=we(t,m),g=Zi(a),[h,v]=Tt({prop:s,defaultProp:c??null,onChange:l,caller:ea}),[b,_]=x(!1),S=lt(d),C=Ah(n),N=G(!1),[E,A]=x(0);return z(()=>{const M=m.current;if(M)return M.addEventListener(Il,S),()=>M.removeEventListener(Il,S)},[S]),o(VI,{scope:n,orientation:r,dir:g,loop:i,currentTabStopId:h,onItemFocus:ce(M=>v(M),[v]),onItemShiftTab:ce(()=>_(!0),[]),onFocusableItemAdd:ce(()=>A(M=>M+1),[]),onFocusableItemRemove:ce(()=>A(M=>M-1),[]),children:o(pe.div,{tabIndex:b||E===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:Q(e.onMouseDown,()=>{N.current=!0}),onFocus:Q(e.onFocus,M=>{const U=!N.current;if(M.target===M.currentTarget&&U&&!b){const k=new CustomEvent(Il,qI);if(M.currentTarget.dispatchEvent(k),!k.defaultPrevented){const F=C().filter(j=>j.focusable);Lh([F.find(j=>j.active),F.find(j=>j.id===h),...F].filter(Boolean).map(j=>j.ref.current),u)}}N.current=!1}),onBlur:Q(e.onBlur,()=>_(!1))})})}),Rh="RovingFocusGroupItem",Dh=V((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:s,...c}=e,l=ct(),d=a||l,u=WI(Rh,n),p=u.currentTabStopId===d,m=Ah(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:h}=u;return z(()=>{if(r)return f(),()=>g()},[r,f,g]),o(kl.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:o(pe.span,{tabIndex:p?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:Q(e.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:Q(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:Q(e.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const b=XI(v,u.orientation,u.dir);if(b!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let _=m().filter(S=>S.focusable).map(S=>S.ref.current);if(b==="last")_.reverse();else if(b==="prev"||b==="next"){b==="prev"&&_.reverse();const S=_.indexOf(v.currentTarget);_=u.loop?QI(_,S+1):_.slice(S+1)}setTimeout(()=>Lh(_))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:h!=null}):s})})});Dh.displayName=Rh;var JI={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function YI(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function XI(e,t,n){const r=YI(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return JI[r]}function Lh(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function QI(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var El=xh,Pl=Dh,Ko="Tabs",[ZI,z1]=st(Ko,[Wr]),$h=Wr(),[ek,Al]=ZI(Ko),Mh=V((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:a,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=Zi(c),[p,m]=Tt({prop:r,onChange:i,defaultProp:a??"",caller:Ko});return o(ek,{scope:n,baseId:ct(),value:p,onValueChange:m,orientation:s,dir:u,activationMode:l,children:o(pe.div,{dir:u,"data-orientation":s,...d,ref:t})})});Mh.displayName=Ko;var Oh="TabsList",jh=V((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,a=Al(Oh,n),s=$h(n);return o(El,{asChild:!0,...s,orientation:a.orientation,dir:a.dir,loop:r,children:o(pe.div,{role:"tablist","aria-orientation":a.orientation,...i,ref:t})})});jh.displayName=Oh;var Fh="TabsTrigger",Bh=V((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...a}=e,s=Al(Fh,n),c=$h(n),l=qh(s.baseId,r),d=Hh(s.baseId,r),u=r===s.value;return o(Pl,{asChild:!0,...c,focusable:!i,active:u,children:o(pe.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...a,ref:t,onMouseDown:Q(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:Q(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:Q(e.onFocus,()=>{const p=s.activationMode!=="manual";!u&&!i&&p&&s.onValueChange(r)})})})});Bh.displayName=Fh;var Uh="TabsContent",Gh=V((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:a,...s}=e,c=Al(Uh,n),l=qh(c.baseId,r),d=Hh(c.baseId,r),u=r===c.value,p=G(u);return z(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),o(nt,{present:i||u,children:({present:m})=>o(pe.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:d,tabIndex:0,...s,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&a})})});Gh.displayName=Uh;function qh(e,t){return`${e}-trigger-${t}`}function Hh(e,t){return`${e}-content-${t}`}var tk=Mh,nk=jh,rk=Bh,ik=Gh;function Kh({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:a,value:s}){return o(tk,{onValueChange:r,value:s,children:[o(nk,{"aria-label":e,className:n,children:i.map(c=>o(rk,{className:a,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function rr({children:e,className:t,forceMount:n=!1,value:r}){return o(ik,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function Se(e){return o("input",{...e})}function ak(e,t){const n=String(e.device_id||"").trim(),r=String(e.group_id||t||"").trim(),i=String(e.display_name||n||"Unnamed device"),a=e.enabled!==!1&&e.enabled!==0,s=[`Device ID ${n||"unknown"}`];return r&&s.push(`Team ID ${r}`),{advancedDetail:`Advanced: ${s.join(" · ")}`,deviceId:n,displayName:i,statusLabel:a?"Enabled in this Team":"Disabled in this Team",teamId:r}}var ok="codemem-coordinator-admin-target-group",q={activeSection:"groups",inviteGroup:"",inviteTtlHours:"24",invitePolicy:"auto_admit",invitePending:!1,showArchivedGroups:!1,createGroupId:"",createGroupDisplayName:"",groupActionPendingId:"",groupActionPendingKind:"",joinReviewPendingId:"",joinReviewPendingAction:"",deviceActionPendingId:"",deviceActionPendingKind:"",groupRenameDrafts:new Map,deviceRenameDrafts:new Map,deviceRenameServerNames:new Map,groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function sk(e){const{summary:t,runDevice:n}=e,r=Array.isArray(w.lastCoordinatorAdminDevices)?w.lastCoordinatorAdminDevices:[];return y(rr,{className:"coordinator-admin-panel",value:"devices"},y("h3",null,"Enrolled devices"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Rename, disable, re-enable, or remove Team devices here. Space access is granted from Spaces below; Team membership alone does not share memories.":"Finish setup first. Device administration stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const a=ak(i,String(w.lastCoordinatorAdminStatus?.active_group||"")),{deviceId:s,displayName:c,teamId:l}=a,d=q.deviceActionPendingId===s,u=q.deviceRenameDrafts.get(s)??String(i.display_name||""),p=i.enabled!==!1&&i.enabled!==0,m=!s||d||t.readiness!=="ready";return y("div",{class:"peer-card peer-card--padded",key:s||String(i.fingerprint||"unknown")},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-submeta"},a.statusLabel),y("div",{class:"peer-meta"},a.advancedDetail),y("form",{class:"coordinator-admin-form",onSubmit:f=>{f.preventDefault(),!m&&n(s,l,c,"rename")}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready"||d,onInput:f=>{q.deviceRenameDrafts.set(s,String(f.currentTarget.value||""))},type:"text",value:u}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:m,type:"submit"},d&&q.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),p?y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"disable"),type:"button"},d&&q.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):y("button",{class:"settings-button",disabled:m,onClick:()=>n(s,l,c,"enable"),type:"button"},d&&q.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),y("button",{class:"settings-button danger",disabled:m,onClick:()=>n(s,l,c,"remove"),type:"button"},d&&q.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No enrolled devices found for the active coordinator group.":"Device administration will appear here once setup is complete."))}var Vo="Collapsible",[ck,J1]=st(Vo),[lk,xl]=ck(Vo),Vh=V((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:a,onOpenChange:s,...c}=e,[l,d]=Tt({prop:r,defaultProp:i??!1,onChange:s,caller:Vo});return o(lk,{scope:n,disabled:a,contentId:ct(),open:l,onOpenToggle:ce(()=>d(u=>!u),[d]),children:o(pe.div,{"data-state":Dl(l),"data-disabled":a?"":void 0,...c,ref:t})})});Vh.displayName=Vo;var Wh="CollapsibleTrigger",zh=V((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=xl(Wh,n);return o(pe.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":Dl(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:Q(e.onClick,i.onOpenToggle)})});zh.displayName=Wh;var Rl="CollapsibleContent",Jh=V((e,t)=>{const{forceMount:n,...r}=e,i=xl(Rl,e.__scopeCollapsible);return o(nt,{present:n||i.open,children:({present:a})=>o(dk,{...r,ref:t,present:a})})});Jh.displayName=Rl;var dk=V((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...a}=e,s=xl(Rl,n),[c,l]=x(r),d=G(null),u=we(t,d),p=G(0),m=p.current,f=G(0),g=f.current,h=s.open||c,v=G(h),b=G(void 0);return z(()=>{const _=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(_)},[]),We(()=>{const _=d.current;if(_){b.current=b.current||{transitionDuration:_.style.transitionDuration,animationName:_.style.animationName},_.style.transitionDuration="0s",_.style.animationName="none";const S=_.getBoundingClientRect();p.current=S.height,f.current=S.width,v.current||(_.style.transitionDuration=b.current.transitionDuration,_.style.animationName=b.current.animationName),l(r)}},[s.open,r]),o(pe.div,{"data-state":Dl(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...a,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":g?`${g}px`:void 0,...e.style},children:h&&i})});function Dl(e){return e?"open":"closed"}var Wo=Vh,Yh=zh,zo=Jh,uk=["top","right","bottom","left"],Nn=Math.min,bt=Math.max,Jo=Math.round,Yo=Math.floor,Ht=e=>({x:e,y:e}),pk={left:"right",right:"left",bottom:"top",top:"bottom"};function Ll(e,t,n){return bt(e,Nn(t,n))}function dn(e,t){return typeof e=="function"?e(t):e}function un(e){return e.split("-")[0]}function zr(e){return e.split("-")[1]}function $l(e){return e==="x"?"y":"x"}function Ml(e){return e==="y"?"height":"width"}function Kt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Ol(e){return $l(Kt(e))}function mk(e,t,n){n===void 0&&(n=!1);const r=zr(e),i=Ol(e),a=Ml(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=Xo(s)),[s,Xo(s)]}function fk(e){const t=Xo(e);return[jl(e),t,jl(t)]}function jl(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Xh=["left","right"],Qh=["right","left"],hk=["top","bottom"],gk=["bottom","top"];function vk(e,t,n){switch(e){case"top":case"bottom":return n?t?Qh:Xh:t?Xh:Qh;case"left":case"right":return t?hk:gk;default:return[]}}function yk(e,t,n,r){const i=zr(e);let a=vk(un(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(jl)))),a}function Xo(e){const t=un(e);return pk[t]+e.slice(t.length)}function bk(e){return{top:0,right:0,bottom:0,left:0,...e}}function Zh(e){return typeof e!="number"?bk(e):{top:e,right:e,bottom:e,left:e}}function Qo(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 eg(e,t,n){let{reference:r,floating:i}=e;const a=Kt(t),s=Ol(t),c=Ml(s),l=un(t),d=a==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,m=r[c]/2-i[c]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:p};break;case"left":f={x:r.x-i.width,y:p};break;default:f={x:r.x,y:r.y}}switch(zr(t)){case"start":f[s]-=m*(n&&d?-1:1);break;case"end":f[s]+=m*(n&&d?-1:1);break}return f}async function _k(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:m=!1,padding:f=0}=dn(t,e),g=Zh(f),h=c[m?p==="floating"?"reference":"floating":p],v=Qo(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(h)))==null||n?h:h.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(c.floating)),boundary:d,rootBoundary:u,strategy:l})),b=p==="floating"?{x:r,y:i,width:s.floating.width,height:s.floating.height}:s.reference,_=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),S=await(a.isElement==null?void 0:a.isElement(_))?await(a.getScale==null?void 0:a.getScale(_))||{x:1,y:1}:{x:1,y:1},C=Qo(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:_,strategy:l}):b);return{top:(v.top-C.top+g.top)/S.y,bottom:(C.bottom-v.bottom+g.bottom)/S.y,left:(v.left-C.left+g.left)/S.x,right:(C.right-v.right+g.right)/S.x}}var wk=50,Sk=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:_k},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}=eg(d,r,l),m=r,f=0;const g={};for(let h=0;h<a.length;h++){const v=a[h];if(!v)continue;const{name:b,fn:_}=v,{x:S,y:C,data:N,reset:E}=await _({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:g,rects:d,platform:c,elements:{reference:e,floating:t}});u=S??u,p=C??p,g[b]={...g[b],...N},E&&f<wk&&(f++,typeof E=="object"&&(E.placement&&(m=E.placement),E.rects&&(d=E.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):E.rects),{x:u,y:p}=eg(d,m,l)),h=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:g}},Ck=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=dn(e,t)||{};if(d==null)return{};const p=Zh(u),m={x:n,y:r},f=Ol(i),g=Ml(f),h=await s.getDimensions(d),v=f==="y",b=v?"top":"left",_=v?"bottom":"right",S=v?"clientHeight":"clientWidth",C=a.reference[g]+a.reference[f]-m[f]-a.floating[g],N=m[f]-a.reference[f],E=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=E?E[S]:0;(!A||!await(s.isElement==null?void 0:s.isElement(E)))&&(A=c.floating[S]||a.floating[g]);const M=C/2-N/2,U=A/2-h[g]/2-1,k=Nn(p[b],U),F=Nn(p[_],U),j=k,H=A-h[g]-F,L=A/2-h[g]/2+M,R=Ll(j,L,H),P=!l.arrow&&zr(i)!=null&&L!==R&&a.reference[g]/2-(L<j?k:F)-h[g]/2<0,I=P?L<j?L-j:L-H:0;return{[f]:m[f]+I,data:{[f]:R,centerOffset:L-R-I,...P&&{alignmentOffset:I}},reset:P}}}),Tk=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:h=!0,...v}=dn(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const b=un(i),_=Kt(c),S=un(c)===c,C=await(l.isRTL==null?void 0:l.isRTL(d.floating)),N=m||(S||!h?[Xo(c)]:fk(c)),E=g!=="none";!m&&E&&N.push(...yk(c,h,g,C));const A=[c,...N],M=await l.detectOverflow(t,v),U=[];let k=((r=a.flip)==null?void 0:r.overflows)||[];if(u&&U.push(M[b]),p){const L=mk(i,s,C);U.push(M[L[0]],M[L[1]])}if(k=[...k,{placement:i,overflows:U}],!U.every(L=>L<=0)){var F,j;const L=(((F=a.flip)==null?void 0:F.index)||0)+1,R=A[L];if(R&&(!(p==="alignment"&&_!==Kt(R))||k.every(I=>Kt(I.placement)===_?I.overflows[0]>0:!0)))return{data:{index:L,overflows:k},reset:{placement:R}};let P=(j=k.filter(I=>I.overflows[0]<=0).sort((I,D)=>I.overflows[1]-D.overflows[1])[0])==null?void 0:j.placement;if(!P)switch(f){case"bestFit":{var H;const I=(H=k.filter(D=>{if(E){const O=Kt(D.placement);return O===_||O==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(O=>O>0).reduce((O,W)=>O+W,0)]).sort((D,O)=>D[1]-O[1])[0])==null?void 0:H[0];I&&(P=I);break}case"initialPlacement":P=c;break}if(i!==P)return{reset:{placement:P}}}return{}}}};function tg(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ng(e){return uk.some(t=>e[t]>=0)}var Nk=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=dn(e,t);switch(i){case"referenceHidden":{const s=tg(await r.detectOverflow(t,{...a,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:ng(s)}}}case"escaped":{const s=tg(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:ng(s)}}}default:return{}}}}},rg=new Set(["left","top"]);async function Ik(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=un(n),c=zr(n),l=Kt(n)==="y",d=rg.has(s)?-1:1,u=a&&l?-1:1,p=dn(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof g=="number"&&(f=c==="end"?g*-1:g),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var kk=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:c}=t,l=await Ik(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:a+l.y,data:{...l,placement:s}}}}},Ek=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:b=>{let{x:_,y:S}=b;return{x:_,y:S}}},...d}=dn(e,t),u={x:n,y:r},p=await a.detectOverflow(t,d),m=Kt(un(i)),f=$l(m);let g=u[f],h=u[m];if(s){const b=f==="y"?"top":"left",_=f==="y"?"bottom":"right",S=g+p[b],C=g-p[_];g=Ll(S,g,C)}if(c){const b=m==="y"?"top":"left",_=m==="y"?"bottom":"right",S=h+p[b],C=h-p[_];h=Ll(S,h,C)}const v=l.fn({...t,[f]:g,[m]:h});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:s,[m]:c}}}}}},Pk=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:a,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=dn(e,t),u={x:n,y:r},p=Kt(i),m=$l(p);let f=u[m],g=u[p];const h=dn(c,t),v=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){const S=m==="y"?"height":"width",C=a.reference[m]-a.floating[S]+v.mainAxis,N=a.reference[m]+a.reference[S]-v.mainAxis;f<C?f=C:f>N&&(f=N)}if(d){var b,_;const S=m==="y"?"width":"height",C=rg.has(un(i)),N=a.reference[p]-a.floating[S]+(C&&((b=s.offset)==null?void 0:b[p])||0)+(C?0:v.crossAxis),E=a.reference[p]+a.reference[S]+(C?0:((_=s.offset)==null?void 0:_[p])||0)-(C?v.crossAxis:0);g<N?g=N:g>E&&(g=E)}return{[m]:f,[p]:g}}}},Ak=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:a,platform:s,elements:c}=t,{apply:l=()=>{},...d}=dn(e,t),u=await s.detectOverflow(t,d),p=un(i),m=zr(i),f=Kt(i)==="y",{width:g,height:h}=a.floating;let v,b;p==="top"||p==="bottom"?(v=p,b=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,v=m==="end"?"top":"bottom");const _=h-u.top-u.bottom,S=g-u.left-u.right,C=Nn(h-u[v],_),N=Nn(g-u[b],S),E=!t.middlewareData.shift;let A=C,M=N;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=_),E&&!m){const k=bt(u.left,0),F=bt(u.right,0),j=bt(u.top,0),H=bt(u.bottom,0);f?M=g-2*(k!==0||F!==0?k+F:bt(u.left,u.right)):A=h-2*(j!==0||H!==0?j+H:bt(u.top,u.bottom))}await l({...t,availableWidth:M,availableHeight:A});const U=await s.getDimensions(c.floating);return g!==U.width||h!==U.height?{reset:{rects:!0}}:{}}}};function Zo(){return typeof window<"u"}function Jr(e){return ig(e)?(e.nodeName||"").toLowerCase():"#document"}function _t(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Vt(e){var t;return(t=(ig(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ig(e){return Zo()?e instanceof Node||e instanceof _t(e).Node:!1}function Dt(e){return Zo()?e instanceof Element||e instanceof _t(e).Element:!1}function pn(e){return Zo()?e instanceof HTMLElement||e instanceof _t(e).HTMLElement:!1}function ag(e){return!Zo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof _t(e).ShadowRoot}function ta(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Lt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function xk(e){return/^(table|td|th)$/.test(Jr(e))}function es(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var Rk=/transform|translate|scale|rotate|perspective|filter/,Dk=/paint|layout|strict|content/,ir=e=>!!e&&e!=="none",Fl;function Bl(e){const t=Dt(e)?Lt(e):e;return ir(t.transform)||ir(t.translate)||ir(t.scale)||ir(t.rotate)||ir(t.perspective)||!Ul()&&(ir(t.backdropFilter)||ir(t.filter))||Rk.test(t.willChange||"")||Dk.test(t.contain||"")}function Lk(e){let t=In(e);for(;pn(t)&&!Yr(t);){if(Bl(t))return t;if(es(t))return null;t=In(t)}return null}function Ul(){return Fl==null&&(Fl=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Fl}function Yr(e){return/^(html|body|#document)$/.test(Jr(e))}function Lt(e){return _t(e).getComputedStyle(e)}function ts(e){return Dt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function In(e){if(Jr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||ag(e)&&e.host||Vt(e);return ag(t)?t.host:t}function og(e){const t=In(e);return Yr(t)?e.ownerDocument?e.ownerDocument.body:e.body:pn(t)&&ta(t)?t:og(t)}function na(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=og(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=_t(i);if(a){const c=Gl(s);return t.concat(s,s.visualViewport||[],ta(i)?i:[],c&&n?na(c):[])}else return t.concat(i,na(i,[],n))}function Gl(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function sg(e){const t=Lt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=pn(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=Jo(n)!==a||Jo(r)!==s;return c&&(n=a,r=s),{width:n,height:r,$:c}}function ql(e){return Dt(e)?e:e.contextElement}function Xr(e){const t=ql(e);if(!pn(t))return Ht(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=sg(t);let s=(a?Jo(n.width):n.width)/r,c=(a?Jo(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var $k=Ht(0);function cg(e){const t=_t(e);return!Ul()||!t.visualViewport?$k:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Mk(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==_t(e)?!1:t}function ar(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=ql(e);let s=Ht(1);t&&(r?Dt(r)&&(s=Xr(r)):s=Xr(e));const c=Mk(a,n,r)?cg(a):Ht(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(a){const m=_t(a),f=r&&Dt(r)?_t(r):r;let g=m,h=Gl(g);for(;h&&r&&f!==g;){const v=Xr(h),b=h.getBoundingClientRect(),_=Lt(h),S=b.left+(h.clientLeft+parseFloat(_.paddingLeft))*v.x,C=b.top+(h.clientTop+parseFloat(_.paddingTop))*v.y;l*=v.x,d*=v.y,u*=v.x,p*=v.y,l+=S,d+=C,g=_t(h),h=Gl(g)}}return Qo({width:u,height:p,x:l,y:d})}function ns(e,t){const n=ts(e).scrollLeft;return t?t.left+n:ar(Vt(e)).left+n}function lg(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-ns(e,n),y:n.top+t.scrollTop}}function Ok(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=Vt(r),c=t?es(t.floating):!1;if(r===s||c&&a)return n;let l={scrollLeft:0,scrollTop:0},d=Ht(1);const u=Ht(0),p=pn(r);if((p||!p&&!a)&&((Jr(r)!=="body"||ta(s))&&(l=ts(r)),p)){const f=ar(r);d=Xr(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!a?lg(s,l):Ht(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-l.scrollTop*d.y+u.y+m.y}}function jk(e){return Array.from(e.getClientRects())}function Fk(e){const t=Vt(e),n=ts(e),r=e.ownerDocument.body,i=bt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),a=bt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+ns(e);const c=-n.scrollTop;return Lt(r).direction==="rtl"&&(s+=bt(t.clientWidth,r.clientWidth)-i),{width:i,height:a,x:s,y:c}}var dg=25;function Bk(e,t){const n=_t(e),r=Vt(e),i=n.visualViewport;let a=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){a=i.width,s=i.height;const u=Ul();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=ns(r);if(d<=0){const u=r.ownerDocument,p=u.body,m=getComputedStyle(p),f=u.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,g=Math.abs(r.clientWidth-p.clientWidth-f);g<=dg&&(a-=g)}else d<=dg&&(a+=d);return{width:a,height:s,x:c,y:l}}function Uk(e,t){const n=ar(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=pn(e)?Xr(e):Ht(1);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function ug(e,t,n){let r;if(t==="viewport")r=Bk(e,n);else if(t==="document")r=Fk(Vt(e));else if(Dt(t))r=Uk(t,n);else{const i=cg(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Qo(r)}function pg(e,t){const n=In(e);return n===t||!Dt(n)||Yr(n)?!1:Lt(n).position==="fixed"||pg(n,t)}function Gk(e,t){const n=t.get(e);if(n)return n;let r=na(e,[],!1).filter(c=>Dt(c)&&Jr(c)!=="body"),i=null;const a=Lt(e).position==="fixed";let s=a?In(e):e;for(;Dt(s)&&!Yr(s);){const c=Lt(s),l=Bl(s);!l&&c.position==="fixed"&&(i=null),(a?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||ta(s)&&!l&&pg(e,s))?r=r.filter(d=>d!==s):i=c,s=In(s)}return t.set(e,r),r}function qk(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const a=[...n==="clippingAncestors"?es(t)?[]:Gk(t,this._c):[].concat(n),r],s=ug(t,a[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<a.length;p++){const m=ug(t,a[p],i);c=bt(m.top,c),l=Nn(m.right,l),d=Nn(m.bottom,d),u=bt(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function Hk(e){const{width:t,height:n}=sg(e);return{width:t,height:n}}function Kk(e,t,n){const r=pn(t),i=Vt(t),a=n==="fixed",s=ar(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=Ht(0);function d(){l.x=ns(i)}if(r||!r&&!a)if((Jr(t)!=="body"||ta(i))&&(c=ts(t)),r){const p=ar(t,!0,a,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();a&&!r&&i&&d();const u=i&&!r&&!a?lg(i,c):Ht(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 Hl(e){return Lt(e).position==="static"}function mg(e,t){if(!pn(e)||Lt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Vt(e)===n&&(n=n.ownerDocument.body),n}function fg(e,t){const n=_t(e);if(es(e))return n;if(!pn(e)){let i=In(e);for(;i&&!Yr(i);){if(Dt(i)&&!Hl(i))return i;i=In(i)}return n}let r=mg(e,t);for(;r&&xk(r)&&Hl(r);)r=mg(r,t);return r&&Yr(r)&&Hl(r)&&!Bl(r)?n:r||Lk(e)||n}var Vk=async function(e){const t=this.getOffsetParent||fg,n=this.getDimensions,r=await n(e.floating);return{reference:Kk(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Wk(e){return Lt(e).direction==="rtl"}var zk={convertOffsetParentRelativeRectToViewportRelativeRect:Ok,getDocumentElement:Vt,getClippingRect:qk,getOffsetParent:fg,getElementRects:Vk,getClientRects:jk,getDimensions:Hk,getScale:Xr,isElement:Dt,isRTL:Wk};function hg(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Jk(e,t){let n=null,r;const i=Vt(e);function a(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:u,top:p,width:m,height:f}=d;if(c||t(),!m||!f)return;const g=Yo(p),h=Yo(i.clientWidth-(u+m)),v=Yo(i.clientHeight-(p+f)),b=Yo(u),_={rootMargin:-g+"px "+-h+"px "+-v+"px "+-b+"px",threshold:bt(0,Nn(1,l))||1};let S=!0;function C(N){const E=N[0].intersectionRatio;if(E!==l){if(!S)return s();E?s(!1,E):r=setTimeout(()=>{s(!1,1e-7)},1e3)}E===1&&!hg(d,e.getBoundingClientRect())&&s(),S=!1}try{n=new IntersectionObserver(C,{..._,root:i.ownerDocument})}catch{n=new IntersectionObserver(C,_)}n.observe(e)}return s(!0),a}function Yk(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=ql(e),u=i||a?[...d?na(d):[],...t?na(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),a&&b.addEventListener("resize",n)});const p=d&&c?Jk(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(b=>{let[_]=b;_&&_.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!l&&f.observe(d),t&&f.observe(t));let g,h=l?ar(e):null;l&&v();function v(){const b=ar(e);h&&!hg(h,b)&&n(),h=b,g=requestAnimationFrame(v)}return n(),()=>{var b;u.forEach(_=>{i&&_.removeEventListener("scroll",n),a&&_.removeEventListener("resize",n)}),p?.(),(b=f)==null||b.disconnect(),f=null,l&&cancelAnimationFrame(g)}}var Xk=kk,Qk=Ek,Zk=Tk,eE=Ak,tE=Nk,gg=Ck,nE=Pk,rE=(e,t,n)=>{const r=new Map,i={platform:zk,...n},a={...i.platform,_c:r};return Sk(e,t,{...i,platform:a})},rs=typeof document<"u"?yt:function(){};function is(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(!is(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!is(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function vg(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function yg(e,t){const n=vg(e);return Math.round(t*n)/n}function Kl(e){const t=G(e);return rs(()=>{t.current=e}),t}function iE(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=x({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=x(r);is(m,r)||f(r);const[g,h]=x(null),[v,b]=x(null),_=ce(D=>{D!==E.current&&(E.current=D,h(D))},[]),S=ce(D=>{D!==A.current&&(A.current=D,b(D))},[]),C=a||g,N=s||v,E=G(null),A=G(null),M=G(u),U=l!=null,k=Kl(l),F=Kl(i),j=Kl(d),H=ce(()=>{if(!E.current||!A.current)return;const D={placement:t,strategy:n,middleware:m};F.current&&(D.platform=F.current),rE(E.current,A.current,D).then(O=>{const W={...O,isPositioned:j.current!==!1};L.current&&!is(M.current,W)&&(M.current=W,fo(()=>{p(W)}))})},[m,t,n,F,j]);rs(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[d]);const L=G(!1);rs(()=>(L.current=!0,()=>{L.current=!1}),[]),rs(()=>{if(C&&(E.current=C),N&&(A.current=N),C&&N){if(k.current)return k.current(C,N,H);H()}},[C,N,H,k,U]);const R=xe(()=>({reference:E,floating:A,setReference:_,setFloating:S}),[_,S]),P=xe(()=>({reference:C,floating:N}),[C,N]),I=xe(()=>{const D={position:n,left:0,top:0};if(!P.floating)return D;const O=yg(P.floating,u.x),W=yg(P.floating,u.y);return c?{...D,transform:"translate("+O+"px, "+W+"px)",...vg(P.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:O,top:W}},[n,c,P.floating,u.x,u.y]);return xe(()=>({...u,update:H,refs:R,elements:P,floatingStyles:I}),[u,H,R,P,I])}var aE=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?gg({element:r.current,padding:i}).fn(n):{}:r?gg({element:r,padding:i}).fn(n):{}}}},oE=(e,t)=>{const n=Xk(e);return{name:n.name,fn:n.fn,options:[e,t]}},sE=(e,t)=>{const n=Qk(e);return{name:n.name,fn:n.fn,options:[e,t]}},cE=(e,t)=>({fn:nE(e).fn,options:[e,t]}),lE=(e,t)=>{const n=Zk(e);return{name:n.name,fn:n.fn,options:[e,t]}},dE=(e,t)=>{const n=eE(e);return{name:n.name,fn:n.fn,options:[e,t]}},uE=(e,t)=>{const n=tE(e);return{name:n.name,fn:n.fn,options:[e,t]}},pE=(e,t)=>{const n=aE(e);return{name:n.name,fn:n.fn,options:[e,t]}},mE="Arrow",bg=V((e,t)=>{const{children:n,width:r=10,height:i=5,...a}=e;return o(pe.svg,{...a,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o("polygon",{points:"0,0 30,0 15,10"})})});bg.displayName=mE;var fE=bg;function Vl(e){const[t,n]=x(void 0);return We(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Wl="Popper",[_g,kn]=st(Wl),[hE,wg]=_g(Wl),Sg=e=>{const{__scopePopper:t,children:n}=e,[r,i]=x(null);return o(hE,{scope:t,anchor:r,onAnchorChange:i,children:n})};Sg.displayName=Wl;var Cg="PopperAnchor",Tg=V((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,a=wg(Cg,n),s=G(null),c=we(t,s),l=G(null);return z(()=>{const d=l.current;l.current=r?.current||s.current,d!==l.current&&a.onAnchorChange(l.current)}),r?null:o(pe.div,{...i,ref:c})});Tg.displayName=Cg;var zl="PopperContent",[gE,vE]=_g(zl),Ng=V((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:a="center",alignOffset:s=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:p="partial",hideWhenDetached:m=!1,updatePositionStrategy:f="optimized",onPlaced:g,...h}=e,v=wg(zl,n),[b,_]=x(null),S=we(t,ne=>_(ne)),[C,N]=x(null),E=Vl(C),A=E?.width??0,M=E?.height??0,U=r+(a!=="center"?"-"+a:""),k=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},F=Array.isArray(d)?d:[d],j=F.length>0,H={padding:k,boundary:F.filter(bE),altBoundary:j},{refs:L,floatingStyles:R,placement:P,isPositioned:I,middlewareData:D}=iE({strategy:"fixed",placement:U,whileElementsMounted:(...ne)=>Yk(...ne,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[oE({mainAxis:i+M,alignmentAxis:s}),l&&sE({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?cE():void 0,...H}),l&&lE({...H}),dE({...H,apply:({elements:ne,rects:Pe,availableWidth:ge,availableHeight:ae})=>{const{width:Ee,height:le}=Pe.reference,Te=ne.floating.style;Te.setProperty("--radix-popper-available-width",`${ge}px`),Te.setProperty("--radix-popper-available-height",`${ae}px`),Te.setProperty("--radix-popper-anchor-width",`${Ee}px`),Te.setProperty("--radix-popper-anchor-height",`${le}px`)}}),C&&pE({element:C,padding:c}),_E({arrowWidth:A,arrowHeight:M}),m&&uE({strategy:"referenceHidden",...H})]}),[O,W]=Eg(P),ue=lt(g);We(()=>{I&&ue?.()},[I,ue]);const re=D.arrow?.x,ie=D.arrow?.y,be=D.arrow?.centerOffset!==0,[Y,fe]=x();return We(()=>{b&&fe(window.getComputedStyle(b).zIndex)},[b]),o("div",{ref:L.setFloating,"data-radix-popper-content-wrapper":"",style:{...R,transform:I?R.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Y,"--radix-popper-transform-origin":[D.transformOrigin?.x,D.transformOrigin?.y].join(" "),...D.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o(gE,{scope:n,placedSide:O,onArrowChange:N,arrowX:re,arrowY:ie,shouldHideArrow:be,children:o(pe.div,{"data-side":O,"data-align":W,...h,ref:S,style:{...h.style,animation:I?void 0:"none"}})})})});Ng.displayName=zl;var Ig="PopperArrow",yE={top:"bottom",right:"left",bottom:"top",left:"right"},kg=V(function(t,n){const{__scopePopper:r,...i}=t,a=vE(Ig,r),s=yE[a.placedSide];return o("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:o(fE,{...i,ref:n,style:{...i.style,display:"block"}})})});kg.displayName=Ig;function bE(e){return e!==null}var _E=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[l,d]=Eg(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,m=(i.arrow?.y??0)+c/2;let f="",g="";return l==="bottom"?(f=a?u:`${p}px`,g=`${-c}px`):l==="top"?(f=a?u:`${p}px`,g=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,g=a?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,g=a?u:`${m}px`),{data:{x:f,y:g}}}});function Eg(e){const[t,n="center"]=e.split("-");return[t,n]}var ra=Sg,ia=Tg,as=Ng,os=kg,ss="Popover",[Pg,Y1]=st(ss,[kn]),aa=kn(),[wE,En]=Pg(ss),Ag=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,c=aa(t),l=G(null),[d,u]=x(!1),[p,m]=Tt({prop:r,defaultProp:i??!1,onChange:a,caller:ss});return o(ra,{...c,children:o(wE,{scope:t,contentId:ct(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:ce(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:ce(()=>u(!0),[]),onCustomAnchorRemove:ce(()=>u(!1),[]),modal:s,children:n})})};Ag.displayName=ss;var xg="PopoverAnchor",Rg=V((e,t)=>{const{__scopePopover:n,...r}=e,i=En(xg,n),a=aa(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return z(()=>(s(),()=>c()),[s,c]),o(ia,{...a,...r,ref:t})});Rg.displayName=xg;var Dg="PopoverTrigger",Lg=V((e,t)=>{const{__scopePopover:n,...r}=e,i=En(Dg,n),a=aa(n),s=we(t,i.triggerRef),c=o(pe.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Fg(i.open),...r,ref:s,onClick:Q(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:o(ia,{asChild:!0,...a,children:c})});Lg.displayName=Dg;var Jl="PopoverPortal",[SE,CE]=Pg(Jl,{forceMount:void 0}),$g=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=En(Jl,t);return o(SE,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Xn,{asChild:!0,container:i,children:r})})})};$g.displayName=Jl;var Qr="PopoverContent",Mg=V((e,t)=>{const n=CE(Qr,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=En(Qr,e.__scopePopover);return o(nt,{present:r||a.open,children:a.modal?o(NE,{...i,ref:t}):o(IE,{...i,ref:t})})});Mg.displayName=Qr;var TE=Jn("PopoverContent.RemoveScroll"),NE=V((e,t)=>{const n=En(Qr,e.__scopePopover),r=G(null),i=we(t,r),a=G(!1);return z(()=>{const s=r.current;if(s)return No(s)},[]),o(Bi,{as:TE,allowPinchZoom:!0,children:o(Og,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Q(e.onCloseAutoFocus,s=>{s.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:Q(e.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;a.current=c.button===2||l},{checkForDefaultPrevented:!1}),onFocusOutside:Q(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),IE=V((e,t)=>{const n=En(Qr,e.__scopePopover),r=G(!1),i=G(!1);return o(Og,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||n.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;n.triggerRef.current?.contains(s)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Og=V((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=En(Qr,n),f=aa(n);return vo(),o(ji,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o(Yn,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:o(as,{"data-state":Fg(m.open),role:"dialog",id:m.contentId,...f,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),jg="PopoverClose",kE=V((e,t)=>{const{__scopePopover:n,...r}=e,i=En(jg,n);return o(pe.button,{type:"button",...r,ref:t,onClick:Q(e.onClick,()=>i.onOpenChange(!1))})});kE.displayName=jg;var EE="PopoverArrow",PE=V((e,t)=>{const{__scopePopover:n,...r}=e,i=aa(n);return o(os,{...i,...r,ref:t})});PE.displayName=EE;function Fg(e){return e?"open":"closed"}var Bg=Ag,AE=Rg,xE=Lg,Ug=$g,Gg=Mg;function Yl(e){return e.trim()}function qg({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:a,"aria-labelledby":s}){const[c,l]=x(!1),[d,u]=x(""),[p,m]=x(0),f=G(null),g=xe(()=>{const k=new Set,F=[];for(const j of[...n,...e]){const H=Yl(j);!H||k.has(H)||(k.add(H),F.push(H))}return F.sort((j,H)=>j.localeCompare(H))},[n,e]),h=Yl(d),v=h.toLowerCase(),b=xe(()=>v?g.filter(k=>k.toLowerCase().includes(v)):g,[g,v]),_=h?g.some(k=>k.toLowerCase()===v):!1,S=!!h&&!_,C=b.length+(S?1:0);z(()=>{p>=C&&m(Math.max(0,C-1))},[C,p]),z(()=>{if(!c)return;const k=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(k)},[c]);const N=k=>{e.includes(k)?t(e.filter(F=>F!==k)):t(Array.from(new Set([...e,k])))},E=k=>{const F=Yl(k);F&&(t(Array.from(new Set([...e,F]))),u(""),m(0))},A=k=>{if(k<b.length){const F=b[k];F&&N(F);return}S&&E(h)},M=k=>{if(k.key==="ArrowDown"){k.preventDefault(),m(F=>Math.min(C-1,F+1));return}if(k.key==="ArrowUp"){k.preventDefault(),m(F=>Math.max(0,F-1));return}if(k.key==="Enter"){k.preventDefault(),A(p);return}},U=k=>{t(e.filter(F=>F!==k))};return o("div",{class:"project-scope-picker",children:[o("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?o("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(k=>o("li",{class:"project-scope-picker-selected-chip",children:[o("span",{children:k}),a?null:o("button",{"aria-label":`Remove ${k}`,class:"project-scope-picker-selected-remove",onClick:()=>U(k),type:"button",children:"×"})]},k))}),o(Bg,{onOpenChange:k=>{l(k),k||(u(""),m(0))},open:c,children:[o(xE,{asChild:!0,children:o("button",{class:"project-scope-picker-trigger settings-button",disabled:a,type:"button",children:[o("span",{"aria-hidden":"true",children:"+"}),o("span",{children:r||"Add project"})]})}),o(Ug,{children:o(Gg,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[o("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:k=>{u(k.currentTarget.value),m(0)},onKeyDown:M,placeholder:"Search or create…",ref:f,type:"text",value:d}),o("div",{class:"project-scope-picker-results",role:"listbox",children:[b.length===0&&!S?o("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((k,F)=>{const j=e.includes(k);return o("button",{"aria-selected":j,class:F===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(F),N(k)},onMouseEnter:()=>m(F),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:j?"✓":""}),o("span",{class:"project-scope-picker-row-label",children:k})]},k)}),S?o("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:()=>E(h),onMouseEnter:()=>m(b.length),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),o("span",{class:"project-scope-picker-row-label",children:`Create "${h}"`})]}):null]})]})})]})]})}function Xl(e){const t=G({value:e,previous:e});return xe(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var cs="Switch",[RE,X1]=st(cs),[DE,LE]=RE(cs),Hg=V((e,t)=>{const{__scopeSwitch:n,name:r,checked:i,defaultChecked:a,required:s,disabled:c,value:l="on",onCheckedChange:d,form:u,...p}=e,[m,f]=x(null),g=we(t,S=>f(S)),h=G(!1),v=m?u||!!m.closest("form"):!0,[b,_]=Tt({prop:i,defaultProp:a??!1,onChange:d,caller:cs});return o(DE,{scope:n,checked:b,disabled:c,children:[o(pe.button,{type:"button",role:"switch","aria-checked":b,"aria-required":s,"data-state":zg(b),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:g,onClick:Q(e.onClick,S=>{_(C=>!C),v&&(h.current=S.isPropagationStopped(),h.current||S.stopPropagation())})}),v&&o(Wg,{control:m,bubbles:!h.current,name:r,value:l,checked:b,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});Hg.displayName=cs;var Kg="SwitchThumb",Vg=V((e,t)=>{const{__scopeSwitch:n,...r}=e,i=LE(Kg,n);return o(pe.span,{"data-state":zg(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Vg.displayName=Kg;var $E="SwitchBubbleInput",Wg=V(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=G(null),c=we(s,a),l=Xl(n),d=Vl(t);return z(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Wg.displayName=$E;function zg(e){return e?"checked":"unchecked"}var ME=Hg,OE=Vg;function Zr({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:a,onCheckedChange:s,thumbClassName:c}){return o(ME,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:a,onCheckedChange:s,children:o(OE,{className:c})})}function se(e,t="success"){yI(e,t)}function Jg(e){return`${ok}:${String(e||"").trim()}`}function jE(e){try{return localStorage.getItem(Jg(e))||""}catch{return""}}function FE(e,t){try{localStorage.setItem(Jg(e),t)}catch{}}function or(){return String(w.coordinatorAdminTargetGroup||"").trim()}function Ql(e){w.coordinatorAdminTargetGroup=e,FE(w.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function ei(){return(Array.isArray(w.lastCoordinatorAdminGroups)?w.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 BE(){const e=new Map;for(const t of ei())e.set(t.group_id,t.display_name||t.group_id);q.groupRenameDrafts.clear();for(const[t,n]of e.entries())q.groupRenameDrafts.set(t,n)}function UE(){const e=or();return ei().find(t=>t.group_id===e)||null}function Yg(){const e=w.lastCoordinatorAdminStatus,t=ei(),n=String(e?.active_group||"").trim(),r=jE(e?.coordinator_url||null),i=or(),a=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(a.size===0||a.has(s))?s:n||t[0]?.group_id||"";return Ql(c),c}function GE(){const e=new Map,t=new Map,n=Array.isArray(w.lastCoordinatorAdminDevices)?w.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const a=String(r.display_name||""),s=q.deviceRenameDrafts.get(i),c=q.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:a),t.set(i,a)}q.deviceRenameDrafts.clear();for(const[r,i]of e.entries())q.deviceRenameDrafts.set(r,i);q.deviceRenameServerNames.clear();for(const[r,i]of t.entries())q.deviceRenameServerNames.set(r,i)}function qE(e,t){return t&&t.groupId===e?t:null}function HE(e,t){return e?.loaded&&e.default_space_scope_id?"Configured":e?.loaded?"Not configured":t?.defaultSpaceLabel?t.defaultSpaceLabel:t?.defaultSpaceScopeId?"Configured":"Open Team defaults to inspect"}function KE(e,t){return e?.loaded?e.auto_grant_default_space_on_join?"On for the default Space":"Off — Space access stays explicit":t?.autoGrantDefaultSpaceOnJoin===!0?"On for the default Space":t?.autoGrantDefaultSpaceOnJoin===!1?"Off — Space access stays explicit":"Open Team defaults to inspect"}function VE(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function WE(e){const t=VE(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function zE(e){const t=qE(e.groupId,e.setupGuide);return{autoGrant:KE(e.preferences,t),defaultSpace:HE(e.preferences,t),spaces:WE(e.scopeManagement)}}var Zl=null,ls=null,ed=null;function JE(){return Zl}function td(e){ls=e}function Xg(e){ed=e}function YE(e){return ed===e}function XE(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function nd(e){return!Zl||!ls?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function ds(e){Zl=e,ed?.(e)}function Pn(e){const t=ls;ls=null,ds(null),t?.(e)}function QE(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var ZE=V(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:a=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=G(null);uo(p,()=>m.current,[]);const[f,g]=x(!1),[h,v]=x(-1),b=xe(()=>{const N=t.trim().toLowerCase();return(N?r.filter(E=>E.toLowerCase().includes(N)):r).slice(0,a)},[t,r,a]);z(()=>{h>=b.length&&v(b.length-1)},[b.length,h]);const _=f&&b.length>0,S=N=>{n(N),g(!1),v(-1),m.current?.focus()};return o(Bg,{open:_,onOpenChange:g,children:[o(AE,{asChild:!0,children:o("input",{...u,ref:m,className:d,value:t,onInput:N=>{n(N.currentTarget.value),g(!0),v(-1)},onFocus:N=>{c?.(N)},onBlur:N=>{window.setTimeout(()=>g(!1),120),l?.(N)},onKeyDown:N=>{if(N.key==="ArrowDown"){N.preventDefault(),g(!0),v(E=>b.length===0?-1:Math.min(E+1,b.length-1));return}if(N.key==="ArrowUp"){N.preventDefault(),f||g(!0),v(E=>Math.max(E-1,-1));return}if(N.key==="Escape"&&_){N.preventDefault(),g(!1),v(-1);return}if((N.key==="Tab"||N.key==="Enter")&&h>=0){const E=b[h];if(E){N.preventDefault(),S(E);return}}if(N.key==="Enter"&&i){N.preventDefault(),i();return}s?.(N)},role:"combobox","aria-autocomplete":"list","aria-expanded":_,"aria-controls":"autocompleteListbox","aria-activedescendant":h>=0?`autocomplete-option-${h}`:void 0})}),o(Ug,{children:o(Gg,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:N=>N.preventDefault(),onCloseAutoFocus:N=>N.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:o("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((N,E)=>{const A=E===h;return o("div",{"aria-selected":A,className:A?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${E}`,onMouseDown:M=>{M.preventDefault(),S(N)},onMouseEnter:()=>v(E),role:"option",tabIndex:-1,children:N},N)})})})})]})}),rd="Radio",[eP,Qg]=st(rd),[tP,nP]=eP(rd),Zg=V((e,t)=>{const{__scopeRadio:n,name:r,checked:i=!1,required:a,disabled:s,value:c="on",onCheck:l,form:d,...u}=e,[p,m]=x(null),f=we(t,v=>m(v)),g=G(!1),h=p?d||!!p.closest("form"):!0;return o(tP,{scope:n,checked:i,disabled:s,children:[o(pe.button,{type:"button",role:"radio","aria-checked":i,"data-state":rv(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:Q(e.onClick,v=>{i||l?.(),h&&(g.current=v.isPropagationStopped(),g.current||v.stopPropagation())})}),h&&o(nv,{control:p,bubbles:!g.current,name:r,value:c,checked:i,required:a,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});Zg.displayName=rd;var ev="RadioIndicator",tv=V((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,a=nP(ev,n);return o(nt,{present:r||a.checked,children:o(pe.span,{"data-state":rv(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:t})})});tv.displayName=ev;var rP="RadioBubbleInput",nv=V(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=G(null),c=we(s,a),l=Xl(n),d=Vl(t);return z(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o(pe.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});nv.displayName=rP;function rv(e){return e?"checked":"unchecked"}var iP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],us="RadioGroup",[aP,Q1]=st(us,[Wr,Qg]),iv=Wr(),av=Qg(),[oP,sP]=aP(us),ov=V((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:i,value:a,required:s=!1,disabled:c=!1,orientation:l,dir:d,loop:u=!0,onValueChange:p,...m}=e,f=iv(n),g=Zi(d),[h,v]=Tt({prop:a,defaultProp:i??null,onChange:p,caller:us});return o(oP,{scope:n,name:r,required:s,disabled:c,value:h,onValueChange:v,children:o(El,{asChild:!0,...f,orientation:l,dir:g,loop:u,children:o(pe.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:g,...m,ref:t})})})});ov.displayName=us;var sv="RadioGroupItem",cv=V((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,a=sP(sv,n),s=a.disabled||r,c=iv(n),l=av(n),d=G(null),u=we(t,d),p=a.value===i.value,m=G(!1);return z(()=>{const f=h=>{iP.includes(h.key)&&(m.current=!0)},g=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",g),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",g)}},[]),o(Pl,{asChild:!0,...c,focusable:!s,active:p,children:o(Zg,{disabled:s,required:a.required,checked:p,...l,...i,name:a.name,ref:u,onCheck:()=>a.onValueChange(i.value),onKeyDown:Q(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:Q(i.onFocus,()=>{m.current&&d.current?.click()})})})});cv.displayName=sv;var cP="RadioGroupIndicator",lv=V((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return o(tv,{...av(n),...r,ref:t})});lv.displayName=cP;var lP=ov,dP=cv,uP=lv;function pP({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:a,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return o(lP,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,m)=>{const f=`radio-option-input-${m}`,g=`radio-option-label-${m}`;return o("label",{className:i,htmlFor:f,children:[o(dP,{id:f,"aria-labelledby":g,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:o(uP,{className:r})}),o("span",{className:a,id:g,children:p.label})]},p.value)})})}function dv(e,[t,n]){return Math.min(n,Math.max(t,e))}var mP=[" ","Enter","ArrowUp","ArrowDown"],fP=[" ","Enter"],sr="Select",[ps,ms,hP]=Bo(sr),[ti,Z1]=st(sr,[hP,kn]),fs=kn(),[gP,An]=ti(sr),[vP,yP]=ti(sr),uv=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:a,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:m,required:f,form:g}=e,h=fs(t),[v,b]=x(null),[_,S]=x(null),[C,N]=x(!1),E=Zi(d),[A,M]=Tt({prop:r,defaultProp:i??!1,onChange:a,caller:sr}),[U,k]=Tt({prop:s,defaultProp:c,onChange:l,caller:sr}),F=G(null),j=v?g||!!v.closest("form"):!0,[H,L]=x(new Set),R=Array.from(H).map(P=>P.props.value).join(";");return o(ra,{...h,children:o(gP,{required:f,scope:t,trigger:v,onTriggerChange:b,valueNode:_,onValueNodeChange:S,valueNodeHasChildren:C,onValueNodeHasChildrenChange:N,contentId:ct(),value:U,onValueChange:k,open:A,onOpenChange:M,dir:E,triggerPointerDownPosRef:F,disabled:m,children:[o(ps.Provider,{scope:t,children:o(vP,{scope:e.__scopeSelect,onNativeOptionAdd:ce(P=>{L(I=>new Set(I).add(P))},[]),onNativeOptionRemove:ce(P=>{L(I=>{const D=new Set(I);return D.delete(P),D})},[]),children:n})}),j?o(xv,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:U,onChange:P=>k(P.target.value),disabled:m,form:g,children:[U===void 0?o("option",{value:""}):null,Array.from(H)]},R):null]})})};uv.displayName=sr;var pv="SelectTrigger",mv=V((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,a=fs(n),s=An(pv,n),c=s.disabled||r,l=we(t,s.onTriggerChange),d=ms(n),u=G("touch"),[p,m,f]=Dv(h=>{const v=d().filter(_=>!_.disabled),b=Lv(v,h,v.find(_=>_.value===s.value));b!==void 0&&s.onValueChange(b.value)}),g=h=>{c||(s.onOpenChange(!0),f()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return o(ia,{asChild:!0,...a,children:o(pe.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Rv(s.value)?"":void 0,...i,ref:l,onClick:Q(i.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&g(h)}),onPointerDown:Q(i.onPointerDown,h=>{u.current=h.pointerType;const v=h.target;v.hasPointerCapture(h.pointerId)&&v.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(g(h),h.preventDefault())}),onKeyDown:Q(i.onKeyDown,h=>{const v=p.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&m(h.key),!(v&&h.key===" ")&&mP.includes(h.key)&&(g(),h.preventDefault())})})})});mv.displayName=pv;var fv="SelectValue",hv=V((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:a,placeholder:s="",...c}=e,l=An(fv,n),{onValueNodeHasChildrenChange:d}=l,u=a!==void 0,p=we(t,l.onValueNodeChange);return We(()=>{d(u)},[d,u]),o(pe.span,{...c,ref:p,style:{pointerEvents:"none"},children:Rv(l.value)?o(Z,{children:s}):a})});hv.displayName=fv;var bP="SelectIcon",gv=V((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return o(pe.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});gv.displayName=bP;var _P="SelectPortal",vv=e=>o(Xn,{asChild:!0,...e});vv.displayName=_P;var cr="SelectContent",yv=V((e,t)=>{const n=An(cr,e.__scopeSelect),[r,i]=x();if(We(()=>{i(new DocumentFragment)},[]),!n.open){const a=r;return a?on(o(bv,{scope:e.__scopeSelect,children:o(ps.Slot,{scope:e.__scopeSelect,children:o("div",{children:e.children})})}),a):null}return o(_v,{...e,ref:t})});yv.displayName=cr;var $t=10,[bv,xn]=ti(cr),wP="SelectContentImpl",SP=Jn("SelectContent.RemoveScroll"),_v=V((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:s,side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v,...b}=e,_=An(cr,n),[S,C]=x(null),[N,E]=x(null),A=we(t,ne=>C(ne)),[M,U]=x(null),[k,F]=x(null),j=ms(n),[H,L]=x(!1),R=G(!1);z(()=>{if(S)return No(S)},[S]),vo();const P=ce(ne=>{const[Pe,...ge]=j().map(le=>le.ref.current),[ae]=ge.slice(-1),Ee=document.activeElement;for(const le of ne)if(le===Ee||(le?.scrollIntoView({block:"nearest"}),le===Pe&&N&&(N.scrollTop=0),le===ae&&N&&(N.scrollTop=N.scrollHeight),le?.focus(),document.activeElement!==Ee))return},[j,N]),I=ce(()=>P([M,S]),[P,M,S]);z(()=>{H&&I()},[H,I]);const{onOpenChange:D,triggerPointerDownPosRef:O}=_;z(()=>{if(S){let ne={x:0,y:0};const Pe=ae=>{ne={x:Math.abs(Math.round(ae.pageX)-(O.current?.x??0)),y:Math.abs(Math.round(ae.pageY)-(O.current?.y??0))}},ge=ae=>{ne.x<=10&&ne.y<=10?ae.preventDefault():S.contains(ae.target)||D(!1),document.removeEventListener("pointermove",Pe),O.current=null};return O.current!==null&&(document.addEventListener("pointermove",Pe),document.addEventListener("pointerup",ge,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Pe),document.removeEventListener("pointerup",ge,{capture:!0})}}},[S,D,O]),z(()=>{const ne=()=>D(!1);return window.addEventListener("blur",ne),window.addEventListener("resize",ne),()=>{window.removeEventListener("blur",ne),window.removeEventListener("resize",ne)}},[D]);const[W,ue]=Dv(ne=>{const Pe=j().filter(ae=>!ae.disabled),ge=Lv(Pe,ne,Pe.find(ae=>ae.ref.current===document.activeElement));ge&&setTimeout(()=>ge.ref.current.focus())}),re=ce((ne,Pe,ge)=>{const ae=!R.current&&!ge;(_.value!==void 0&&_.value===Pe||ae)&&(U(ne),ae&&(R.current=!0))},[_.value]),ie=ce(()=>S?.focus(),[S]),be=ce((ne,Pe,ge)=>{const ae=!R.current&&!ge;(_.value!==void 0&&_.value===Pe||ae)&&F(ne)},[_.value]),Y=r==="popper"?id:wv,fe=Y===id?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:g,hideWhenDetached:h,avoidCollisions:v}:{};return o(bv,{scope:n,content:S,viewport:N,onViewportChange:E,itemRefCallback:re,selectedItem:M,onItemLeave:ie,itemTextRefCallback:be,focusSelectedItem:I,selectedItemText:k,position:r,isPositioned:H,searchRef:W,children:o(Bi,{as:SP,allowPinchZoom:!0,children:o(ji,{asChild:!0,trapped:_.open,onMountAutoFocus:ne=>{ne.preventDefault()},onUnmountAutoFocus:Q(i,ne=>{_.trigger?.focus({preventScroll:!0}),ne.preventDefault()}),children:o(Yn,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:ne=>ne.preventDefault(),onDismiss:()=>_.onOpenChange(!1),children:o(Y,{role:"listbox",id:_.contentId,"data-state":_.open?"open":"closed",dir:_.dir,onContextMenu:ne=>ne.preventDefault(),...b,...fe,onPlaced:()=>L(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Q(b.onKeyDown,ne=>{const Pe=ne.ctrlKey||ne.altKey||ne.metaKey;if(ne.key==="Tab"&&ne.preventDefault(),!Pe&&ne.key.length===1&&ue(ne.key),["ArrowUp","ArrowDown","Home","End"].includes(ne.key)){let ge=j().filter(ae=>!ae.disabled).map(ae=>ae.ref.current);if(["ArrowUp","End"].includes(ne.key)&&(ge=ge.slice().reverse()),["ArrowUp","ArrowDown"].includes(ne.key)){const ae=ne.target,Ee=ge.indexOf(ae);ge=ge.slice(Ee+1)}setTimeout(()=>P(ge)),ne.preventDefault()}})})})})})})});_v.displayName=wP;var CP="SelectItemAlignedPosition",wv=V((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,a=An(cr,n),s=xn(cr,n),[c,l]=x(null),[d,u]=x(null),p=we(t,E=>u(E)),m=ms(n),f=G(!1),g=G(!0),{viewport:h,selectedItem:v,selectedItemText:b,focusSelectedItem:_}=s,S=ce(()=>{if(a.trigger&&a.valueNode&&c&&d&&h&&v&&b){const E=a.trigger.getBoundingClientRect(),A=d.getBoundingClientRect(),M=a.valueNode.getBoundingClientRect(),U=b.getBoundingClientRect();if(a.dir!=="rtl"){const ge=U.left-A.left,ae=M.left-ge,Ee=E.left-ae,le=E.width+Ee,Te=Math.max(le,A.width),B=window.innerWidth-$t,oe=dv(ae,[$t,Math.max($t,B-Te)]);c.style.minWidth=le+"px",c.style.left=oe+"px"}else{const ge=A.right-U.right,ae=window.innerWidth-M.right-ge,Ee=window.innerWidth-E.right-ae,le=E.width+Ee,Te=Math.max(le,A.width),B=window.innerWidth-$t,oe=dv(ae,[$t,Math.max($t,B-Te)]);c.style.minWidth=le+"px",c.style.right=oe+"px"}const k=m(),F=window.innerHeight-$t*2,j=h.scrollHeight,H=window.getComputedStyle(d),L=parseInt(H.borderTopWidth,10),R=parseInt(H.paddingTop,10),P=parseInt(H.borderBottomWidth,10),I=parseInt(H.paddingBottom,10),D=L+R+j+I+P,O=Math.min(v.offsetHeight*5,D),W=window.getComputedStyle(h),ue=parseInt(W.paddingTop,10),re=parseInt(W.paddingBottom,10),ie=E.top+E.height/2-$t,be=F-ie,Y=v.offsetHeight/2,fe=v.offsetTop+Y,ne=L+R+fe,Pe=D-ne;if(ne<=ie){const ge=k.length>0&&v===k[k.length-1].ref.current;c.style.bottom="0px";const ae=d.clientHeight-h.offsetTop-h.offsetHeight,Ee=ne+Math.max(be,Y+(ge?re:0)+ae+P);c.style.height=Ee+"px"}else{const ge=k.length>0&&v===k[0].ref.current;c.style.top="0px";const ae=Math.max(ie,L+h.offsetTop+(ge?ue:0)+Y)+Pe;c.style.height=ae+"px",h.scrollTop=ne-ie+h.offsetTop}c.style.margin=`${$t}px 0`,c.style.minHeight=O+"px",c.style.maxHeight=F+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,a.trigger,a.valueNode,c,d,h,v,b,a.dir,r]);We(()=>S(),[S]);const[C,N]=x();return We(()=>{d&&N(window.getComputedStyle(d).zIndex)},[d]),o(NP,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:ce(E=>{E&&g.current===!0&&(S(),_?.(),g.current=!1)},[S,_]),children:o("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:o(pe.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});wv.displayName=CP;var TP="SelectPopperPosition",id=V((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=$t,...a}=e,s=fs(n);return o(as,{...s,...a,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});id.displayName=TP;var[NP,ad]=ti(cr,{}),od="SelectViewport",Sv=V((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,a=xn(od,n),s=ad(od,n),c=we(t,a.onViewportChange),l=G(0);return o(Z,{children:[o("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),o(ps.Slot,{scope:n,children:o(pe.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Q(i.onScroll,d=>{const u=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=s;if(m?.current&&p){const f=Math.abs(l.current-u.scrollTop);if(f>0){const g=window.innerHeight-$t*2,h=parseFloat(p.style.minHeight),v=parseFloat(p.style.height),b=Math.max(h,v);if(b<g){const _=b+f,S=Math.min(g,_),C=_-S;p.style.height=S+"px",p.style.bottom==="0px"&&(u.scrollTop=C>0?C:0,p.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});Sv.displayName=od;var Cv="SelectGroup",[IP,kP]=ti(Cv),EP=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=ct();return o(IP,{scope:n,id:i,children:o(pe.div,{role:"group","aria-labelledby":i,...r,ref:t})})});EP.displayName=Cv;var Tv="SelectLabel",PP=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=kP(Tv,n);return o(pe.div,{id:i.id,...r,ref:t})});PP.displayName=Tv;var hs="SelectItem",[AP,Nv]=ti(hs),Iv=V((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:a,...s}=e,c=An(hs,n),l=xn(hs,n),d=c.value===r,[u,p]=x(a??""),[m,f]=x(!1),g=we(t,_=>l.itemRefCallback?.(_,r,i)),h=ct(),v=G("touch"),b=()=>{i||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return o(AP,{scope:n,value:r,disabled:i,textId:h,isSelected:d,onItemTextChange:ce(_=>{p(S=>S||(_?.textContent??"").trim())},[]),children:o(ps.ItemSlot,{scope:n,value:r,disabled:i,textValue:u,children:o(pe.div,{role:"option","aria-labelledby":h,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...s,ref:g,onFocus:Q(s.onFocus,()=>f(!0)),onBlur:Q(s.onBlur,()=>f(!1)),onClick:Q(s.onClick,()=>{v.current!=="mouse"&&b()}),onPointerUp:Q(s.onPointerUp,()=>{v.current==="mouse"&&b()}),onPointerDown:Q(s.onPointerDown,_=>{v.current=_.pointerType}),onPointerMove:Q(s.onPointerMove,_=>{v.current=_.pointerType,i?l.onItemLeave?.():v.current==="mouse"&&_.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Q(s.onPointerLeave,_=>{_.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:Q(s.onKeyDown,_=>{l.searchRef?.current!==""&&_.key===" "||(fP.includes(_.key)&&b(),_.key===" "&&_.preventDefault())})})})})});Iv.displayName=hs;var oa="SelectItemText",kv=V((e,t)=>{const{__scopeSelect:n,className:r,style:i,...a}=e,s=An(oa,n),c=xn(oa,n),l=Nv(oa,n),d=yP(oa,n),[u,p]=x(null),m=we(t,b=>p(b),l.onItemTextChange,b=>c.itemTextRefCallback?.(b,l.value,l.disabled)),f=u?.textContent,g=xe(()=>o("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:h,onNativeOptionRemove:v}=d;return We(()=>(h(g),()=>v(g)),[h,v,g]),o(Z,{children:[o(pe.span,{id:l.textId,...a,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?on(a.children,s.valueNode):null]})});kv.displayName=oa;var Ev="SelectItemIndicator",Pv=V((e,t)=>{const{__scopeSelect:n,...r}=e;return Nv(Ev,n).isSelected?o(pe.span,{"aria-hidden":!0,...r,ref:t}):null});Pv.displayName=Ev;var sd="SelectScrollUpButton",xP=V((e,t)=>{const n=xn(sd,e.__scopeSelect),r=ad(sd,e.__scopeSelect),[i,a]=x(!1),s=we(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){a(l.scrollTop>0)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Av,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});xP.displayName=sd;var cd="SelectScrollDownButton",RP=V((e,t)=>{const n=xn(cd,e.__scopeSelect),r=ad(cd,e.__scopeSelect),[i,a]=x(!1),s=we(t,r.onScrollButtonChange);return We(()=>{if(n.viewport&&n.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight;a(Math.ceil(l.scrollTop)<d)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Av,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});RP.displayName=cd;var Av=V((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,a=xn("SelectScrollButton",n),s=G(null),c=ms(n),l=ce(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return z(()=>()=>l(),[l]),We(()=>{c().find(d=>d.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),o(pe.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:Q(i.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:Q(i.onPointerMove,()=>{a.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:Q(i.onPointerLeave,()=>{l()})})}),DP="SelectSeparator",LP=V((e,t)=>{const{__scopeSelect:n,...r}=e;return o(pe.div,{"aria-hidden":!0,...r,ref:t})});LP.displayName=DP;var ld="SelectArrow",$P=V((e,t)=>{const{__scopeSelect:n,...r}=e,i=fs(n),a=An(ld,n),s=xn(ld,n);return a.open&&s.position==="popper"?o(os,{...i,...r,ref:t}):null});$P.displayName=ld;var MP="SelectBubbleInput",xv=V(({__scopeSelect:e,value:t,...n},r)=>{const i=G(null),a=we(r,i),s=Xl(t);return z(()=>{const c=i.current;if(!c)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==t&&d){const u=new Event("change",{bubbles:!0});d.call(c,t),c.dispatchEvent(u)}},[s,t]),o(pe.select,{...n,style:{...rh,...n.style},ref:a,defaultValue:t})});xv.displayName=MP;function Rv(e){return e===""||e===void 0}function Dv(e){const t=lt(e),n=G(""),r=G(0),i=ce(s=>{const c=n.current+s;t(c),(function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=ce(()=>{n.current="",window.clearTimeout(r.current)},[]);return z(()=>()=>window.clearTimeout(r.current),[]),[n,i,a]}function Lv(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=OP(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function OP(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var jP=uv,FP=mv,BP=hv,UP=gv,GP=vv,qP=yv,HP=Sv,KP=Iv,VP=kv,WP=Pv,$v="__codemem-empty-select__";function zP(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Open"}),o("path",{d:"m6 9 6 6 6-6"})]})}function JP(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Selected"}),o("path",{d:"M20 6 9 17l-5-5"})]})}function dd(e){return e===""?$v:e}function YP(e){return e===$v?"":e}function Rn({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:a,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const m=u?dd(u):void 0;return o(jP,{disabled:r,onValueChange:f=>s(YP(f)),value:m,children:[o(FP,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[o(BP,{placeholder:l}),o(UP,{className:"sync-radix-select-icon","aria-hidden":"true",children:o(zP,{})})]}),o(GP,{children:o(qP,{className:n,position:"popper",children:o(HP,{className:p,children:c.map(f=>o(KP,{className:a,disabled:f.disabled,value:dd(f.value),children:[o(VP,{children:f.label}),o(WP,{className:"sync-radix-select-indicator",children:o(JP,{})})]},dd(f.value)))})})})]})}function XP({descriptionId:e,request:t}){const[n,r]=x("choice"),[i,a]=x(t.actors.find(v=>v.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=x("");z(()=>{r("choice");const v=t.actors.find(_=>_.isLocal)?.actorId||t.actors[0]?.actorId||"",b=t.actors.find(_=>_.actorId!==v)?.actorId||"";a(v),c(b)},[t]);const l=t.actors.find(v=>v.actorId===i)||t.actors[0],d=t.actors.filter(v=>v.actorId!==i),u=d.find(v=>v.actorId===s)||d[0],p=t.actors.map(v=>({label:o(Z,{children:[v.label,v.isLocal?" (You)":""]}),value:v.actorId})),m=d.map(v=>({label:`${v.label}${v.isLocal?" (You)":""}`,value:v.actorId})),f=!!(l?.actorId&&u?.actorId),g=()=>{!l?.actorId||!u?.actorId||Pn({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},h=v=>{const b=v.target instanceof HTMLElement?v.target:null;v.defaultPrevented||v.isComposing||v.key!=="Enter"||b?.closest(".sync-dialog-radio-list")&&f&&(v.preventDefault(),g())};return n==="choice"?o("div",{className:"sync-dialog-stack",children:o("ul",{className:"sync-dialog-choice-list",children:[o("li",{children:o("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>Pn({action:"different-people"}),type:"button",children:"These are different people"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>Pn({action:"cancel"}),type:"button",children:"Decide later"})})]})}):o("div",{className:"sync-dialog-stack",onKeyDown:v=>{h(v),Vr(v,{onSubmit:g,disabled:!f})},children:[o("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),o(pP,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:i,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:a,options:p,rootClassName:"sync-dialog-radio-list",value:i}),o("div",{className:"field",children:[o("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),o(Rn,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:c,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:u?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),o("button",{className:"settings-button","data-primary-action":"true",disabled:!f,onClick:g,type:"button",children:"Combine people"})]})]})}function QP({descriptionId:e,request:t,titleId:n}){const[r,i]=x(t.kind==="input"&&t.initialValue||""),[a,s]=x(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";z(()=>{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"){Pn(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}Pn(m)};return o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:n,children:t.title}),o(Mi,{ariaLabel:`Close ${t.title}`,onClick:()=>Pn(t.kind==="confirm"?!1:null)})]}),o("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?o("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?o("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?o("div",{className:"field",children:[t.suggestions?.length?o(ZE,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:m=>{i(m),a&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):o(Se,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:m=>{i(m.currentTarget.value),a&&s(null)},onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),a?o("div",{className:"sync-field-hint",id:l,children:a}):null]}):null,t.kind==="duplicate-person"?o(XP,{descriptionId:e,request:t}):null]}),o("div",{className:"modal-footer",children:[o("div",{className:"small"}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>Pn(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?o("button",{autoFocus:!0,className:`settings-button ${QE(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function ZP(){const[e,t]=x(JE());z(()=>(Xg(t),()=>{YE(t)&&Xg(null)}),[]);const n=!!e,r=xe(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=xe(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?o(Fr,{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||Pn(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?o(QP,{descriptionId:i,request:e,titleId:r}):null}):null}var lr=null;function gs(){lr?.isConnected||(lr=document.getElementById("syncDialogMount"),lr||(lr=document.createElement("div"),lr.id="syncDialogMount",document.body.appendChild(lr)),Ge(o(ZP,{}),lr))}function Wt(e){return gs(),nd("confirm")?new Promise(t=>{td(n=>t(!!n)),ds({kind:"confirm",...e})}):Promise.resolve(!1)}function ud(e){return gs(),nd("input")?new Promise(t=>{td(n=>t(typeof n=="string"?n:null)),ds({kind:"input",...e})}):Promise.resolve(null)}function eA(e){return gs(),nd("duplicate-person")?new Promise(t=>{td(n=>t(n||{action:"cancel"})),ds({kind:"duplicate-person",...e})}):Promise.resolve(XE({kind:"duplicate-person",...e}))}function tA(e){return e.readiness==="ready"?null:"Space management needs the coordinator URL, target Team, and admin secret before it can list Spaces or change memberships."}function nA(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function Mv(e){const t=String(e.label||"").trim()||"Untitled Space",n=nA(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",a=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Advanced: Space ID ${i} · Membership epoch ${a}`}}function rA(e){const t={active:"Space access active",revoked:"Space access revoked",not_member:"No Space access"},n=e.role.replaceAll("_"," "),r=e.status==="not_member"?t[e.status]:`${t[e.status]} · ${n}`,i=e.membershipEpoch==null?"—":String(e.membershipEpoch);return{statusLabel:t[e.status],detail:r,advancedDetail:`Advanced: membership epoch ${i}`}}function iA(e,t,n){return`Revoke ${t||n||"this device"} from ${Mv(e).title}?`}function aA(e,t){const n=new Map(t.map(r=>[String(r.device_id||"").trim(),r]).filter(([r])=>r.length>0));return e.map(r=>{const i=String(r.device_id||"").trim();if(!i)return null;const a=n.get(i),s=String(a?.status||"").trim(),c=a?s==="revoked"?"revoked":"active":"not_member",l=typeof a?.membership_epoch=="number"&&Number.isFinite(a.membership_epoch)?Math.trunc(a.membership_epoch):null;return{deviceId:i,displayName:String(r.display_name||i||"Unnamed device"),enabled:r.enabled!==!1&&r.enabled!==0,status:c,role:String(a?.role||"member"),membershipEpoch:l,updatedAt:a?.updated_at?String(a.updated_at):null}}).filter(r=>r!==null).sort((r,i)=>{const a={active:0,revoked:1,not_member:2};return a[r.status]-a[i.status]||r.displayName.localeCompare(i.displayName)})}function oA(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(a=>String(a.group_id||"").trim()===i)}function sA(){return{loaded:!1,loading:!1,error:"",includeInactive:!1,devicesLoaded:!1,scopes:[],membersByScope:new Map,devices:[],createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}}function pd(e){if(!e||typeof e!="object")return[];const t=e.items;return Array.isArray(t)?t:[]}function dt(e){let t=q.groupScopeManagementDrafts.get(e);return t||(t=sA(),q.groupScopeManagementDrafts.set(e,t)),t}function wt(e,t){q.groupScopeManagementDrafts.set(e,t)}async function ni(e,t,n=dt(e).includeInactive){wt(e,{...dt(e),loading:!0,error:"",includeInactive:n}),t();try{const[r,i]=await Promise.all([Ow(e,n),_p(e,!0)]),a=pd(r),s=pd(i),c=await Promise.all(a.map(async l=>{const d=String(l.scope_id||"").trim();return d?[d,pd(await Fw(e,d,!0))]:[d,[]]}));wt(e,{...dt(e),loaded:!0,loading:!1,error:"",includeInactive:n,devicesLoaded:!0,scopes:a,devices:s,membersByScope:new Map(c.filter(([l])=>l.length>0)),actionPendingKey:"",actionPendingKind:""})}catch(r){wt(e,{...dt(e),loaded:!0,loading:!1,error:r instanceof Error?r.message:"Failed to load Spaces."})}t()}function md(e,t){q.groupScopeManagementOpen.add(e),dt(e),t(),ni(e,t)}function Ov(e,t){q.groupScopeManagementOpen.delete(e),q.groupScopeManagementDrafts.delete(e),t()}async function cA(e,t){const n=dt(e);if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),a=n.createKind.trim()||"team";if(!r||!i){se("Enter a Space id and label before creating a Space.","warning");return}wt(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await jw(e,{scope_id:r,label:i,kind:a});const s=dt(e);wt(e,{...s,createScopeId:"",createLabel:"",createKind:"team",actionPendingKey:"",actionPendingKind:""}),se("Space created. Grant devices explicitly before data can sync."),await ni(e,t,s.includeInactive)}catch(s){wt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to create Space."}),t()}}async function lA(e,t,n,r){const i=dt(e),a=`grant:${t}:${n}`;if(!i.actionPendingKey){wt(e,{...i,actionPendingKey:a,actionPendingKind:"grant",error:""}),r();try{await Bw(e,t,{device_id:n,role:"member"}),se("Device granted access to the Space."),await ni(e,r,i.includeInactive)}catch(s){wt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:s instanceof Error?s.message:"Failed to grant Space access."}),r()}}}async function dA(e,t,n,r,i){const a=String(t.scope_id||"").trim();if(!a||!await Wt({title:iA(t,r,n),description:"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.",confirmLabel:"Revoke membership",cancelLabel:"Keep membership",tone:"danger"}))return;const s=dt(e),c=`revoke:${a}:${n}`;if(!s.actionPendingKey){wt(e,{...s,actionPendingKey:c,actionPendingKind:"revoke",error:""}),i();try{await Uw(e,a,n),se("Space access revoked. Future sync is blocked for that device."),await ni(e,i,s.includeInactive)}catch(l){wt(e,{...dt(e),actionPendingKey:"",actionPendingKind:"",error:l instanceof Error?l.message:"Failed to revoke Space access."}),i()}}}function uA(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=aA(oA(n.devices,w.lastCoordinatorAdminDevices,e,n.devicesLoaded),n.membersByScope.get(a)??[]);return s.length?y("div",{class:"coordinator-admin-scope-member-list"},s.map(c=>{const l=`${n.actionPendingKind}:${a}:${c.deviceId}`,d=n.actionPendingKey===l,u=c.enabled&&c.status!=="active",p=c.status==="active",m=rA(c);return y("div",{class:"coordinator-admin-scope-member-row",key:c.deviceId},y("div",{class:"coordinator-admin-scope-member-copy"},y("strong",null,c.displayName),y("span",null,m.detail),y("span",{class:"peer-meta"},m.advancedDetail),c.enabled?null:y("span",null,"Device is disabled in this Team.")),y("div",{class:"peer-actions"},u?y("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{lA(e,a,c.deviceId,i)},type:"button"},d&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,p?y("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{dA(e,t,c.deviceId,c.displayName,i)},type:"button"},d&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):y("div",{class:"peer-submeta coordinator-admin-empty-state"},"No enrolled devices in this Team yet. Enroll a device before granting this Space.")}function pA(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=Mv(t);return y("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:a||s.title},y("div",{class:"peer-title"},y("strong",null,s.title)),y("div",{class:"peer-submeta"},s.summary),y("div",{class:"peer-meta"},s.advancedDetail),y("div",{class:"peer-submeta"},"Devices below are enrolled in the Team; only active Space members can sync this data boundary."),uA(e,t,n,r,i))}function mA(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,a=q.groupScopeManagementDrafts.get(t);if(!a)return null;const s=tA(r);if(s)return y("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(!a.loaded)return y("div",{class:"peer-submeta"},"Loading Spaces…");const c=!n||!!a.actionPendingKey||a.loading;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),y("div",{class:"peer-submeta"},"Teams discover and enroll devices. Spaces grant data access. Granting a device here is explicit; Team membership alone does not share memories."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),y(Zr,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:a.includeInactive,className:"coordinator-admin-switch",disabled:c,onCheckedChange:l=>{ni(t,i,l)},thumbClassName:"coordinator-admin-switch-thumb"})),y("form",{class:"coordinator-admin-form",onSubmit:l=>{l.preventDefault(),!c&&cA(t,i)}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Space id"),y(Se,{class:"peer-scope-input",disabled:c,onInput:l=>{wt(t,{...dt(t),createScopeId:String(l.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:a.createScopeId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Label"),y(Se,{class:"peer-scope-input",disabled:c,onInput:l=>{wt(t,{...dt(t),createLabel:String(l.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:a.createLabel})),y("label",{class:"coordinator-admin-field"},y("span",null,"Kind"),y(Se,{class:"peer-scope-input",disabled:c,onInput:l=>{wt(t,{...dt(t),createKind:String(l.currentTarget.value||"")})},placeholder:"team",type:"text",value:a.createKind}))),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:c,type:"submit"},a.actionPendingKind==="create"?"Creating…":"Create Space"),y("button",{class:"settings-button",disabled:c,onClick:()=>{ni(t,i,a.includeInactive)},type:"button"},a.loading?"Refreshing…":"Refresh"))),a.error?y("div",{class:"peer-submeta coordinator-admin-error"},a.error):null,a.scopes.length?y("div",{class:"coordinator-admin-scope-card-list"},a.scopes.map(l=>pA(t,l,a,n,i))):y("div",{class:"peer-meta coordinator-admin-empty-state"},"No Spaces are defined for this Team yet. Create a Space, then grant specific devices. Projects stay local-only until assigned to a Space."))}function jv(){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 fA(){return{projects_include:[],projects_exclude:[],auto_seed_scope:!0,default_space_scope_id:"",auto_grant_default_space_on_join:!1,loaded:!1,saving:!1,error:""}}async function fd(e,t){const n=fA();q.groupPreferencesDrafts.set(e,n),q.groupPreferencesOpen.add(e),t();try{const r=await FS(e);q.groupPreferencesDrafts.set(e,{projects_include:Array.isArray(r.projects_include)?[...r.projects_include]:[],projects_exclude:Array.isArray(r.projects_exclude)?[...r.projects_exclude]:[],auto_seed_scope:r.auto_seed_scope,default_space_scope_id:r.default_space_scope_id||"",auto_grant_default_space_on_join:r.auto_grant_default_space_on_join===!0,loaded:!0,saving:!1,error:""})}catch(r){q.groupPreferencesDrafts.set(e,{...n,loaded:!0,error:r instanceof Error?r.message:"Failed to load preferences."})}t()}function vs(e,t){q.groupPreferencesOpen.delete(e),q.groupPreferencesDrafts.delete(e),t()}async function hA(e,t){const n=q.groupPreferencesDrafts.get(e);if(!n||n.saving)return;const r={projects_include:n.projects_include.length>0?[...n.projects_include]:null,projects_exclude:n.projects_exclude.length>0?[...n.projects_exclude]:null,auto_seed_scope:n.auto_seed_scope,default_space_scope_id:n.default_space_scope_id||null,auto_grant_default_space_on_join:n.auto_grant_default_space_on_join};q.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await BS(e,r),se("Team defaults saved. New devices use these filters and Space settings."),vs(e,t)}catch(i){const a=q.groupPreferencesDrafts.get(e);if(!a)return;q.groupPreferencesDrafts.set(e,{...a,saving:!1,error:i instanceof Error?i.message:"Failed to save preferences."}),t()}}function gA(e,t,n){const r=q.groupPreferencesDrafts.get(e);if(!r)return null;if(!r.loaded)return y("div",{class:"peer-submeta"},"Loading project defaults…");const i=`coord-admin-scope-autoseed-${e}`,a=`coord-admin-default-space-autogrant-${e}`,s=`coord-admin-scope-include-${e}`,c=`coord-admin-scope-exclude-${e}`,l=!n||r.saving||!r.auto_seed_scope;return y(Z,null,y("h4",{class:"coordinator-admin-drawer-title"},"Team defaults"),y("div",{class:"peer-submeta"},"Space access grants decide what new devices can sync. Advanced sharing rules only narrow future writes after Space access already exists."),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:i},"Auto-apply advanced rules to new devices"),y(Zr,{"aria-labelledby":i,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!n||r.saving,onCheckedChange:d=>{const u=q.groupPreferencesDrafts.get(e)??r;q.groupPreferencesDrafts.set(e,{...u,auto_seed_scope:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:a},"Auto-grant default Space on join"),y(Zr,{"aria-labelledby":a,checked:r.auto_grant_default_space_on_join,className:"coordinator-admin-switch",disabled:!n||r.saving||!r.default_space_scope_id,onCheckedChange:d=>{const u=q.groupPreferencesDrafts.get(e)??r;q.groupPreferencesDrafts.set(e,{...u,auto_grant_default_space_on_join:d}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?y("div",{class:"peer-submeta"},"Default Space configured."):y("div",{class:"peer-submeta"},"No default Space has been created yet."),y("div",{class:"coordinator-admin-field"},y("span",{id:s},"Include template"),y(qg,{"aria-labelledby":s,availableProjects:q.availableProjects,disabled:l,emptyLabel:"All projects allowed.",onValuesChange:d=>{const u=q.groupPreferencesDrafts.get(e)??r;q.groupPreferencesDrafts.set(e,{...u,projects_include:d}),t()},placeholder:"Add project",values:r.projects_include}),y("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),y("div",{class:"coordinator-admin-field"},y("span",{id:c},"Exclude template"),y(qg,{"aria-labelledby":c,availableProjects:q.availableProjects,disabled:l,emptyLabel:"Nothing excluded.",onValuesChange:d=>{const u=q.groupPreferencesDrafts.get(e)??r;q.groupPreferencesDrafts.set(e,{...u,projects_exclude:d}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?y("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!n||r.saving,onClick:()=>{hA(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),y("button",{class:"settings-button",disabled:r.saving,onClick:()=>vs(e,t),type:"button"},"Cancel")))}function vA(e){const t=q.teamSetupGuide;if(!t)return null;const n=t.displayName||t.groupId,r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return y("div",{class:"peer-meta coordinator-admin-empty-state"},y("h4",{class:"coordinator-admin-drawer-title"},`Set up ${n}`),y("div",{class:"peer-submeta"},"A Team organizes people and devices. The default Space is the memory boundary; Team membership only grants data access when default Space auto-grant is enabled."),t.setupWarning?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`Team created, but ${r} failed. Automatic repair is not available yet; use Spaces to inspect or create access manually before inviting teammates.`):y("div",{class:"peer-submeta"},t.defaultSpaceScopeId?t.defaultSpaceLabel?`Default Space ready: ${t.defaultSpaceLabel}. New devices can receive this Space when auto-grant is enabled.`:"Default Space ready. New devices can receive this Space when auto-grant is enabled.":"Default Space status is unknown. Check Spaces before inviting teammates."),y("ol",{class:"peer-submeta"},y("li",null,"Review Team defaults and the auto-grant default Space setting."),y("li",null,"Invite teammates or other devices."),y("li",null,"Assign projects to Spaces from the Projects tab.")),y("div",{class:"peer-actions"},y("button",{class:"settings-button",onClick:()=>{q.groupPreferencesOpen.add(t.groupId),fd(t.groupId,e)},type:"button"},"Review Team defaults"),y("button",{class:"settings-button",onClick:()=>{md(t.groupId,e)},type:"button"},"Check Spaces"),y("button",{class:"settings-button",onClick:()=>{q.inviteGroup=t.groupId,q.activeSection="invites",e()},type:"button"},"Invite devices"),y("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Assign projects"),y("button",{class:"settings-button",onClick:()=>{q.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function yA(e,t){return t?e?"Restoring…":"Archiving…":e?"Unarchive":"Archive"}function bA(e){const{summary:t,createGroup:n,runGroup:r,renderShell:i,reloadData:a}=e,s=String(w.lastCoordinatorAdminStatus?.active_group||"").trim(),c=or(),l=ei(),d=l.filter(g=>!g.archived_at),u=l.filter(g=>g.archived_at),p=q.showArchivedGroups?l:d,m=c?l.some(g=>g.group_id===c):!1,f=[`${d.length} active`];return u.length&&f.push(`${u.length} archived`),y(rr,{className:"coordinator-admin-panel",value:"groups"},y("h3",null,"Teams"),y("p",{class:"peer-submeta"},c?`Managing ${c}${s&&s!==c?` · this node uses ${s} for discovery`:""}`:s?`This node uses ${s} for discovery. Select a Team below to manage it.`:"No Team selected yet. Create one or select an existing Team to manage."),l.length?y("p",{class:"peer-submeta"},f.join(" · ")):null,!m&&c?y("div",{class:"peer-meta coordinator-admin-inline-warning"},`The selected Team (${c}) is configured locally but does not exist in the coordinator yet. Create it below or switch to another Team once one exists.`):null,vA(i),(()=>{const g=t.readiness!=="ready"||q.groupActionPendingKind==="create";return y("form",{class:"coordinator-admin-form",onSubmit:h=>{h.preventDefault(),!g&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"New Team id"),y(Se,{class:"peer-scope-input",disabled:g,onInput:h=>{q.createGroupId=String(h.currentTarget.value||"")},placeholder:"team-alpha",type:"text",value:q.createGroupId})),y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Se,{class:"peer-scope-input",disabled:g,onInput:h=>{q.createGroupDisplayName=String(h.currentTarget.value||"")},placeholder:"Team Alpha",type:"text",value:q.createGroupDisplayName}))),y("div",{class:"section-actions coordinator-admin-groups-toolbar"},y("div",{class:"coordinator-admin-primary-actions"},y("button",{class:"settings-button",disabled:g,type:"submit"},q.groupActionPendingKind==="create"?"Creating…":"Create Team")),y("div",{class:"coordinator-admin-secondary-actions"},y("label",{class:"coordinator-admin-inline-filter"},y("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),y(Zr,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:q.showArchivedGroups,className:"coordinator-admin-switch",disabled:t.readiness!=="ready",onCheckedChange:h=>{q.showArchivedGroups=h,i()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),p.length?y("div",{class:"peer-list"},p.map(g=>{const h=g.group_id===c,v=q.groupActionPendingId===g.group_id,b=!!g.archived_at,_=q.groupRenameDrafts.get(g.group_id)??g.display_name??g.group_id,S=q.groupPreferencesOpen.has(g.group_id),C=q.groupScopeManagementOpen.has(g.group_id),N=b?"unarchive":"archive",E=yA(b,v&&q.groupActionPendingKind===N),A=zE({groupId:g.group_id,preferences:q.groupPreferencesDrafts.get(g.group_id),scopeManagement:q.groupScopeManagementDrafts.get(g.group_id),setupGuide:q.teamSetupGuide});return y("div",{class:"peer-card peer-card--padded",key:g.group_id},y("div",{class:"peer-title"},y("strong",null,_)),y("div",{class:"peer-submeta"},b?"Archived Team":"Active Team"),y("div",{class:"peer-meta"},`Advanced: Team ID ${g.group_id}`),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Default Space"),y("strong",null,A.defaultSpace)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Auto-grant"),y("strong",null,A.autoGrant)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Spaces"),y("strong",null,A.spaces))),s===g.group_id?y("div",{class:"peer-submeta"},"This node uses this Team for coordinator-backed discovery."):null,y("label",{class:"coordinator-admin-field"},y("span",null,"Display name"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready"||v,onInput:M=>{q.groupRenameDrafts.set(g.group_id,String(M.currentTarget.value||""))},type:"text",value:_})),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:t.readiness!=="ready"||h,onClick:()=>{Ql(g.group_id),a()},type:"button"},h?"Managing":"Manage Team"),y("button",{class:"settings-button",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,_,"rename"),type:"button"},v&&q.groupActionPendingKind==="rename"?"Renaming…":"Rename"),y("button",{"aria-expanded":S,"aria-controls":`coord-admin-project-defaults-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":S?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{S?vs(g.group_id,i):fd(g.group_id,i)},type:"button"},y("span",null,"Team defaults"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(jv,null))),y("button",{"aria-expanded":C,"aria-controls":`coord-admin-spaces-drawer-${g.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":C?"open":"closed",disabled:t.readiness!=="ready"||v,onClick:()=>{C?Ov(g.group_id,i):md(g.group_id,i)},type:"button"},y("span",null,"Spaces & access"),y("span",{"aria-hidden":"true",class:"device-row-chevron"},y(jv,null))),y("button",{class:b?"settings-button":"settings-button danger",disabled:t.readiness!=="ready"||v,onClick:()=>r(g.group_id,g.display_name||g.group_id,N),type:"button"},E)),y(Wo,{open:S,onOpenChange:M=>{M?fd(g.group_id,i):vs(g.group_id,i)}},y(zo,{"aria-label":`Project defaults for ${_}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${g.group_id}`},S?gA(g.group_id,i,t.readiness==="ready"):null)),y(Wo,{open:C,onOpenChange:M=>{M?md(g.group_id,i):Ov(g.group_id,i)}},y(zo,{"aria-label":`Spaces for ${_}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${g.group_id}`},C?mA({groupId:g.group_id,ready:t.readiness==="ready",renderShell:i,summary:t}):null)))})):y("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?q.showArchivedGroups?"No Teams are available yet.":"No active Teams yet. Create one to get started.":"Team browsing will appear here once setup is complete."))}function ri(e){return o("textarea",{...e})}function _A(e){const{summary:t,createInvite:n,renderShell:r}=e,i=w.lastCoordinatorAdminStatus,a=or()||String(i?.active_group||"").trim(),s=q.inviteGroup.trim()||a,c=String(w.lastTeamInvite?.encoded||"").trim(),l=Array.isArray(w.lastTeamInvite?.warnings)?w.lastTeamInvite?.warnings:[],d=t.readiness!=="ready"||q.invitePending;return y(rr,{className:"coordinator-admin-panel",value:"invites"},y("h3",null,"Legacy Team invites"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Legacy Team invites enroll a device in the selected Team. They do not grant project access; share projects from Projects instead.":"Finish setup first. Invite creation stays disabled until the local Teams configuration is ready."),y("form",{class:"coordinator-admin-form",onSubmit:u=>{u.preventDefault(),!d&&n()}},y("div",{class:"coordinator-admin-form-grid"},y("label",{class:"coordinator-admin-field"},y("span",null,"Team"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready",onInput:u=>{q.inviteGroup=String(u.currentTarget.value||""),r()},placeholder:a||"team-alpha",type:"text",value:q.inviteGroup})),y("label",{class:"coordinator-admin-field"},y("span",null,"Join policy"),y(Rn,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:t.readiness!=="ready",id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:u=>{q.invitePolicy=u==="approval_required"?"approval_required":"auto_admit",r()},options:[{value:"auto_admit",label:"Auto-admit to Team"},{value:"approval_required",label:"Require approval to join Team"}],triggerClassName:"sync-radix-select-trigger sync-actor-select",value:q.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),y("label",{class:"coordinator-admin-field"},y("span",null,"Expires in (hours)"),y(Se,{class:"peer-scope-input",disabled:t.readiness!=="ready",min:"1",onInput:u=>{q.inviteTtlHours=String(u.currentTarget.value||"")},type:"number",value:q.inviteTtlHours}))),y("div",{class:"section-actions"},y("button",{class:"settings-button",disabled:d,type:"submit"},q.invitePending?"Creating…":"Create legacy Team invite"),s?y("span",{class:"peer-submeta"},`Using Team ${s}`):null)),c?y("label",{class:"coordinator-admin-field"},y("span",null,"Generated invite"),y(ri,{class:"feed-search coordinator-admin-output",readOnly:!0,value:c}),y("button",{class:"settings-button sync-action-copy",type:"button",onClick:u=>Yi(c,u.currentTarget)},"Copy")):null,l?.length?y("div",{class:"peer-meta coordinator-admin-warning-list"},l.join(" · ")):null,y("h3",null,"Project sharing operations"),y("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),w.lastShareOperations.length>0?y("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...w.lastShareOperations.map(u=>y("li",{key:u.operation_id},y("strong",null,u.person.display_name),y("span",null,` — ${u.projects.map(p=>p.display_name).join(", ")} — ${u.lifecycle.label}`)))):y("div",{class:"peer-meta"},"No project sharing operations yet."))}function wA(e){const{summary:t,reviewJoinRequest:n}=e,r=Array.isArray(w.lastCoordinatorAdminJoinRequests)?w.lastCoordinatorAdminJoinRequests:[];return y(rr,{className:"coordinator-admin-panel",value:"join-requests"},y("h3",null,"Pending join requests"),y("p",{class:"peer-submeta"},t.readiness==="ready"?"Approve or deny devices that want to join this Team. Default Space access is handled by Team defaults and can be reviewed in Spaces.":"Finish setup first. Join request review stays disabled until Teams is ready."),r.length?y("div",{class:"peer-list"},r.map(i=>{const a=String(i.request_id||"").trim(),s=String(i.device_id||"unknown-device"),c=String(i.display_name||s).trim()||s,l=String(i.fingerprint||"").trim(),d=[`Device ID ${s}`];l&&d.push(`Fingerprint ${l}`);const u=q.joinReviewPendingId===a;return y("div",{class:"peer-card peer-card--padded",key:a||s},y("div",{class:"peer-title"},y("strong",null,c)),y("div",{class:"peer-meta"},`Advanced: ${d.join(" · ")}`),y("div",{class:"peer-actions"},y("button",{class:"settings-button",disabled:!a||u,onClick:()=>n(a,"approve"),type:"button"},u&&q.joinReviewPendingAction==="approve"?"Approving…":"Approve"),y("button",{class:"settings-button danger",disabled:!a||u,onClick:()=>n(a,"deny"),type:"button"},u&&q.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):y("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."))}function SA(e){const{renderShell:t,reloadData:n}=e;async function r(){if(q.groupActionPendingKind)return;const l=q.createGroupId.trim();if(!l){se("Enter a Team id before creating a Team.","warning");return}const d=q.createGroupDisplayName.trim();q.groupActionPendingKind="create",t();try{const u=await Dw({group_id:l,display_name:d||null}),p=u.default_space,m=(p&&"scope"in p?p.scope:p)??{},f=p&&"preferences"in p?p.preferences:null,g=String(m?.scope_id||"");q.createGroupId="",q.createGroupDisplayName="",q.teamSetupGuide={groupId:l,displayName:String(u.group?.display_name||d||l),defaultSpaceScopeId:g,defaultSpaceLabel:String(m?.label||""),autoGrantDefaultSpaceOnJoin:typeof f?.auto_grant_default_space_on_join=="boolean"?f.auto_grant_default_space_on_join:null,setupWarning:u.setup_warning||null},await n(),Ql(l),await n(),u.setup_warning?se("Team created, but default Space setup needs repair.","warning"):g?se("Team created with a default Space.","success"):se("Team created, but default Space status is unknown.","warning")}catch(u){se(u instanceof Error?u.message:"Failed to create Team.","warning")}finally{q.groupActionPendingKind="",t()}}async function i(l,d,u){if(!(!l||q.groupActionPendingId)&&!((u==="archive"||u==="unarchive")&&!await Wt({title:`${u==="archive"?"Archive":"Unarchive"} ${d||l}?`,description:u==="archive"?"Archived Teams stay visible and restorable, but they stop being operational for new invites and joins.":"This Team will become operational again for invites and coordinator-backed joins.",confirmLabel:u==="archive"?"Archive Team":"Unarchive Team",cancelLabel:u==="archive"?"Keep Team active":"Keep Team archived",tone:"danger"}))){q.groupActionPendingId=l,q.groupActionPendingKind=u,t();try{u==="rename"&&(await Lw(l,d),se("Team renamed.","success")),u==="archive"&&(await $w(l),se("Team archived.","success")),u==="unarchive"&&(await Mw(l),se("Team unarchived.","success")),await n()}catch(p){se(p instanceof Error?p.message:`Failed to ${u} Team.`,"warning")}finally{q.groupActionPendingId="",q.groupActionPendingKind="",t()}}}async function a(){if(q.invitePending)return;const l=w.lastCoordinatorAdminStatus,d=or()||String(l?.active_group||"").trim(),u=q.inviteGroup.trim()||d,p=Number(q.inviteTtlHours);if(!u){se("Choose a Team before creating an invite.","warning");return}if(!Number.isFinite(p)||p<1){se("Invite lifetime must be at least 1 hour.","warning");return}q.invitePending=!0,t();try{const m=await wp({group_id:u,policy:q.invitePolicy,ttl_hours:p});w.lastTeamInvite=m,q.inviteGroup=u;const f=Array.isArray(m.warnings)?m.warnings:[];se(f.length?`Invite created. Review ${f.length===1?"the warning":`${f.length} warnings`} before sharing it.`:"Invite created. Copy it from Teams and share it with your teammate.",f.length?"warning":"success")}catch(m){se(m instanceof Error?m.message:"Failed to create invite.","warning")}finally{q.invitePending=!1,t()}}async function s(l,d){if(!q.joinReviewPendingId){q.joinReviewPendingId=l,q.joinReviewPendingAction=d,t();try{const u=await qw(l,d);d==="approve"&&u.setup_warning?se("Join request approved, but default Space access needs repair.","warning"):se(d==="approve"?"Join request approved.":"Join request denied.","success"),await n()}catch(u){se(u instanceof Error?u.message:"Failed to review join request.","warning")}finally{q.joinReviewPendingId="",q.joinReviewPendingAction="",t()}}}async function c(l,d,u,p){if(!(!l||q.deviceActionPendingId)&&!((p==="disable"||p==="remove")&&!await Wt({title:`${p==="disable"?"Disable":"Remove"} ${u||l}?`,description:p==="disable"?"This device will stay enrolled but can no longer participate until you re-enable it.":"This removes the enrolled device record from the coordinator. The teammate would need a fresh invite or re-enrollment path to come back.",confirmLabel:p==="disable"?"Disable device":"Remove device",cancelLabel:p==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))){q.deviceActionPendingId=l,q.deviceActionPendingKind=p,t();try{if(p==="rename"){const m=String(q.deviceRenameDrafts.get(l)||"").trim();if(!m){se("Enter a device name before renaming it.","warning");return}await Hw(l,d,m),se("Device renamed.","success")}p==="disable"&&(await Kw(l,d),se("Device disabled.","success")),p==="enable"&&(await Vw(l,d),se("Device enabled.","success")),p==="remove"&&(await Ww(l,d),se("Device removed.","success")),await n()}catch(m){se(m instanceof Error?m.message:`Failed to ${p} device.`,"warning")}finally{q.deviceActionPendingId="",q.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:r,runGroupAction:i,createInviteFromAdminPanel:a,reviewJoinRequestFromAdminPanel:s,runDeviceAction:c}}function CA(){const e=w.lastCoordinatorAdminStatus;return e?e.readiness==="ready"?{readiness:"ready",title:"Teams is ready",detail:"This viewer can use the local Teams admin configuration to manage invites, join requests, and enrolled devices without exposing the admin secret to the browser."}:e.readiness==="partial"?{readiness:"partial",title:"Teams setup is incomplete",detail:e.has_admin_secret===!1?"Set a coordinator admin secret for the viewer server before using Teams invite and device actions.":"Finish configuring the coordinator target and Team before using Teams actions."}:{readiness:"not_configured",title:"Teams is not configured",detail:"Set a coordinator URL, Team, and admin secret locally to enable remote Teams administration from this viewer."}:{readiness:"partial",title:"Checking Teams readiness…",detail:"Loading local Teams configuration from the viewer server."}}var{createGroupFromAdminPanel:TA,runGroupAction:NA,createInviteFromAdminPanel:IA,reviewJoinRequestFromAdminPanel:kA,runDeviceAction:EA}=SA({renderShell:()=>dr(),reloadData:()=>hd()});function dr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=w.lastCoordinatorAdminStatus,n=CA(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!UE()?.archived_at,c=n.readiness==="ready",l=n.readiness==="ready"&&!s,d=n.readiness==="ready",u=n.readiness==="ready",p=or(),m=ei().filter(b=>!b.archived_at).length,f=ei().filter(b=>b.archived_at).length,g=Array.isArray(w.lastCoordinatorAdminJoinRequests)?w.lastCoordinatorAdminJoinRequests.length:0,h=Array.isArray(w.lastCoordinatorAdminDevices)?w.lastCoordinatorAdminDevices.length:0,v=n.readiness!=="ready"?n.detail:s?"The selected Team is archived. Restore it or switch Teams before creating invites.":"";(q.activeSection==="invites"&&!l||q.activeSection==="groups"&&!c||q.activeSection==="join-requests"&&!d||q.activeSection==="devices"&&!u)&&(q.activeSection=n.readiness==="ready"?"groups":"invites"),Ge(y("div",{class:"coordinator-admin-shell"},y("div",{class:"card coordinator-admin-header"},y("div",{class:"section-header"},y("h2",null,"Teams")),y("div",{class:"coordinator-admin-summary-grid"},y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Team admin target"),y("strong",null,p||"None selected")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Node discovery Team"),y("strong",null,i||"None")),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Teams"),y("strong",null,`${m} active${f?` · ${f} archived`:""}`)),y("div",{class:"coordinator-admin-summary-card"},y("span",{class:"section-meta"},"Selected Team activity"),y("strong",null,`${g} join requests · ${h} devices`))),v?y("div",{class:"peer-meta coordinator-admin-inline-warning"},v):null,r?y("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),y("div",{class:"card coordinator-admin-sections"},y(Kh,{ariaLabel:"Teams sections",listClassName:"coordinator-admin-tabs-list",onValueChange:b=>{q.activeSection=b||"groups",dr()},tabs:[{value:"groups",label:"Teams",disabled:!c},{value:"invites",label:"Invites",disabled:!l},{value:"join-requests",label:"Join requests",disabled:!d},{value:"devices",label:"Devices",disabled:!u}],triggerClassName:"coordinator-admin-tab-trigger",value:q.activeSection},bA({summary:n,createGroup:()=>{TA()},runGroup:(b,_,S)=>{NA(b,_,S)},renderShell:dr,reloadData:()=>{hd()}}),_A({summary:n,createInvite:()=>{IA()},renderShell:dr}),wA({summary:n,reviewJoinRequest:(b,_)=>{kA(b,_)}}),sk({summary:n,runDevice:(b,_,S,C)=>{EA(b,_,S,C)}})),y("div",{class:"section-meta coordinator-admin-context-line"},s?`Selected Team ${p||"—"} is archived. Switch or restore it to enable invite operations.`:p?`Actions below apply to ${p}.`:"Select a Team to start managing people, Spaces, and access."))),e)}function PA(){dr()}async function hd(){try{w.lastCoordinatorAdminStatus=await Qa()}catch{w.lastCoordinatorAdminStatus=null,w.lastCoordinatorAdminJoinRequests=[],w.lastCoordinatorAdminDevices=[],q.deviceRenameDrafts.clear(),q.deviceRenameServerNames.clear(),dr();return}const e=String(w.lastCoordinatorAdminStatus?.active_group||"").trim();if(Yg(),w.lastCoordinatorAdminStatus?.readiness==="ready"){try{const n=await Fp();w.lastShareOperations=Array.isArray(n.items)?n.items:[]}catch{}try{const n=await bp(q.showArchivedGroups);w.lastCoordinatorAdminGroups=Array.isArray(n?.items)?n.items:[],BE(),Yg()}catch{w.lastCoordinatorAdminGroups=[],q.groupRenameDrafts.clear()}const t=or();try{const n=await Gw(t||e);w.lastCoordinatorAdminJoinRequests=Array.isArray(n?.items)?n.items:[]}catch{w.lastCoordinatorAdminJoinRequests=[]}try{const n=await _p(t||e,!0);w.lastCoordinatorAdminDevices=Array.isArray(n?.items)?n.items:[],GE()}catch{w.lastCoordinatorAdminDevices=[]}try{q.availableProjects=await Za()}catch{q.availableProjects=[]}}else w.lastCoordinatorAdminGroups=[],q.groupRenameDrafts.clear(),w.lastCoordinatorAdminJoinRequests=[],w.lastCoordinatorAdminDevices=[],q.deviceRenameDrafts.clear(),q.deviceRenameServerNames.clear();dr()}function gd(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var vd=new WeakMap,Fv={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},AA={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},xA={available:"Available",offline:"Offline",unknown:"Availability unknown"};function RA(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function DA(e,t){return t.get(e)??AA}function LA(e){return e.reduce((t,n)=>!t||Fv[n.state]>Fv[t.state]?n:t,null)}function $A(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 MA(e,t,n,r,i=[]){const a=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&a.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),m=RA(e.projectRecipients.filter(S=>S.status==="active"&&S.recipientKind==="identity"&&S.identityId===u.identityId).map(S=>S.canonicalProjectIdentity)),f=S=>{const C=s.get(S);if(!C)return null;const N=DA(S,d);return{canonicalProjectIdentity:S,displayName:C,state:N.state,statusLabel:N.label,statusCopy:N.explanation,deliveredCopiesMayRemain:N.deliveredCopiesMayRemain}},g=m.flatMap(S=>{const C=f(S);return C?[C]:[]}),h=[],v=[...g,...h],b=LA(v),_=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:a.get(u.identityId)??"Identity unavailable",availability:_,availabilityLabel:xA[_],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:g,inheritedProjects:h,unavailableProjectCount:m.length-g.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:v.some(S=>S.deliveredCopiesMayRemain),action:$A(_,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"&&a.has(u.identityId)).length}}function Bv({empty:e,projects:t}){return t.length===0?o("p",{className:"small",children:e}):o("ul",{children:t.map(n=>o("li",{children:[o("strong",{children:n.displayName}),o("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function sa(e){if(!(e instanceof yc))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 ys(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:ca(e)}}function ca(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 bs(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(a=>{const s=n.find(l=>l.deviceId===a.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===a.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var Uv="devices-commit-status";function mn(e){const t=document.getElementById(Uv);t&&(t.textContent=e)}function OA({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter(R=>R.status==="active"&&R.mergedIntoIdentityId===null),a=new Map(i.map(R=>[R.identityId,R.displayName])),s=new Set(a.keys()),[c,l]=x(()=>Object.fromEntries(n.map(R=>[R.deviceId,ys(R,s)]))),[d,u]=x(null),[p,m]=x(!1),[f,g]=x(!1),[h,v]=x(""),b=G(null),_=G(0),S=r.previewBindings??Lp,C=r.commitBindings??$p,N=gd(r),E=d!==null&&bs(d.preview,d.request,n,"bind"),A=xe(()=>n.filter(R=>R.state==="setup_required"&&c[R.deviceId]?.selected),[c,n]),M=JSON.stringify({items:t.items.map(ca),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),U=i.map(R=>`${R.identityId}:${R.displayName}`).sort().join("|");z(()=>{d&&b.current?.focus()},[d]),z(()=>{_.current+=1,g(!1),l(R=>Object.fromEntries(n.map(P=>{const I=R[P.deviceId];if(!I)return[P.deviceId,ys(P,s)];if(P.state!=="setup_required")return[P.deviceId,ys(P,s)];const D=I.targetIdentityId!==""&&s.has(I.targetIdentityId);return I.itemSignature===ca(P)&&D?[P.deviceId,I]:I.explicit&&D?[P.deviceId,{...I,selected:!1,itemSignature:ca(P)}]:[P.deviceId,ys(P,s)]}))),u(null),m(!1)},[M,U]);const k=(R,P)=>{_.current+=1,g(!1),l(I=>({...I,[R]:{...I[R],...P}})),u(null),m(!1),v(""),mn("")},F=R=>({bindings:R.map(P=>{const I=c[P.deviceId];return{deviceId:P.deviceId,targetIdentityId:I?.targetIdentityId??"",confirmed:!0}})}),j=async R=>{if(N){v("Refresh Devices before reviewing Identity setup.");return}if(R.some(D=>D.state!=="setup_required")){v("Only devices that require Identity setup can be reviewed here.");return}const P=R.find(D=>xo(t,D).blocked);if(P){v(xo(t,P).recovery??"Identity setup is unavailable.");return}if(R.length===0||R.some(D=>!c[D.deviceId]?.targetIdentityId)){v("Choose an Identity for every selected device before review.");return}g(!0),v(""),mn("");const I=_.current;try{const D=F(R),O=await S(D);I===_.current&&(bs(O,D,R,"bind")?u({preview:O,request:D}):v("Identity setup preview was incomplete. Refresh and try again."))}catch(D){I===_.current&&v(sa(D))}I===_.current&&g(!1)},H=async()=>{if(!(!d||!p||N||!E)){g(!0),v("");try{await C({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),m(!1),mn("Identity setup completed.");const R=await r.onCommitted?.();mn(R===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":R===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch(R){v(sa(R))}g(!1)}},L=n.filter(R=>R.state==="setup_required");return n.length===0?null:o(Z,{children:[h?o("p",{role:"alert",children:h}):null,L.length>1?o("div",{className:"device-identity-setup-summary",children:[o("strong",{children:[L.length.toLocaleString()," devices need Identity setup"]}),o("button",{className:"settings-button",disabled:f||N||A.length===0,onClick:()=>{j(A)},type:"button",children:["Review ",A.length.toLocaleString()," selected"]})]}):null,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map((R,P)=>{const I=c[R.deviceId],D=xo(t,R),O=D.blocked||N,W=`device-inventory-title-${P}`;return o("li",{children:o("article",{"aria-labelledby":W,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${R.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:W,children:[R.displayName,R.isLocal?" (this device)":""]}),o("span",{className:"badge actor-badge",children:R.state==="setup_required"?"Setup required":R.state==="pairing_required"?"Pairing required":R.state==="conflicted"?"Review required":"Configured"})]}),R.state==="setup_required"?o(Z,{children:[o("fieldset",{children:[o("legend",{children:"Assign an existing Identity"}),i.length===0?o("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,L.length>1?o("label",{children:[o("input",{"aria-label":`Select for setup: ${R.displayName}`,checked:I?.selected??!1,disabled:O,onInput:ue=>k(R.deviceId,{selected:ue.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,o("label",{htmlFor:`${W}-identity`,children:"Identity"}),o("select",{"aria-label":`Choose an Identity for ${R.displayName}`,disabled:O,id:`${W}-identity`,onInput:ue=>k(R.deviceId,{targetIdentityId:ue.currentTarget.value,explicit:!0}),value:I?.targetIdentityId??"",children:[o("option",{value:"",children:"Choose Identity…"}),i.map(ue=>o("option",{value:ue.identityId,children:ue.displayName},ue.identityId))]}),R.suggestedIdentityId&&a.has(R.suggestedIdentityId)?o("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,D.recovery?o("p",{className:"small",children:D.recovery}):null]}),o("div",{className:"device-identity-card-actions",children:[i.length===0?o("button",{"aria-label":`Open Identity administration for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,o("button",{"aria-label":`Review this device: ${R.displayName}`,className:"settings-button",disabled:f||O||!I?.targetIdentityId,onClick:()=>{j([R])},type:"button",children:"Review this device"})]})]}):R.state==="pairing_required"?o(Z,{children:[o("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Go to pairing for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):R.state==="conflicted"?o(Z,{children:[o("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Open Advanced review for ${R.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},R.deviceId)})}),d?o("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[o("h3",{id:"device-identity-review-heading",ref:b,tabIndex:-1,children:"Review Identity setup"}),o("ul",{children:d.preview.outcomes.map(R=>o("li",{children:[o("strong",{children:[R.displayName,":"]})," ",R.previousIdentityId?a.get(R.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",a.get(R.targetIdentityId)??"Unavailable Identity"]},R.deviceId))}),o("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:p,disabled:N,onInput:R=>m(R.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),o("div",{className:"peer-actions",children:[o("button",{className:"settings-button",disabled:f,onClick:()=>{u(null),m(!1)},type:"button",children:"Back"}),o("button",{className:"settings-button sync-dialog-confirm",disabled:f||N||!p||!E,onClick:()=>{H()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function Gv({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const a=e.identities.filter(R=>R.status==="active"&&R.mergedIntoIdentityId===null&&R.identityId!==n.identityId),[s,c]=x(!1),[l,d]=x(""),[u,p]=x(!1),[m,f]=x(null),[g,h]=x(!1),[v,b]=x(!1),[_,S]=x(""),C=G(0),N=i,E=new Map(e.identities.map(R=>[R.identityId,R.displayName])),A=m?.preview.status==="ready"&&m.preview.outcomes.length===1?m.preview.outcomes[0]:null,M=m!==null&&bs(m.preview,m.request,[n],"rebind"),U=xo(t,n),k=U.blocked||gd(r),F=`configured-rebind-trigger-${n.deviceId}`,j=a.find(R=>R.identityId===l)?.displayName??"";z(()=>{C.current+=1,b(!1),l&&!a.some(R=>R.identityId===l)&&(d(""),p(!1)),f(null),h(!1)},[a.map(R=>R.identityId).sort().join("|"),ca(n)]);const H=async()=>{if(k){S(U.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){S("Choose a target Identity and confirm the reassignment before review.");return}b(!0),S(""),mn("");const R=C.current;try{const P={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},I=await(r.previewBindings??Lp)(P);R===C.current&&(I.status!=="ready"?S(sa(new yc(409,I.errorCode??"binding_preview_unavailable",I))):bs(I,P,[n],"rebind")?f({preview:I,request:P}):S("Identity reassignment preview was incomplete. Refresh and try again."))}catch(P){R===C.current&&S(sa(P))}R===C.current&&b(!1)},L=async()=>{if(!(!m||!g||k||!M)){b(!0),S("");try{await(r.commitBindings??$p)({...m.request,reviewedInventoryDigest:m.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),f(null),h(!1),mn("Identity reassignment completed.");const R=await r.onCommitted?.();mn(R===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":R===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(F)??document.getElementById("devices-heading"))?.focus()}catch(R){S(sa(R))}b(!1)}};return o("div",{className:"device-identity-rebind",children:[o("button",{"aria-expanded":s,className:"settings-button",disabled:k,id:F,onClick:()=>{C.current+=1,b(!1),c(!s),f(null),h(!1),S(""),mn("")},type:"button",children:"Change Identity…"}),U.recovery?o("p",{className:"small",children:U.recovery}):null,s?o("fieldset",{children:[o("legend",{children:"Reassign this configured device"}),o("p",{children:[o("strong",{children:"Suggested current Identity (unconfirmed):"})," ",N]}),o("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),o("select",{disabled:k,id:`configured-rebind-${n.deviceId}`,onInput:R=>{C.current+=1,b(!1),d(R.currentTarget.value),p(!1),f(null),h(!1)},value:l,children:[o("option",{value:"",children:"Choose a different Identity…"}),a.map(R=>o("option",{value:R.identityId,children:R.displayName},R.identityId))]}),o("label",{children:[o("input",{checked:u,disabled:k||!l,onInput:R=>{C.current+=1,b(!1),p(R.currentTarget.checked),f(null),h(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",j||"the selected Identity"]}),o("button",{className:"settings-button",disabled:v||k,onClick:()=>{H()},type:"button",children:"Review reassignment"}),m?o("div",{className:"device-identity-rebind-review",children:[o("h4",{children:"Review reassignment"}),o("p",{children:[A?.displayName,":"," ",A?.previousIdentityId?E.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",E.get(A?.targetIdentityId??"")??"Unavailable Identity"]}),o("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:g,disabled:k,onInput:R=>h(R.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),o("button",{className:"settings-button sync-dialog-confirm",disabled:v||k||!g||!M,onClick:()=>{L()},type:"button",children:"Reassign Identity"})]}):null,_?o("p",{"aria-live":"assertive",role:"alert",children:_}):null]}):null]})}function jA({intent:e,options:t,projection:n}){if(t.loading)return o(Lf,{label:"Loading Devices"});if(t.loadError)return o("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(m=>!t.inventory?.items.some(f=>f.state!=="configured"&&f.evidenceDeviceIds.includes(m.deviceId))),a=new Set(i.map(m=>m.deviceId)),s=t.inventoryUnavailable?o("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=$f(t.inventory),l=t.inventory?.items.filter(m=>m.state==="configured"&&!m.evidenceDeviceIds.some(f=>a.has(f)))??[],d=t.inventory?o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((m,f)=>{const g=`configured-inventory-title-${f}`,h=e.identities.find(v=>v.identityId===m.identityId)?.displayName??"Unavailable Identity";return o("li",{children:o("article",{"aria-labelledby":g,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:g,children:m.displayName}),o("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),o("p",{children:[o("strong",{children:"Owning Identity:"})," ",h]}),o(Gv,{intent:e,inventory:t.inventory,item:m,options:t,previousIdentityName:h})]})},m.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?o("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),o("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),o("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?o(Z,{children:[t.inventory.truncated?o("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?o("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,o(OA,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?o(Z,{children:[r,s,u,p,d,o("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):o(Z,{children:[r,s,u,p,d,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((m,f)=>{const g=`devices-card-title-${f}`,h=m.action,v=t.inventory?.items.find(b=>b.state==="configured"&&b.evidenceDeviceIds.includes(m.deviceId));return o("li",{children:o("article",{"aria-labelledby":g,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:g,children:m.displayName}),o("span",{className:"badge actor-badge",children:[gd(t)?"Device":"Configured"," ·"," ",m.availabilityLabel]})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Owning Identity"}),o("dd",{children:m.identityName})]}),o("div",{children:[o("dt",{children:"Availability"}),o("dd",{children:m.availabilityLabel})]}),m.isPairedPeer?o("div",{children:[o("dt",{children:"Codemem version"}),o("dd",{children:m.reportedRuntimeVersion??"Not reported"})]}):null,o("div",{children:[o("dt",{children:"Sharing status"}),o("dd",{children:[o("strong",{children:m.statusLabel})," — ",m.statusCopy]})]})]}),o("section",{"aria-labelledby":`${g}-direct`,children:[o("h4",{id:`${g}-direct`,children:"Direct Projects"}),o(Bv,{empty:"No Projects are shared directly.",projects:m.directProjects})]}),o("section",{"aria-labelledby":`${g}-teams`,children:[o("h4",{id:`${g}-teams`,children:"Projects through Teams"}),o(Bv,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:m.inheritedProjects})]}),m.unavailableProjectCount>0?o("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,m.deliveredCopiesMayRemain?o("p",{className:"small",children:[o("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,h&&t.onNavigate?o("button",{"aria-label":`${h.label} for ${m.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(h.target),ref:b=>{b&&vd.set(b,{deviceId:m.deviceId,target:h.target})},type:"button",children:h.label}):null,v&&t.inventory?o(Gv,{intent:e,inventory:t.inventory,item:v,options:t,previousIdentityName:m.identityName}):null]})},m.deviceId)})}),n.revokedDeviceCount>0?o("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function _s(e,t,n,r,i,a={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?vd.get(s):void 0,d=MA(t,n,r,i,a.peerRuntimeMetadata);if(Ge(o("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("div",{className:"recipient-policy-sharing-header",children:[o("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),o("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),o(jA,{intent:t,options:a,projection:d}),o("p",{"aria-live":"polite",id:Uv,role:"status"})]}),e),mn(""),!a.loading&&w.pendingDeviceIdentityFocus!==void 0){const u=w.pendingDeviceIdentityFocus,p=a.inventory?.items.find(f=>f.deviceId===u||f.evidenceDeviceIds.includes(u??"")),m=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(f=>document.getElementById(`device-identity-card-${f}`)).find(f=>f instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)w.pendingDeviceIdentityFocus=void 0;else if(m){w.pendingDeviceIdentityFocus=void 0,m.focus();return}else if(!a.inventoryUnavailable&&!a.refreshError){w.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=vd.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function FA(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function ur(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function BA(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.round(i/60);if(a<60)return`${a}m ago`;const s=Math.round(a/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function ii(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 Dn(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 qv(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function UA(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 yd(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const a=n/i;return Number.isFinite(a)?`${Math.round(a*100)}%`:"n/a"}function la(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:a}=n[r],s=t/a,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function GA(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function da(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ws(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 Hv(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function qA(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function HA(e,t=2){if(!e.length)return"";const n=e.map(a=>String(a).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function Kv(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function KA(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function VA(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,a=0;for(;a<n.length-1&&r(i)>=1024;)i/=1024,a+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[a]}`}function Vv(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===w.lastStatsPayload?.identity?.actor_id)}function Ss(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function WA(e){if(!e)return[];const t=String(e).split(`
|
|
46
|
-
`).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function zA(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of r)if(!(a.length<18)&&(i.push(a),i.length>=t))break;return i}function Wv(e){const t=da(e.title),n=da(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 zv(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function ft(e){return`${String(e.kind||"").toLowerCase()}:${zv(e)}`}function JA(e){if(e.tags!=null)return ws(e.tags);const t=ws(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function YA(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function XA(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function QA(e){if(Vv(e))return"You";const t=String(e.actor_id||"").trim(),n=Br(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function ZA(e,t={}){if(Vv(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=Br(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Jv(e,t){const n=new Map;return e.forEach(r=>{n.set(ft(r),r)}),t.forEach(r=>{n.set(ft(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function ex(e,t){const n=new Set(t.map(ft));return Jv(e.filter(r=>!n.has(ft(r))),t)}var eF=560;function tx(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function Cs(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Ts(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function nx(e,t){const n=new Set(t.map(ft));return e.filter(r=>!n.has(ft(r))).length}var[Ns,tF]=st("Tooltip",[kn]),Is=kn(),Yv="TooltipProvider",rx=700,bd="tooltip.open",[ix,_d]=Ns(Yv),Xv=e=>{const{__scopeTooltip:t,delayDuration:n=rx,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,s=G(!0),c=G(!1),l=G(0);return z(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),o(ix,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:ce(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:ce(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:ce(d=>{c.current=d},[]),disableHoverableContent:i,children:a})};Xv.displayName=Yv;var ua="Tooltip",[ax,pa]=Ns(ua),Qv=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:s,delayDuration:c}=e,l=_d(ua,e.__scopeTooltip),d=Is(t),[u,p]=x(null),m=ct(),f=G(0),g=s??l.disableHoverableContent,h=c??l.delayDuration,v=G(!1),[b,_]=Tt({prop:r,defaultProp:i??!1,onChange:A=>{A?(l.onOpen(),document.dispatchEvent(new CustomEvent(bd))):l.onClose(),a?.(A)},caller:ua}),S=xe(()=>b?v.current?"delayed-open":"instant-open":"closed",[b]),C=ce(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,_(!0)},[_]),N=ce(()=>{window.clearTimeout(f.current),f.current=0,_(!1)},[_]),E=ce(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,_(!0),f.current=0},h)},[h,_]);return z(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),o(ra,{...d,children:o(ax,{scope:t,contentId:m,open:b,stateAttribute:S,trigger:u,onTriggerChange:p,onTriggerEnter:ce(()=>{l.isOpenDelayedRef.current?E():C()},[l.isOpenDelayedRef,E,C]),onTriggerLeave:ce(()=>{g?N():(window.clearTimeout(f.current),f.current=0)},[N,g]),onOpen:C,onClose:N,disableHoverableContent:g,children:n})})};Qv.displayName=ua;var wd="TooltipTrigger",Zv=V((e,t)=>{const{__scopeTooltip:n,...r}=e,i=pa(wd,n),a=_d(wd,n),s=Is(n),c=we(t,G(null),i.onTriggerChange),l=G(!1),d=G(!1),u=ce(()=>l.current=!1,[]);return z(()=>()=>document.removeEventListener("pointerup",u),[u]),o(ia,{asChild:!0,...s,children:o(pe.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:c,onPointerMove:Q(e.onPointerMove,p=>{p.pointerType!=="touch"&&!d.current&&!a.isPointerInTransitRef.current&&(i.onTriggerEnter(),d.current=!0)}),onPointerLeave:Q(e.onPointerLeave,()=>{i.onTriggerLeave(),d.current=!1}),onPointerDown:Q(e.onPointerDown,()=>{i.open&&i.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:Q(e.onFocus,()=>{l.current||i.onOpen()}),onBlur:Q(e.onBlur,i.onClose),onClick:Q(e.onClick,i.onClose)})})});Zv.displayName=wd;var Sd="TooltipPortal",[ox,sx]=Ns(Sd,{forceMount:void 0}),ey=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=pa(Sd,t);return o(ox,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Xn,{asChild:!0,container:i,children:r})})})};ey.displayName=Sd;var ai="TooltipContent",ty=V((e,t)=>{const n=sx(ai,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...a}=e,s=pa(ai,e.__scopeTooltip);return o(nt,{present:r||s.open,children:s.disableHoverableContent?o(ny,{side:i,...a,ref:t}):o(cx,{side:i,...a,ref:t})})}),cx=V((e,t)=>{const n=pa(ai,e.__scopeTooltip),r=_d(ai,e.__scopeTooltip),i=G(null),a=we(t,i),[s,c]=x(null),{trigger:l,onClose:d}=n,u=i.current,{onPointerInTransitChange:p}=r,m=ce(()=>{c(null),p(!1)},[p]),f=ce((g,h)=>{const v=g.currentTarget,b={x:g.clientX,y:g.clientY},_=mx(b,px(b,v.getBoundingClientRect())),S=fx(h.getBoundingClientRect());c(gx([..._,...S])),p(!0)},[p]);return z(()=>()=>m(),[m]),z(()=>{if(l&&u){const g=v=>f(v,u),h=v=>f(v,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",h)}}},[l,u,f,m]),z(()=>{if(s){const g=h=>{const v=h.target,b={x:h.clientX,y:h.clientY},_=l?.contains(v)||u?.contains(v),S=!hx(b,s);_?m():S&&(m(),d())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,s,d,m]),o(ny,{...e,ref:a})}),[lx,dx]=Ns(ua,{isInside:!1}),ux=CC("TooltipContent"),ny=V((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:s,...c}=e,l=pa(ai,n),d=Is(n),{onClose:u}=l;return z(()=>(document.addEventListener(bd,u),()=>document.removeEventListener(bd,u)),[u]),z(()=>{if(l.trigger){const p=m=>{m.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,u]),o(Yn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:o(as,{"data-state":l.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o(ux,{children:r}),o(lx,{scope:n,isInside:!0,children:o(VN,{id:l.contentId,role:"tooltip",children:i||r})})]})})});ty.displayName=ai;var ry="TooltipArrow",iy=V((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Is(n);return dx(ry,n).isInside?null:o(os,{...i,...r,ref:t})});iy.displayName=ry;function px(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function mx(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function fx(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function hx(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function gx(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),vx(t)}function vx(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const a=t[t.length-1],s=t[t.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const a=n[n.length-1],s=n[n.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var yx=Xv,bx=Qv,_x=Zv,wx=ey,Sx=ty,Cx=iy;function Cd({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return o(yx,{delayDuration:t,skipDelayDuration:n,children:e})}function ks({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:a=!0,disabled:s=!1}){return s?o(Z,{children:e}):o(bx,{children:[o(_x,{asChild:a,children:e}),o(wx,{children:o(Sx,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,o(Cx,{className:"tooltip-arrow"})]})})]})}function Tx(e){e.dataset.feedRenderRoot="preact"}function Nx(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function Ix(e,t){Tx(e),Ge(y(Cd,null,t),e)}function kx(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function Ex(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function Td(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function Px(e){const t=Ss(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=da(n),a=da(r),s=!!r&&a!==i,c=ws(e?.facts||t?.facts||[]),l=c.length?c:WA(r||n),d=l.length?l:zA(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function Ax(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 xx(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function Rx(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function Dx(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function Lx(e,t){const n=w.feedTypeFilter==="observations"?" · observations":w.feedTypeFilter==="summaries"?" · session summaries":"",r=YA(w.feedScopeFilter),i=!w.feedQuery.trim()&&w.lastFeedFilteredCount?` · ${w.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${w.feedQuery.trim()?` · matching "${w.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Es({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 $x({open:e}){const[t,n]=x(()=>String(w.feedQuery||"")),[r,i]=x(!1),[a,s]=x(!1),[c,l]=x(""),[d,u]=x(!1),[p,m]=x(""),[f,g]=x(""),[h,v]=x(null),b=G(0),_=String(w.feedQuery||""),S=String(t||"").trim(),C=w.currentProject||null,N=Ex(c),E=Td({project:C,query:S,workingSetFiles:N}),A=h&&Td({project:h.inputs.project,query:h.inputs.query,workingSetFiles:h.inputs.working_set_files})===E?h:null,M=p&&f===E?p:"";z(()=>{b.current+=1,u(!1),m(""),g(""),v(L=>!L||L.inputs.query!==S||L.inputs.project!==C?null:L)},[E]),z(()=>{e&&!r&&(n(kx({feedQuery:_,hasInspectorOverride:a,inspectorQuery:t})),i(!0))},[_,a,r,t,e]);const U=async()=>{const L=S,R=C,P=N,I=Td({project:R,query:L,workingSetFiles:P}),D=b.current+1;if(b.current=D,!L){m("Enter a query to inspect."),g(I),v(null);return}u(!0),m(""),g("");try{const O=await Xw({context:L,project:R,working_set_files:P});if(D!==b.current)return;v(O)}catch(O){if(D!==b.current)return;m(O instanceof Error?O.message:String(O)),g(I),v(null)}finally{D===b.current&&u(!1)}},k=A?.retrieval.candidates.filter(L=>L.disposition==="selected")||[],F=A?.retrieval.candidates.filter(L=>L.disposition==="dropped")||[],j=A?.retrieval.candidates.filter(L=>L.disposition==="deduped")||[],H=A?.retrieval.candidates.filter(L=>L.disposition==="trimmed")||[];return e?y("div",{className:"feed-inspector"},y("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[y("div",{className:"feed-card-header"},[y("div",{className:"feed-card-title"},"Context Inspector"),y("div",{className:"feed-card-meta"},a?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),y("div",{className:"feed-card-body"},[y("input",{className:"feed-search",onInput:L=>{n(String(L.currentTarget.value||"")),s(!0),v(null),m(""),g("")},placeholder:"Trace a pack query…",value:t}),y("div",{className:"section-meta",style:"margin-top:8px;"},a?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),y("textarea",{className:"feed-inspector-files",onInput:L=>l(String(L.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),y("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},y("button",{className:"toggle-button active",disabled:d,onClick:()=>{U()},type:"button"},d?"Tracing…":"Run trace"),A?y("span",{className:"section-meta"},`mode=${A.mode.selected} · candidates=${A.retrieval.candidate_count} · tokens=${A.output.estimated_tokens}`):null),h&&!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,M?y("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},M):null]),A?y(Z,null,[y(Es,{label:"Selected",candidates:k}),y(Es,{label:"Dropped",candidates:F}),y(Es,{label:"Deduped",candidates:j}),y(Es,{label:"Trimmed",candidates:H}),y("div",{className:"feed-card-body"},[A.assembly.collapsed_groups.length?y("div",{className:"section-meta"},`Collapsed duplicates: ${A.assembly.collapsed_groups.map(L=>`kept #${L.kept} from [${L.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 Mx={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function Nd({variant:e,tone:t,title:n,children:r}){const i=Mx[e];return o("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function ay(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 Ox(e){if(Array.isArray(e))return e}function jx(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,s,c=[],l=!0,d=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(l=(r=a.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function Fx(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
47
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Bx(e,t){return Ox(e)||jx(e,t)||Ux(e,t)||Fx()}function Ux(e,t){if(e){if(typeof e=="string")return ay(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)?ay(e,t):void 0}}var oy=Object.entries,sy=Object.setPrototypeOf,Gx=Object.isFrozen,qx=Object.getPrototypeOf,Hx=Object.getOwnPropertyDescriptor,Xe=Object.freeze,Qe=Object.seal,oi=Object.create,cy=typeof Reflect<"u"&&Reflect,Id=cy.apply,kd=cy.construct;Xe||(Xe=function(t){return t}),Qe||(Qe=function(t){return t}),Id||(Id=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];return t.apply(n,i)}),kd||(kd=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 ma=Ve(Array.prototype.forEach),Kx=Ve(Array.prototype.lastIndexOf),ly=Ve(Array.prototype.pop),si=Ve(Array.prototype.push),Vx=Ve(Array.prototype.splice),Ln=Array.isArray,fa=Ve(String.prototype.toLowerCase),Ed=Ve(String.prototype.toString),dy=Ve(String.prototype.match),ha=Ve(String.prototype.replace),uy=Ve(String.prototype.indexOf),Wx=Ve(String.prototype.trim),zx=Ve(Number.prototype.toString),Jx=Ve(Boolean.prototype.toString),py=typeof BigInt>"u"?null:Ve(BigInt.prototype.toString),my=typeof Symbol>"u"?null:Ve(Symbol.prototype.toString),ze=Ve(Object.prototype.hasOwnProperty),ga=Ve(Object.prototype.toString),Ze=Ve(RegExp.prototype.test),pr=Yx(TypeError);function Ve(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Id(e,t,r)}}function Yx(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return kd(e,n)}}function Ne(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fa;if(sy&&sy(e,null),!Ln(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const a=n(i);a!==i&&(Gx(t)||(t[r]=a),i=a)}e[i]=!0}return e}function Xx(e){for(let t=0;t<e.length;t++)ze(e,t)||(e[t]=null);return e}function ut(e){const t=oi(null);for(const r of oy(e)){var n=Bx(r,2);const i=n[0],a=n[1];ze(e,i)&&(Ln(a)?t[i]=Xx(a):a&&typeof a=="object"&&a.constructor===Object?t[i]=ut(a):t[i]=a)}return t}function Qx(e){switch(typeof e){case"string":return e;case"number":return zx(e);case"boolean":return Jx(e);case"bigint":return py?py(e):"0";case"symbol":return my?my(e):"Symbol()";case"undefined":return ga(e);case"function":case"object":{if(e===null)return ga(e);const t=e,n=zt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:ga(r)}return ga(e)}default:return ga(e)}}function zt(e,t){for(;e!==null;){const r=Hx(e,t);if(r){if(r.get)return Ve(r.get);if(typeof r.value=="function")return Ve(r.value)}e=qx(e)}function n(){return null}return n}function Zx(e){try{return Ze(e,""),!0}catch{return!1}}var fy=Xe(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Pd=Xe(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ad=Xe(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),eR=Xe(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),xd=Xe(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),tR=Xe(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),hy=Xe(["#text"]),gy=Xe(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Rd=Xe(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),vy=Xe(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ps=Xe(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),nR=Qe(/{{[\w\W]*|^[\w\W]*}}/g),rR=Qe(/<%[\w\W]*|^[\w\W]*%>/g),iR=Qe(/\${[\w\W]*/g),aR=Qe(/^data-[\-\w.\u00B7-\uFFFF]+$/),oR=Qe(/^aria-[\-\w]+$/),yy=Qe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),sR=Qe(/^(?:\w+script|data):/i),cR=Qe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),lR=Qe(/^html$/i),dR=Qe(/^[a-z][.\w]*(-[.\w]+)+$/i),by=Qe(/<[/\w!]/g),uR=Qe(/<[/\w]/g),pR=Qe(/<\/no(script|embed|frames)/i),mR=Qe(/\/>/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},fR=function(){return typeof window>"u"?null:window},hR=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const a="dompurify"+(r?"#"+r:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},_y=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},$n=function(t,n,r,i){return ze(t,n)&&Ln(t[n])?Ne(i.base?ut(i.base):{},t[n],i.transform):r};function wy(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fR();const t=te=>wy(te);if(t.version="3.4.11",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 a=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,m=zt(p,"cloneNode"),f=zt(p,"remove"),g=zt(p,"nextSibling"),h=zt(p,"childNodes"),v=zt(p,"parentNode"),b=zt(p,"shadowRoot"),_=zt(p,"attributes"),S=s&&s.prototype?zt(s.prototype,"nodeType"):null,C=s&&s.prototype?zt(s.prototype,"nodeName"):null;if(typeof a=="function"){const te=n.createElement("template");te.content&&te.content.ownerDocument&&(n=te.content.ownerDocument)}let N,E="",A,M=!1,U=0;const k=function(){if(U>0)throw pr('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.')},F=function(T){k(),U++;try{return N.createHTML(T)}finally{U--}},j=function(T){k(),U++;try{return N.createScriptURL(T)}finally{U--}},H=function(){return M||(A=hR(u,i),M=!0),A},L=n,R=L.implementation,P=L.createNodeIterator,I=L.createDocumentFragment,D=L.getElementsByTagName,O=r.importNode;let W=_y();t.isSupported=typeof oy=="function"&&typeof v=="function"&&R&&R.createHTMLDocument!==void 0;const ue=nR,re=rR,ie=iR,be=aR,Y=oR,fe=sR,ne=cR,Pe=dR;let ge=yy,ae=null;const Ee=Ne({},[...fy,...Pd,...Ad,...xd,...hy]);let le=null;const Te=Ne({},[...gy,...Rd,...vy,...Ps]);let B=Object.seal(oi(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}})),oe=null,K=null;const J=Object.seal(oi(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Oe=!0,Ae=!0,At=!1,hn=!0,ht=!1,gn=!0,ve=!1,gt=!1,St=null,Ni=null,Ja=!1,vn=!1,Er=!1,Hn=!1,vt=!0,Kn=!1;const mw="user-content-";let rp=!0,ip=!1,Ii={},Zt=null;const ap=Ne({},["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 fw=null;const hw=Ne({},["audio","video","img","source","image","track"]);let op=null;const gw=Ne({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pc="http://www.w3.org/1998/Math/MathML",mc="http://www.w3.org/2000/svg",en="http://www.w3.org/1999/xhtml";let ki=en,sp=!1,cp=null;const T1=Ne({},[pc,mc,en],Ed),vw=Xe(["mi","mo","mn","ms","mtext"]);let lp=Ne({},vw);const yw=Xe(["annotation-xml"]);let dp=Ne({},yw);const N1=Ne({},["title","style","font","a","script"]);let Ya=null;const I1=["application/xhtml+xml","text/html"],k1="text/html";let Ke=null,Ei=null;const E1=n.createElement("form"),bw=function(T){return T instanceof RegExp||T instanceof Function},up=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ei&&Ei===T)return;(!T||typeof T!="object")&&(T={}),T=ut(T),Ya=I1.indexOf(T.PARSER_MEDIA_TYPE)===-1?k1:T.PARSER_MEDIA_TYPE,Ke=Ya==="application/xhtml+xml"?Ed:fa,ae=$n(T,"ALLOWED_TAGS",Ee,{transform:Ke}),le=$n(T,"ALLOWED_ATTR",Te,{transform:Ke}),cp=$n(T,"ALLOWED_NAMESPACES",T1,{transform:Ed}),op=$n(T,"ADD_URI_SAFE_ATTR",gw,{transform:Ke,base:gw}),fw=$n(T,"ADD_DATA_URI_TAGS",hw,{transform:Ke,base:hw}),Zt=$n(T,"FORBID_CONTENTS",ap,{transform:Ke}),oe=$n(T,"FORBID_TAGS",ut({}),{transform:Ke}),K=$n(T,"FORBID_ATTR",ut({}),{transform:Ke}),Ii=ze(T,"USE_PROFILES")?T.USE_PROFILES&&typeof T.USE_PROFILES=="object"?ut(T.USE_PROFILES):T.USE_PROFILES:!1,Oe=T.ALLOW_ARIA_ATTR!==!1,Ae=T.ALLOW_DATA_ATTR!==!1,At=T.ALLOW_UNKNOWN_PROTOCOLS||!1,hn=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ht=T.SAFE_FOR_TEMPLATES||!1,gn=T.SAFE_FOR_XML!==!1,ve=T.WHOLE_DOCUMENT||!1,vn=T.RETURN_DOM||!1,Er=T.RETURN_DOM_FRAGMENT||!1,Hn=T.RETURN_TRUSTED_TYPE||!1,Ja=T.FORCE_BODY||!1,vt=T.SANITIZE_DOM!==!1,Kn=T.SANITIZE_NAMED_PROPS||!1,rp=T.KEEP_CONTENT!==!1,ip=T.IN_PLACE||!1,ge=Zx(T.ALLOWED_URI_REGEXP)?T.ALLOWED_URI_REGEXP:yy,ki=typeof T.NAMESPACE=="string"?T.NAMESPACE:en,lp=ze(T,"MATHML_TEXT_INTEGRATION_POINTS")&&T.MATHML_TEXT_INTEGRATION_POINTS&&typeof T.MATHML_TEXT_INTEGRATION_POINTS=="object"?ut(T.MATHML_TEXT_INTEGRATION_POINTS):Ne({},vw),dp=ze(T,"HTML_INTEGRATION_POINTS")&&T.HTML_INTEGRATION_POINTS&&typeof T.HTML_INTEGRATION_POINTS=="object"?ut(T.HTML_INTEGRATION_POINTS):Ne({},yw);const $=ze(T,"CUSTOM_ELEMENT_HANDLING")&&T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING=="object"?ut(T.CUSTOM_ELEMENT_HANDLING):oi(null);if(B=oi(null),ze($,"tagNameCheck")&&bw($.tagNameCheck)&&(B.tagNameCheck=$.tagNameCheck),ze($,"attributeNameCheck")&&bw($.attributeNameCheck)&&(B.attributeNameCheck=$.attributeNameCheck),ze($,"allowCustomizedBuiltInElements")&&typeof $.allowCustomizedBuiltInElements=="boolean"&&(B.allowCustomizedBuiltInElements=$.allowCustomizedBuiltInElements),Qe(B),ht&&(Ae=!1),Er&&(vn=!0),Ii&&(ae=Ne({},hy),le=oi(null),Ii.html===!0&&(Ne(ae,fy),Ne(le,gy)),Ii.svg===!0&&(Ne(ae,Pd),Ne(le,Rd),Ne(le,Ps)),Ii.svgFilters===!0&&(Ne(ae,Ad),Ne(le,Rd),Ne(le,Ps)),Ii.mathMl===!0&&(Ne(ae,xd),Ne(le,vy),Ne(le,Ps))),J.tagCheck=null,J.attributeCheck=null,ze(T,"ADD_TAGS")&&(typeof T.ADD_TAGS=="function"?J.tagCheck=T.ADD_TAGS:Ln(T.ADD_TAGS)&&(ae===Ee&&(ae=ut(ae)),Ne(ae,T.ADD_TAGS,Ke))),ze(T,"ADD_ATTR")&&(typeof T.ADD_ATTR=="function"?J.attributeCheck=T.ADD_ATTR:Ln(T.ADD_ATTR)&&(le===Te&&(le=ut(le)),Ne(le,T.ADD_ATTR,Ke))),ze(T,"ADD_URI_SAFE_ATTR")&&Ln(T.ADD_URI_SAFE_ATTR)&&Ne(op,T.ADD_URI_SAFE_ATTR,Ke),ze(T,"FORBID_CONTENTS")&&Ln(T.FORBID_CONTENTS)&&(Zt===ap&&(Zt=ut(Zt)),Ne(Zt,T.FORBID_CONTENTS,Ke)),ze(T,"ADD_FORBID_CONTENTS")&&Ln(T.ADD_FORBID_CONTENTS)&&(Zt===ap&&(Zt=ut(Zt)),Ne(Zt,T.ADD_FORBID_CONTENTS,Ke)),rp&&(ae["#text"]=!0),ve&&Ne(ae,["html","head","body"]),ae.table&&(Ne(ae,["tbody"]),delete oe.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw pr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw pr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const ee=N;N=T.TRUSTED_TYPES_POLICY;try{E=F("")}catch(de){throw N=ee,de}}else T.TRUSTED_TYPES_POLICY===null?(N=void 0,E=""):(N===void 0&&(N=H()),N&&typeof E=="string"&&(E=F("")));Xe&&Xe(T),Ei=T},_w=Ne({},[...Pd,...Ad,...eR]),ww=Ne({},[...xd,...tR]),P1=function(T,$,ee){return $.namespaceURI===en?T==="svg":$.namespaceURI===pc?T==="svg"&&(ee==="annotation-xml"||lp[ee]):!!_w[T]},A1=function(T,$,ee){return $.namespaceURI===en?T==="math":$.namespaceURI===mc?T==="math"&&dp[ee]:!!ww[T]},x1=function(T,$,ee){return $.namespaceURI===mc&&!dp[ee]||$.namespaceURI===pc&&!lp[ee]?!1:!ww[T]&&(N1[T]||!_w[T])},R1=function(T){let $=v(T);(!$||!$.tagName)&&($={namespaceURI:ki,tagName:"template"});const ee=fa(T.tagName),de=fa($.tagName);return cp[T.namespaceURI]?T.namespaceURI===mc?P1(ee,$,de):T.namespaceURI===pc?A1(ee,$,de):T.namespaceURI===en?x1(ee,$,de):!!(Ya==="application/xhtml+xml"&&cp[T.namespaceURI]):!1},Vn=function(T){si(t.removed,{element:T});try{v(T).removeChild(T)}catch{if(f(T),!v(T))throw pr("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Sw=function(T){const $=h(T);if($){const de=[];ma($,Ce=>{si(de,Ce)}),ma(de,Ce=>{try{f(Ce)}catch{}})}const ee=_(T);if(ee)for(let de=ee.length-1;de>=0;--de){const Ce=ee[de],Le=Ce&&Ce.name;if(typeof Le=="string")try{T.removeAttribute(Le)}catch{}}},Pr=function(T,$){try{si(t.removed,{attribute:$.getAttributeNode(T),from:$})}catch{si(t.removed,{attribute:null,from:$})}if($.removeAttribute(T),T==="is")if(vn||Er)try{Vn($)}catch{}else try{$.setAttribute(T,"")}catch{}},D1=function(T){const $=_(T);if($)for(let ee=$.length-1;ee>=0;--ee){const de=$[ee],Ce=de&&de.name;if(!(typeof Ce!="string"||le[Ke(Ce)]))try{T.removeAttribute(Ce)}catch{}}},L1=function(T){const $=[T];for(;$.length>0;){const ee=$.pop();(S?S(ee):ee.nodeType)===Jt.element&&D1(ee);const de=h(ee);if(de)for(let Ce=de.length-1;Ce>=0;--Ce)$.push(de[Ce])}},Cw=function(T){let $=null,ee=null;if(Ja)T="<remove></remove>"+T;else{const Le=dy(T,/^[\r\n\t ]+/);ee=Le&&Le[0]}Ya==="application/xhtml+xml"&&ki===en&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");const de=N?F(T):T;if(ki===en)try{$=new d().parseFromString(de,Ya)}catch{}if(!$||!$.documentElement){$=R.createDocument(ki,"template",null);try{$.documentElement.innerHTML=sp?E:de}catch{}}const Ce=$.body||$.documentElement;return T&&ee&&Ce.insertBefore(n.createTextNode(ee),Ce.childNodes[0]||null),ki===en?D.call($,ve?"html":"body")[0]:ve?$.documentElement:Ce},Tw=function(T){return P.call(T.ownerDocument||T,T,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},fc=function(T){return T=ha(T,ue," "),T=ha(T,re," "),T=ha(T,ie," "),T},pp=function(T){var $;T.normalize();const ee=P.call(T.ownerDocument||T,T,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let de=ee.nextNode();for(;de;)de.data=fc(de.data),de=ee.nextNode();const Ce=($=T.querySelectorAll)===null||$===void 0?void 0:$.call(T,"template");Ce&&ma(Ce,Le=>{Pi(Le.content)&&pp(Le.content)})},hc=function(T){const $=C?C(T):null;return typeof $!="string"||Ke($)!=="form"?!1:typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||T.attributes!==_(T)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function"||T.nodeType!==S(T)||T.childNodes!==h(T)},Pi=function(T){if(!S||typeof T!="object"||T===null)return!1;try{return S(T)===Jt.documentFragment}catch{return!1}},Xa=function(T){if(!S||typeof T!="object"||T===null)return!1;try{return typeof S(T)=="number"}catch{return!1}};function yn(te,T,$){te.length!==0&&ma(te,ee=>{ee.call(t,T,$,Ei)})}const $1=function(T,$){return!!(gn&&T.hasChildNodes()&&!Xa(T.firstElementChild)&&Ze(by,T.textContent)&&Ze(by,T.innerHTML)||gn&&T.namespaceURI===en&&$==="style"&&Xa(T.firstElementChild)||T.nodeType===Jt.processingInstruction||gn&&T.nodeType===Jt.comment&&Ze(uR,T.data))},M1=function(T,$){if(!oe[$]&&kw($)&&(B.tagNameCheck instanceof RegExp&&Ze(B.tagNameCheck,$)||B.tagNameCheck instanceof Function&&B.tagNameCheck($)))return!1;if(rp&&!Zt[$]){const ee=v(T),de=h(T);if(de&&ee){const Ce=de.length;for(let Le=Ce-1;Le>=0;--Le){const Be=ip?de[Le]:m(de[Le],!0);ee.insertBefore(Be,g(T))}}}return Vn(T),!0},Nw=function(T){if(yn(W.beforeSanitizeElements,T,null),hc(T))return Vn(T),!0;const $=Ke(C?C(T):T.nodeName);if(yn(W.uponSanitizeElement,T,{tagName:$,allowedTags:ae}),$1(T,$))return Vn(T),!0;if(oe[$]||!(J.tagCheck instanceof Function&&J.tagCheck($))&&!ae[$])return M1(T,$);if((S?S(T):T.nodeType)===Jt.element&&!R1(T)||($==="noscript"||$==="noembed"||$==="noframes")&&Ze(pR,T.innerHTML))return Vn(T),!0;if(ht&&T.nodeType===Jt.text){const ee=fc(T.textContent);T.textContent!==ee&&(si(t.removed,{element:T.cloneNode()}),T.textContent=ee)}return yn(W.afterSanitizeElements,T,null),!1},Iw=function(T,$,ee){if(K[$]||vt&&($==="id"||$==="name")&&(ee in n||ee in E1))return!1;const de=le[$]||J.attributeCheck instanceof Function&&J.attributeCheck($,T);if(!(Ae&&Ze(be,$))){if(!(Oe&&Ze(Y,$))){if(de){if(!op[$]){if(!Ze(ge,ha(ee,ne,""))){if(!(($==="src"||$==="xlink:href"||$==="href")&&T!=="script"&&uy(ee,"data:")===0&&fw[T])){if(!(At&&!Ze(fe,ha(ee,ne,"")))){if(ee)return!1}}}}}else if(!(kw(T)&&(B.tagNameCheck instanceof RegExp&&Ze(B.tagNameCheck,T)||B.tagNameCheck instanceof Function&&B.tagNameCheck(T))&&(B.attributeNameCheck instanceof RegExp&&Ze(B.attributeNameCheck,$)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck($,T))||$==="is"&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&Ze(B.tagNameCheck,ee)||B.tagNameCheck instanceof Function&&B.tagNameCheck(ee))))return!1}}return!0},O1=Ne({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),kw=function(T){return!O1[fa(T)]&&Ze(Pe,T)},j1=function(T,$,ee,de){if(N&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!ee)switch(u.getAttributeType(T,$)){case"TrustedHTML":return F(de);case"TrustedScriptURL":return j(de)}return de},F1=function(T,$,ee,de){try{ee?T.setAttributeNS(ee,$,de):T.setAttribute($,de),hc(T)?Vn(T):ly(t.removed)}catch{Pr($,T)}},Ew=function(T){yn(W.beforeSanitizeAttributes,T,null);const $=T.attributes;if(!$||hc(T))return;const ee={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0};let de=$.length;const Ce=Ke(T.nodeName);for(;de--;){const Le=$[de],Be=Le.name,xt=Le.namespaceURI,bn=Le.value,jt=Ke(Be),fp=bn;let mt=Be==="value"?fp:Wx(fp);if(ee.attrName=jt,ee.attrValue=mt,ee.keepAttr=!0,ee.forceKeepAttr=void 0,yn(W.uponSanitizeAttribute,T,ee),mt=ee.attrValue,Kn&&(jt==="id"||jt==="name")&&uy(mt,mw)!==0&&(Pr(Be,T),mt=mw+mt),gn&&Ze(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,mt)){Pr(Be,T);continue}if(jt==="attributename"&&dy(mt,"href")){Pr(Be,T);continue}if(!ee.forceKeepAttr){if(!ee.keepAttr){Pr(Be,T);continue}if(!hn&&Ze(mR,mt)){Pr(Be,T);continue}if(ht&&(mt=fc(mt)),!Iw(Ce,jt,mt)){Pr(Be,T);continue}mt=j1(Ce,jt,xt,mt),mt!==fp&&F1(T,Be,xt,mt)}}yn(W.afterSanitizeAttributes,T,null)},gc=function(T){let $=null;const ee=Tw(T);for(yn(W.beforeSanitizeShadowDOM,T,null);$=ee.nextNode();)if(yn(W.uponSanitizeShadowNode,$,null),Nw($),Ew($),Pi($.content)&&gc($.content),(S?S($):$.nodeType)===Jt.element){const de=b($);Pi(de)&&(mp(de),gc(de))}yn(W.afterSanitizeShadowDOM,T,null)},mp=function(T){const $=[{node:T,shadow:null}];for(;$.length>0;){const ee=$.pop();if(ee.shadow){gc(ee.shadow);continue}const de=ee.node,Ce=(S?S(de):de.nodeType)===Jt.element,Le=h(de);if(Le)for(let Be=Le.length-1;Be>=0;--Be)$.push({node:Le[Be],shadow:null});if(Ce){const Be=C?C(de):null;if(typeof Be=="string"&&Ke(Be)==="template"){const xt=de.content;Pi(xt)&&$.push({node:xt,shadow:null})}}if(Ce){const Be=b(de);Pi(Be)&&$.push({node:null,shadow:Be},{node:Be,shadow:null})}}};return t.sanitize=function(te){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},$=null,ee=null,de=null,Ce=null;if(sp=!te,sp&&(te="<!-->"),typeof te!="string"&&!Xa(te)&&(te=Qx(te),typeof te!="string"))throw pr("dirty is not a string, aborting");if(!t.isSupported)return te;gt?(ae=St,le=Ni):up(T),(W.uponSanitizeElement.length>0||W.uponSanitizeAttribute.length>0)&&(ae=ut(ae)),W.uponSanitizeAttribute.length>0&&(le=ut(le)),t.removed=[];const Le=ip&&typeof te!="string"&&Xa(te);if(Le){const bn=C?C(te):te.nodeName;if(typeof bn=="string"){const jt=Ke(bn);if(!ae[jt]||oe[jt])throw pr("root node is forbidden and cannot be sanitized in-place")}if(hc(te))throw pr("root node is clobbered and cannot be sanitized in-place");try{mp(te)}catch(jt){throw Sw(te),jt}}else if(Xa(te))$=Cw("<!---->"),ee=$.ownerDocument.importNode(te,!0),ee.nodeType===Jt.element&&ee.nodeName==="BODY"||ee.nodeName==="HTML"?$=ee:$.appendChild(ee),mp(ee);else{if(!vn&&!ht&&!ve&&te.indexOf("<")===-1)return N&&Hn?F(te):te;if($=Cw(te),!$)return vn?null:Hn?E:""}$&&Ja&&Vn($.firstChild);const Be=Tw(Le?te:$);try{for(;de=Be.nextNode();)Nw(de),Ew(de),Pi(de.content)&&gc(de.content)}catch(bn){throw Le&&Sw(te),bn}if(Le)return ma(t.removed,bn=>{bn.element&&L1(bn.element)}),ht&&pp(te),te;if(vn){if(ht&&pp($),Er)for(Ce=I.call($.ownerDocument);$.firstChild;)Ce.appendChild($.firstChild);else Ce=$;return(le.shadowroot||le.shadowrootmode)&&(Ce=O.call(r,Ce,!0)),Ce}let xt=ve?$.outerHTML:$.innerHTML;return ve&&ae["!doctype"]&&$.ownerDocument&&$.ownerDocument.doctype&&$.ownerDocument.doctype.name&&Ze(lR,$.ownerDocument.doctype.name)&&(xt="<!DOCTYPE "+$.ownerDocument.doctype.name+`>
|
|
48
|
-
`+
|
|
49
|
-
]`).replace("lheading",
|
|
50
|
-
`),n=t.length-1;for(;n>=0&&
|
|
51
|
-
`)}function
|
|
45
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return W(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},ok="DialogDescriptionWarning",sk=({contentRef:e,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${bh(ok).contentName}}.`;return W(()=>{const r=e.current?.getAttribute("aria-describedby");t&&r&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},ck=ch,lk=uh,dk=ph,uk=mh,pk=hh;function gr({ariaDescribedby:e,ariaLabelledby:t,children:n,contentClassName:r,contentId:i,modal:a=!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,onOpenChange:u,open:p,overlayClassName:m,overlayId:f,slotId:y}){return o(ck,{modal:a,open:p,onOpenChange:u,children:p?o(lk,{children:[o(dk,{asChild:!0,children:o("div",{className:m,id:f})}),o(uk,{"aria-describedby":e,"aria-labelledby":t,asChild:!0,onCloseAutoFocus:s,onEscapeKeyDown:c,onInteractOutside:l,onOpenAutoFocus:d,children:o("div",{role:"dialog",className:r,id:i,onClick:g=>{g.target===g.currentTarget&&u(!1)},tabIndex:-1,children:n??(y?o("div",{id:y}):null)})})]}):null})}function mk(e){return o(pk,{...e})}function fk(e,t){return e.canonicalId<t.canonicalId?-1:e.canonicalId>t.canonicalId?1:0}function ra(e){return e.normalize("NFKC").replace(/\u200B/gu,"").replace(/\s+/gu," ").trim().toLowerCase()}function _h(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(fk)}function vr(e){const t=new Map;for(const r of _h(e)){const i=ra(r.displayName),a=t.get(i);a?a.push(r):t.set(i,[r])}const n=new Map;for(const r of t.values())for(const[i,a]of r.entries())n.set(a.canonicalId,r.length>1?`${a.displayName} — duplicate name ${i+1} of ${r.length}`:a.displayName);return n}function hk(e){const t=new Map;for(const n of _h(e)){const r=ra(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=ra(n.displayName).localeCompare(ra(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 wh=500,zo=null,ia=null,aa=null;function oa(e){return ia?ia(e)?(aa=document.activeElement instanceof HTMLElement?document.activeElement:null,!0):!1:(aa=document.activeElement instanceof HTMLElement?document.activeElement:null,zo=e,!0)}function Ze(e){return e.recipientKind==="identity"?`identity:${e.identityId}`:`team:${e.teamId}`}function Sh(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 sa(e){return e.recipientKind==="identity"?Ze({recipientKind:"identity",identityId:e.identityId}):Ze({recipientKind:"team",teamId:e.teamId})}function gk(e,t){return sa(e)===Ze(t)}function Ll(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 vk(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),a=i.flatMap(c=>c.recipientKind==="team"&&!n.has(c.teamId)?[sa(c)]:[]),s=i.flatMap(c=>c.recipientKind==="identity"&&!r.has(c.identityId)?[sa(c)]:[]);return new Map([...Ll(a,"Unavailable Team"),...Ll(s,"Unavailable Identity")])}function yk(e,t,n){if(t?.mode!=="recipient-manage")return new Map;const r=new Set(e.map(i=>i.canonicalProjectIdentity));return Ll(n.filter(i=>!r.has(i)),"Unavailable Project")}function Ch(e,t){return e instanceof Yc?"Recipient access changed after this review. Review the refreshed changes before trying again.":t}function Nh({checked:e,description:t,disabled:n,label:r,onChange:i}){const a=`recipient-policy-choice-${ur()}`;return o("label",{className:"sync-dialog-radio-option recipient-policy-management-choice recipient-policy-management-target",htmlFor:a,children:[o("input",{checked:e,disabled:n,id:a,onChange:i,type:"checkbox"}),o("span",{children:[o("strong",{className:"recipient-policy-management-name",children:r}),o("span",{className:"small recipient-policy-management-description",children:t})]})]})}function bk(e,t,n){const r=e.teamMemberships.filter(c=>c.status==="active"),i=new Map(e.identities.map(c=>[c.identityId,c])),a=[...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:Ze({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:Ze({recipientKind:"identity",identityId:c.identityId}),label:c.displayName,description:`Identity · ${c.status==="pending"?"pending · ":""}locally verified`}))];if(t?.mode!=="project-manage")return a;const s=new Set(a.map(c=>c.key));for(const c of e.projectRecipients){if(c.status!=="active"||c.canonicalProjectIdentity!==t.projectId)continue;const l=sa(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";a.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";a.push({key:l,label:d?.displayName??u,description:`${d?.status==="merged"?"Merged Identity":u} · existing access can only be removed`})}s.add(l)}}return a}function Ih(e){return e.mode==="project-add"?[...new Set(e.projectIds)]:e.mode==="project-manage"?[e.projectId]:[]}function _k(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(sa):n.filter(r=>gk(r,e.recipient)).map(r=>r.canonicalProjectIdentity)}function wk(e,t,n,r){const i=vr(e.map(d=>({canonicalId:d.canonicalProjectIdentity,displayName:d.displayName}))),a=t.mode==="recipient-add"?e.filter(d=>!n.includes(d.canonicalProjectIdentity)):e,s=a.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(a.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 Sk(e,t,n){return e.mode==="project-add"?Ih(e).flatMap(r=>t.flatMap(i=>{const a=Sh(i);return a?[{canonicalProjectIdentity:r,recipient:a,action:"add"}]:[]})):e.mode==="project-manage"?[...new Set([...n,...t])].flatMap(r=>{const i=Sh(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 Ck(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 kh(e,t){let n=!1,r=!1,i=!1,a=!1;const s=Ze(t);for(const c of e){const{change:l,outcome:d}=c;Ze(l.recipient)===s&&(l.action==="add"?(i=!0,d==="added"&&(n=!0)):(a=!0,d==="removed"&&(r=!0)))}return n&&r?"Mixed changes":r?"Removing access":n?"Adding access":i&&!a?"Already has access":a&&!i?"Already without access":"No changes"}function Nk(e){const t=new Set(e.selectedRecipients.map(Ze)),n=new Map;for(const r of e.normalizedChanges){const i=Ze(r.recipient);t.has(i)||n.set(i,r.recipient)}return[...n.values()]}function Ik(e){const t=new Set;return e.filter(n=>t.has(n.deviceId)?!1:(t.add(n.deviceId),!0))}function $l(e,t){const n=t.get(e.canonicalProjectIdentity);return n||(e.displayName!==e.canonicalProjectIdentity?e.displayName:"Unavailable Project")}function kk({preview:e,projectLabels:t,recipientLabels:n}){const r=Ik(e.effectiveDevices),i=Nk(e);return o("div",{className:"sync-dialog-stack recipient-policy-management-review",children:[o("section",{"aria-labelledby":"recipient-policy-review-projects",children:[o("h3",{id:"recipient-policy-review-projects",children:"Projects affected"}),o("ul",{children:e.projects.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:$l(a,t)}),o("span",{children:[" ","— Access changes affect ",a.existingMemoryCount.toLocaleString()," existing memories",a.futureMemoriesShared?" and future activity":"; future activity is not included"]})]},a.canonicalProjectIdentity))})]}),o("section",{"aria-labelledby":"recipient-policy-review-recipients",children:[o("h3",{id:"recipient-policy-review-recipients",children:"Recipient changes"}),o("ul",{children:[e.selectedRecipients.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:a.displayName})," ",o("span",{children:["— ",kh(e.outcomes,a)," · "]}),a.recipientKind==="identity"?o("span",{children:"Identity · locally verified"}):o("span",{className:"recipient-policy-management-recipient-context",children:["Team · ",a.currentMembers.length.toLocaleString()," current"," ",a.currentMembers.length===1?"member":"members",a.currentMembers.length?o(z,{children:[":"," ",o("span",{className:"recipient-policy-management-member-names",children:a.currentMembers.map(s=>s.displayName).join(", ")})]}):null,". Future Team members"," ",a.futureMembersInherit?"inherit":"do not inherit"," access."]})]},Ze(a))),i.map(a=>o("li",{children:[o("strong",{className:"recipient-policy-management-name",children:n.get(Ze(a))??(a.recipientKind==="team"?"Unavailable Team":"Unavailable Identity")})," ",o("span",{children:["— ",kh(e.outcomes,a)," ·"," ",a.recipientKind==="team"?"Team":"Identity"]})]},Ze(a)))]})]}),o("section",{"aria-labelledby":"recipient-policy-review-availability",children:[o("h3",{id:"recipient-policy-review-availability",children:"Resulting availability"}),r.length?o(z,{children:[o("p",{children:["After the update, the affected Projects will be available on"," ",r.length.toLocaleString()," current"," ",r.length===1?"device":"devices"," across all recipients."]}),o("ul",{children:r.map(a=>o("li",{className:"recipient-policy-management-name",children:a.displayName},a.deviceId))})]}):o("p",{children:"After the update, no recipient devices will have access to the affected Projects yet — for example, a Team with no current members. Your own access on this device is not affected."})]}),o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Change details"}),o("p",{className:"small",children:[e.addCount.toLocaleString()," ",e.addCount===1?"add":"adds"," ·"," ",e.removeCount.toLocaleString()," ",e.removeCount===1?"remove":"removes"," ","· ",e.netWriteCount.toLocaleString()," ",e.netWriteCount===1?"write":"writes"]}),e.unchangedProjects.length?o(z,{children:[o("p",{className:"small recipient-policy-management-detail-label",children:o("strong",{children:"Unchanged Projects"})}),o("ul",{"aria-label":"Unchanged Projects",children:e.unchangedProjects.map(a=>o("li",{className:"recipient-policy-management-name",children:$l(a,t)},a.canonicalProjectIdentity))})]}):null]})]})}function Tk({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 o("div",{className:"sync-dialog-stack recipient-policy-management-result",children:o("details",{className:"recipient-policy-management-details",children:[o("summary",{children:"Technical details"}),o("p",{children:["Status: ",i,". Writes: ",r.writeCount.toLocaleString(),"."]}),r.errorCode?o("p",{children:["Error code: ",r.errorCode.replaceAll("_"," "),"."]}):null,r.outcomes.length?o("ul",{children:r.outcomes.map(a=>{const s=e.projects.find(d=>d.canonicalProjectIdentity===a.change.canonicalProjectIdentity),c=s?$l(s,t):t.get(a.change.canonicalProjectIdentity)??"Unavailable Project",l=e.selectedRecipients.find(d=>Ze(d)===Ze(a.change.recipient))?.displayName??n.get(Ze(a.change.recipient))??(a.change.recipient.recipientKind==="team"?"Team":"Identity");return o("li",{children:[a.change.action==="add"?"Add":"Remove"," ",l," ",a.change.action==="add"?"to":"from"," ",c,":"," ",a.outcome.replaceAll("_"," ")]},`${a.change.canonicalProjectIdentity}:${Ze(a.change.recipient)}`)})}):null]})})}function Rk({intent:e,options:t,projects:n}){const[r,i]=D(null),[a,s]=D([]),[c,l]=D([]),[d,u]=D(null),[p,m]=D(null),[f,y]=D(null),[g,h]=D(""),[b,w]=D(!1),_=q(!1),I=q(new Map),N=q(new Map),T=Se(()=>vk(e,r),[e,r]),x=Se(()=>bk(e,r,T),[e,r,T]),j=Se(()=>new Map([...e.teams.map(H=>[`team:${H.teamId}`,H.displayName]),...e.identities.map(H=>[`identity:${H.identityId}`,H.displayName]),...T]),[e,T]),B=Se(()=>yk(n,r,c),[c,n,r]),P=Se(()=>new Set(n.map(H=>H.canonicalProjectIdentity)),[n]),F=Se(()=>{const H=vr(n.map(fe=>({canonicalId:fe.canonicalProjectIdentity,displayName:fe.displayName})));return new Map([...H,...B])},[n,B]);if(W(()=>{if(ia=H=>{if(_.current)return!1;const fe=_k(H,e);return i(H),l(fe),s(H.mode==="recipient-add"?[]:fe),u(null),m(null),I.current=new Map,N.current=new Map,y(null),h(""),w(!1),_.current=!1,!0},zo){const H=zo;zo=null,ia(H)}return()=>{ia=null}},[e]),W(()=>{p&&document.getElementById("recipient-policy-management-title")?.focus()},[p]),!r)return null;const O=Ck(r),G=Ih(r),$=r.mode==="recipient-manage"?!1:G.some(H=>!P.has(H)),A=(r.mode==="recipient-add"||r.mode==="recipient-manage")&&!x.some(H=>H.key===Ze(r.recipient)),E=t.loading||t.loadError||$||A,C=Sk(r,a,c),L=C.length>wh,U=(r.mode==="project-add"||r.mode==="recipient-add")&&a.length===0,V=r.mode!=="project-add"&&r.mode!=="recipient-add"&&C.length===0,de=wk(n,r,c,B),ie=p?.status==="applied",ne=p?ie?"Recipient access updated":"Recipient access needs attention":d?"Review recipient access":O.title,Re=p?ie?"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.":O.description,ye=()=>{_.current||(i(null),u(null),m(null),I.current=new Map,N.current=new Map,y(null),h(""))},Ce=H=>{s(fe=>fe.includes(H)?fe.filter(ae=>ae!==H):[...fe,H]),y(null),h("")},re=async()=>{if(!(E||U||V||L||_.current)){_.current=!0,w(!0),y(null),h("Reviewing exact recipient access changes.");try{const H=await UC({version:1,changes:C});I.current=new Map(j),N.current=new Map(F),u(H),h("Review ready. Confirm the exact changes.")}catch(H){y(Ch(H,"Unable to review recipient access changes.")),h("")}finally{_.current=!1,w(!1)}}},Pe=async()=>{if(!(!d||_.current)){_.current=!0,w(!0),y(null),h("Saving recipient access changes.");try{const H=await qC({version:1,changes:d.normalizedChanges,reviewedPolicyDigest:d.reviewedPolicyDigest});m(H),h("");try{await t.onCommitted?.(H)}catch{y("Recipient access was saved, but this view could not refresh.")}}catch(H){H instanceof Yc&&(u(null),I.current=new Map,N.current=new Map,h("")),y(Ch(H,"Unable to save recipient access changes."))}finally{_.current=!1,w(!1)}}};let ue=null;return t.loading?ue="Loading the complete recipient access inventory…":t.loadError?ue="The complete recipient access inventory is unavailable. Refresh and try again.":$?ue="One selected Project is no longer available. Refresh and try again.":A&&(ue="This recipient is no longer available. Refresh and try again."),o(gr,{ariaDescribedby:"recipient-policy-management-description",ariaLabelledby:"recipient-policy-management-title",contentClassName:"modal recipient-policy-management-dialog",contentId:"recipientPolicyManagementDialog",onCloseAutoFocus:H=>{H.preventDefault();const fe=r.mode.startsWith("project-")?"tabBtn-projects":"tabBtn-sharing",ae=aa?.isConnected?aa:document.getElementById(fe);ae instanceof HTMLElement&&ae.focus(),aa=null},onOpenAutoFocus:H=>{const fe=document.getElementById("recipient-policy-management-title");fe&&(H.preventDefault(),fe.focus())},onOpenChange:H=>{H||ye()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyManagementDialogBackdrop",children:o("div",{"aria-busy":b||t.loading?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-management-title",tabIndex:-1,children:ne}),o(Zr,{ariaLabel:`Close ${ne}`,className:"modal-close-button recipient-policy-management-target",disabled:b,onClick:ye})]}),o("div",{className:"modal-body recipient-policy-management-selection",children:[o("p",{className:"small",id:"recipient-policy-management-description",children:Re}),ue?o("p",{"aria-live":"polite",role:t.loadError?"alert":"status",children:ue}):p&&d?o(Tk,{preview:d,projectLabels:N.current,recipientLabels:I.current,result:p}):d?o(kk,{preview:d,projectLabels:N.current,recipientLabels:I.current}):r.mode==="recipient-add"||r.mode==="recipient-manage"?o("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[o("legend",{children:O.legend}),de.length?de.map(H=>o(Nh,{checked:a.includes(H.canonicalProjectIdentity),description:H.description,disabled:b,label:H.displayName,onChange:()=>Ce(H.canonicalProjectIdentity)},H.canonicalProjectIdentity)):o("p",{className:"small",role:"status",children:r.mode==="recipient-add"?"No additional Projects are available.":"No Projects are available."})]}):o("fieldset",{className:"sync-dialog-radio-list",disabled:b,children:[o("legend",{children:O.legend}),x.length?x.map(H=>o(Nh,{checked:a.includes(H.key),description:H.description,disabled:b,label:H.label,onChange:()=>Ce(H.key)},H.key)):o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."})]}),p?null:o("p",{"aria-live":"polite",className:"small recipient-policy-management-status",role:"status",children:g}),f?o("p",{"aria-live":"assertive",role:"alert",children:f}):null,L?o("p",{"aria-live":"assertive",role:"alert",children:["This selection creates ",C.length.toLocaleString()," access changes. Review at most ",wh.toLocaleString()," changes at a time; reduce the selection and try again."]}):null]}),o("div",{className:"modal-footer recipient-policy-management-actions",children:[o("button",{className:"settings-button recipient-policy-management-target",disabled:b,onClick:d&&!p?()=>{u(null),I.current=new Map,N.current=new Map,h("")}:ye,type:"button",children:p?"Done":d?"Back":"Cancel"}),!p&&!ue?o("button",{className:"settings-button sync-dialog-confirm recipient-policy-management-target",disabled:b||!d&&(U||V||L),onClick:()=>{d?Pe():re()},type:"button",children:b?d?"Saving…":"Reviewing…":d?"Confirm changes":"Review changes"}):null]})]})})}function Th(e,t,n,r={}){He(o(Rk,{intent:n,options:r,projects:t}),e)}function Jo(e){return e.identity_source!=="unmapped"&&e.read_only!==!0}function Pk(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 Yo(e){const t=new Map;for(const n of e)Jo(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 Rh({detailRowCount:e=3,label:t}){return o(z,{children:[o("span",{className:"sr-only",role:"status",children:t}),o("div",{"aria-busy":"true",className:"loading-card-list",children:Array.from({length:2},(n,r)=>o("div",{"aria-hidden":"true",className:"loading-card",children:[o("div",{className:"loading-card-header",children:[o("span",{className:`loading-card-line loading-card-title ${r%2?"w-45":"w-60"}`}),o("span",{className:"loading-card-badge"})]}),o("div",{className:"loading-card-details",children:Array.from({length:e},(i,a)=>o("div",{className:"loading-card-detail",children:[o("span",{className:"loading-card-line loading-card-label"}),o("span",{className:`loading-card-line ${(r+a)%2?"w-45":"w-60"}`})]},a))})]},r))})]})}function Ak(e){return e.state!=="configured"}function Ph(e){return e?.items.filter(Ak)??[]}function Xo(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 Ek=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu,xk=/^(?:actor|device|identity|local):\S+$/iu,Dk=/^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu,Lk=/^pending[_-]\S+$/iu,$k=/^[a-f0-9]{12,64}$/iu;function Ml(e){return[Ek,xk,Dk,Lk,$k].some(t=>t.test(e))}function ai(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||Ml(t)?"":t}var oi=null,si=null;function Qo(e=[],t=""){if(si){const n=si(e,t);return n||(oi=null),n}return oi={projectIds:e,teammateName:t},window.location.hash="#projects",!0}function Ah(e){return!e.read_only&&e.identity_source!=="unmapped"&&e.memory_count!=null&&!e.guardrail_warnings.some(t=>t.requires_confirmation)}function Eh(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 Mk(e){const t=`share-project-${ur()}`,n=Ah(e.project);return o("label",{className:"sync-dialog-radio-option",htmlFor:t,children:[o("input",{checked:e.selected,disabled:!n,id:t,onChange:()=>e.onToggle(e.project.workspace_identity),type:"checkbox"}),o("span",{children:[o("strong",{children:e.project.display_project}),o("span",{className:"small",children:n?`${(e.project.memory_count??0).toLocaleString()} existing memories`:"Unavailable until this project identity is reviewed"})]})]})}function jk({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:[e.teammate.display_name," will receive:"]})}),e.teammate.match==="existing"?o("p",{className:"small",children:"This invitation will use the existing teammate."}):null,o("ul",{children:e.projects.map(t=>o("li",{children:[t.existing_memory_count.toLocaleString()," existing memories and future activity from ",t.display_name]},t.project_id))}),o("p",{children:o("strong",{children:"No other projects will be shared."})})]})}function Ok({projects:e,inventoryError:t}){const[n,r]=D(!1),[i,a]=D(""),[s,c]=D([]),[l,d]=D(null),[u,p]=D(null),[m,f]=D(null),[y,g]=D(!1),[h,b]=D(null),[w,_]=D(!1),I=Se(()=>e.filter(Ah),[e]);W(()=>{if(si=(P,F="")=>{if(t)return!1;const O=[...new Set(P)],G=O.some($=>!I.some(A=>A.workspace_identity===$));return a(F.trim()),c(G?[]:O),_(G),d(null),p(null),f(G?"The original project selection is no longer available. Refresh Projects and try again.":null),b(null),r(!0),!0},oi){const P=oi;oi=null,si(P.projectIds,P.teammateName)}return()=>{si=null}},[I,t]),W(()=>{t&&(oi=null,r(!1),a(""),c([]),d(null),p(null),f(null),b(null),_(!1))},[t]);const N=()=>{y||r(!1)},T=P=>{c(F=>F.includes(P)?F.filter(O=>O!==P):[...F,P])},x=async()=>{if(f(null),!i.trim()){f("Enter your teammate's name.");return}if(s.length===0){f("Select at least one project.");return}g(!0);try{d(await WC({teammate_name:i.trim(),project_ids:s}))}catch(P){f(Eh(P,"Unable to review this invitation."))}finally{g(!1)}},j=async()=>{if(l){f(null),g(!0);try{p(await zC({teammate_name:l.teammate.display_name,project_ids:l.projects.map(P=>P.project_id),reviewed_project_set_digest:l.reviewed_project_set_digest}))}catch(P){P instanceof Error&&P.message==="reviewed_project_set_changed"&&d(null),f(Eh(P,"Unable to create this invitation."))}finally{g(!1)}}},B=async()=>{if(u){f(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(P){f(P instanceof Error?P.message:"Unable to copy the invitation.")}}};return o(z,{children:[o("button",{"aria-describedby":t?"project-share-inventory-error":void 0,className:"settings-button",disabled:t||I.length===0,onClick:()=>si?.([]),type:"button",children:"Share projects"}),t?o("p",{className:"small",id:"project-share-inventory-error",role:"status",children:"The complete project list is unavailable. Refresh Projects to try again."}):null,n?o(gr,{ariaDescribedby:"project-share-description",ariaLabelledby:"project-share-title",contentClassName:"modal",contentId:"projectShareDialog",onOpenChange:P=>{P||N()},open:!0,overlayClassName:"modal-backdrop",overlayId:"projectShareDialogBackdrop",children:o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"project-share-title",children:"Share projects"}),o("button",{"aria-label":"Close Share projects",disabled:y,onClick:N,type:"button",children:"×"})]}),o("div",{"aria-busy":y,className:"modal-body",children:[o("p",{className:"small",id:"project-share-description",children:"Choose a teammate and the exact projects they may receive after accepting."}),u?o("div",{children:[o("p",{role:"status",children:["Invitation created for ",u.teammate.display_name,"."]}),o("p",{children:["Sharing starts after acceptance:"," ",u.projects.map(P=>P.display_name).join(", "),"."]}),o("p",{className:"small",children:["Invitation expires ",new Date(u.invite.expires_at).toLocaleString(),"."]}),o("button",{className:"settings-button",onClick:()=>{B()},type:"button",children:"Copy invite"}),h?o("p",{role:"status",children:h}):null]}):l?o(jk,{preview:l}):o(z,{children:[o("label",{className:"field",htmlFor:"project-share-teammate",children:[o("span",{children:"Who are you sharing with?"}),o("input",{autoFocus:!0,className:"sync-dialog-input",id:"project-share-teammate",maxLength:120,onInput:P=>a(P.currentTarget.value),type:"text",value:i})]}),o("fieldset",{className:"sync-dialog-radio-list",children:[o("legend",{children:"Select exact projects"}),e.map(P=>o(Mk,{onToggle:T,project:P,selected:s.includes(P.workspace_identity)},P.workspace_identity))]})]}),m?o("p",{role:"alert",children:m}):null]}),o("div",{className:"modal-footer",children:[o("button",{className:"settings-button",disabled:y,onClick:N,type:"button",children:u?"Done":"Cancel"}),u?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:y||w,onClick:()=>{l?j():x()},type:"button",children:y?l?"Creating invite…":"Reviewing…":l?"Create invite":"Review sharing"})]})]})}):null]})}function xh(e,t,n={}){He(o(Ok,{inventoryError:n.inventoryError===!0,projects:t}),e)}function jl(e){return ai(String(e??"").trim())}function ci(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.`:Ml(n)?`${t} must use a human-readable name.`:"":`${t} is required.`}function Fk(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 Zo(e,t){return e instanceof Error?e instanceof hm?{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 ca(e){return`${e.toLocaleString()} existing ${e===1?"memory":"memories"}`}function Bk({preview:e}){return e.projects.length===0?o("p",{className:"small",children:"No Projects are currently shared with this Team."}):o("ul",{children:e.projects.map(t=>o("li",{children:[o("strong",{children:t.displayName})," — ",ca(t.existingMemoryCount)," and future activity"]},t.canonicalProjectIdentity))})}function Uk({preview:e}){return o("div",{className:"sync-dialog-stack",children:[o("p",{children:o("strong",{children:["Current Projects for ",e.team?.displayName??"this Team"]})}),o(Bk,{preview:e}),o("p",{children:"Future Projects shared with this Team will also be inherited by this member."}),o("p",{children:o("strong",{children:"No other Projects will be shared through this invitation."})})]})}function qk({preview:e}){const t=e.projects.filter(r=>r.sources.some(i=>i.kind==="direct")),n=e.projects.filter(r=>r.sources.some(i=>i.kind==="team"));return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"add-device-direct-projects",children:[o("h3",{id:"add-device-direct-projects",children:"Direct Projects"}),t.length?o("ul",{children:t.map(r=>o("li",{children:[r.displayName," — ",ca(r.existingMemoryCount)," and future activity"]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No Projects are shared directly."})]}),o("section",{"aria-labelledby":"add-device-team-projects",children:[o("h3",{id:"add-device-team-projects",children:"Projects through Teams"}),n.length?o("ul",{children:n.map(r=>{const i=r.sources.filter(a=>a.kind==="team").map(a=>a.displayName);return o("li",{children:[r.displayName," — ",ca(r.existingMemoryCount)," and future activity",i.length?` through ${i.join(", ")}`:" through a Team"]},r.canonicalProjectIdentity)})}):o("p",{className:"small",children:"No Projects are inherited through Teams."})]}),o("section",{"aria-labelledby":"add-device-excluded-projects",children:[o("h3",{id:"add-device-excluded-projects",children:"Not included"}),e.excludedProjects.length?o("ul",{children:e.excludedProjects.map(r=>o("li",{children:[r.displayName," — ",ca(r.existingMemoryCount)]},r.canonicalProjectIdentity))}):o("p",{className:"small",children:"No other Projects are excluded."}),o("p",{className:"small",children:"This device will not receive the Projects listed here."})]}),e.projects.length>0?o("p",{className:"small",role:"note",children:"The lists above describe access, not delivery: Project data does not sync to the invited device until the Project owner’s device completes access setup for it. Until then, shared memories remain on the Identity’s existing devices."}):null]})}function Dh({preview:e}){return e.journey==="team"?o(Uk,{preview:e}):o(qk,{preview:e})}function Gk({error:e,name:t,onChange:n}){return o("section",{"aria-labelledby":"recipient-onboarding-name-title",children:[o("h3",{id:"recipient-onboarding-name-title",children:"Who will receive access"}),o("label",{className:"field",htmlFor:"recipient-onboarding-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":e?"recipient-onboarding-name-error":void 0,"aria-invalid":!!e,id:"recipient-onboarding-name",onInput:r=>n(r.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:t})]}),e?o("p",{className:"small",id:"recipient-onboarding-name-error",role:"alert",children:e}):null]})}function Hk({deviceName:e,deviceNameError:t,invite:n,onDeviceNameChange:r,onRecipientNameChange:i,recipientName:a,recipientNameError:s}){const c=n.projects??[];return o("div",{className:"sync-dialog-stack",children:[o("section",{"aria-labelledby":"project-share-invitation-recipient",children:[o("h3",{id:"project-share-invitation-recipient",children:"Who will receive access"}),o("p",{children:"Review these display names before importing the invitation."}),o("label",{className:"field",htmlFor:"project-share-recipient-name",children:[o("span",{children:"Identity display name"}),o("input",{"aria-describedby":s?"project-share-recipient-name-error":void 0,"aria-invalid":!!s,id:"project-share-recipient-name",onInput:l=>i(l.currentTarget.value),placeholder:"Your name — e.g. Alex Rivera",value:a})]}),s?o("p",{className:"small",id:"project-share-recipient-name-error",role:"alert",children:s}):null,o("label",{className:"field",htmlFor:"project-share-device-name",children:[o("span",{children:"Device display name"}),o("input",{"aria-describedby":t?"project-share-device-name-error":void 0,"aria-invalid":!!t,id:"project-share-device-name",onInput:l=>r(l.currentTarget.value),placeholder:"This device — e.g. Work Laptop",value:e})]}),t?o("p",{className:"small",id:"project-share-device-name-error",role:"alert",children:t}):null]}),o("section",{"aria-labelledby":"project-share-invitation-projects",children:[o("h3",{id:"project-share-invitation-projects",tabIndex:-1,children:"Exact Projects shared directly"}),n.inviter_name?o("p",{children:["Invitation from ",n.inviter_name,"."]}):null,o("p",{children:["You will receive ",o("strong",{children:"direct access only"})," to the exact Projects listed below."]}),c.length?o("ul",{children:c.map((l,d)=>o("li",{children:[o("strong",{children:l.display_name})," —"," ",ca(l.existing_memory_count)," and future activity"]},`${l.display_name}:${d}`))}):o("p",{role:"alert",children:"Project details are unavailable. Ask the owner to create a new invitation before accepting."})]}),o("p",{children:o("strong",{children:"Accepting this invitation does not join a Team."})}),o("p",{children:o("strong",{children:"No other Projects are included."})})]})}function Kk({result:e}){const t=e.restart_required===!0||e.setup_state==="restart_required",n=e.type==="project_share"&&e.status==="pending_setup";return o("div",{className:"sync-dialog-stack",children:[o("h3",{id:"project-share-invitation-result",tabIndex:-1,children:"Project invitation accepted"}),t?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending and codemem must be restarted."})," Restart codemem to start the sync service. Access remains pending until setup and the first sync finish."]}):n?o("p",{role:"status",children:[o("strong",{children:"Project setup is pending."})," The owner still needs to finish access setup, and the Projects will appear after the first sync completes."]}):o("p",{role:"status",children:"The invitation was accepted, but Project setup status could not be confirmed. Check Sync before expecting Project data."})]})}function Vk({result:e}){const t=e.kind==="team_member"?"Team invitation accepted":"Device added";return o("section",{"aria-describedby":[e.restartRequired?"recipient-invitation-result-detail":null,e.deliveryPending?"recipient-invitation-result-delivery":null].filter(Boolean).join(" ")||void 0,"aria-labelledby":"recipient-invitation-result-title",className:"recipient-policy-invitation-result",id:"recipient-invitation-result",tabIndex:-1,children:[o("span",{"aria-hidden":"true",className:"recipient-policy-invitation-result-mark",children:"✓"}),o("div",{className:"recipient-policy-invitation-result-copy",children:[o("h3",{id:"recipient-invitation-result-title",children:t}),e.restartRequired?o("p",{id:"recipient-invitation-result-detail",children:e.detail}):null,e.deliveryPending?o("p",{className:"small",id:"recipient-invitation-result-delivery",children:"Existing shared Projects do not sync to this device until the Project owner’s device completes access setup for it."}):null]})]})}function Lh(e,t){return e==="team_member"?{kind:e,policy_team_id:t}:{kind:e,target_identity_id:t}}function Wk({intent:e}){const t=e.teams.filter(Z=>Z.status==="active"),n=e.identities.filter(Z=>Z.status==="active"),[r,i]=D(null),[a,s]=D("team_member"),[c,l]=D(t[0]?.teamId??""),[d,u]=D(""),[p,m]=D(null),[f,y]=D(null),[g,h]=D(null),[b,w]=D(null),[_,I]=D(""),[N,T]=D(""),[x,j]=D(""),[B,P]=D(null),[F,O]=D(!1),[G,$]=D(""),[A,E]=D(""),C=q(null),L=q(0),U=q(""),V=q(!1);W(()=>{if(b){document.getElementById("recipient-invitation-result")?.focus();return}if(g){document.getElementById("project-share-invitation-result")?.focus();return}f?.kind==="project_share_invite"&&document.getElementById("project-share-invitation-projects")?.focus()},[f,g,b]);const de=()=>{L.current+=1,U.current="",V.current=!1,u(""),m(null),y(null),h(null),w(null),I(""),T(""),j(""),P(null),$(""),E("")},ie=(Z,te)=>{de(),C.current=te,i(Z)},ne=()=>{F||(i(null),de())},Re=Z=>{L.current+=1,U.current=Z,u(Z)},ye=Z=>{s(Z),l(Z==="team_member"?t[0]?.teamId??"":n[0]?.identityId??""),de()},Ce=async()=>{if(c){O(!0),E(""),$("Reviewing invitation…");try{m((await GC(Lh(a,c))).preview),$("Review ready. Confirm the invitation details.")}catch(Z){E(Zo(Z,"Unable to review this invitation.")),$("")}finally{O(!1)}}},re=async()=>{if(p){O(!0),E(""),$("Creating invitation…");try{P(await HC({...Lh(a,c),reviewed_onboarding_digest:p.reviewedOnboardingDigest})),$("Invitation created.")}catch(Z){Z instanceof Error&&Z.message==="reviewed_onboarding_stale"&&m(null),E(Zo(Z,"Unable to create this invitation.")),$("")}finally{O(!1)}}},Pe=async()=>{const Z=U.current.trim(),te=L.current;if(!Z){E("Paste an invitation first.");return}const Qe=()=>L.current===te&&U.current.trim()===Z;O(!0),E(""),$("Reviewing invitation…");try{const $e=await gm(Z);if(!Qe())return;y($e),$e.kind==="team_member"?I(jl($e.recipient_name)):$e.kind==="project_share_invite"&&(T(jl($e.recipient_name)),j(jl($e.device_name))),$($e.kind==="add_device"?($e.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.":$e.kind==="team_member"?"Review ready. Confirm before accepting.":$e.kind==="project_share_invite"?"Review ready. Confirm the exact Projects before accepting.":"Open Advanced, then Sync, to review and import this legacy invitation.")}catch($e){if(!Qe())return;E(Zo($e,"Unable to review this invitation.")),$("")}finally{O(!1)}},ue=async()=>{if(!(F||V.current||b)&&!(!f||f.kind==="legacy_team_invite")&&!(f.kind==="project_share_invite"&&!(f.projects?.length??0))&&!(f.kind==="project_share_invite"&&(ci(N,"Identity display name")||ci(x,"Device display name")))&&!(f.kind==="team_member"&&ci(_,"Identity display name"))){V.current=!0,O(!0),E(""),$("Accepting invitation…");try{const Z=f.kind==="project_share_invite"?await Wc(d.trim(),{recipient_name:N.trim(),device_name:x.trim()},f.kind):await Wc(d.trim(),{...f.kind==="team_member"?{recipient_name:_.trim()}:{},device_name:f.device_name,reviewed_onboarding_digest:f.onboarding.reviewedOnboardingDigest},f.kind);if(f.kind==="project_share_invite")h(Fk(Z)),$("");else{const te=f.kind;w({kind:te,restartRequired:Z.restart_required===!0||Z.setup_state==="restart_required",detail:te==="team_member"?"Restart codemem to finish joining this Team.":"Restart codemem to finish adding this device.",deliveryPending:te==="add_device"&&(f.onboarding?.projects?.length??0)>0}),$("")}}catch(Z){V.current=!1,E(Zo(Z,f.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.")),$("")}finally{O(!1)}}},H=async()=>{const Z=B?.invite.link||B?.invite.encoded||"";if(!Z){E("The invitation text is unavailable.");return}try{await navigator.clipboard.writeText(Z),$("Invitation copied.")}catch{E("Unable to copy the invitation.")}},fe=f?.kind==="team_member"||f?.kind==="add_device"?f.onboarding:null,ae=f?.kind==="project_share_invite"?f:null,Te=f?.kind==="team_member"?ci(_,"Identity display name"):"",ce=ae?ci(N,"Identity display name"):"",Be=ae?ci(x,"Device display name"):"";return o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:[o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Create an invitation"}),o("p",{children:"Invite a Team member, add a device, or share an exact set of Projects."}),o("div",{className:"peer-actions recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:t.length===0,onClick:Z=>{ye("team_member"),ie("create",Z.currentTarget)},type:"button",children:"Invite Team member"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",disabled:n.length===0,onClick:Z=>{ye("add_device"),ie("create",Z.currentTarget)},type:"button",children:"Add a device"}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>Qo(),type:"button",children:"Share exact Projects"})]}),t.length===0&&n.length===0?o("p",{className:"small",role:"status",children:"No active Teams or Identities are available."}):null]}),o("article",{className:"peer-card peer-card--padded recipient-policy-sharing-card",children:[o("h3",{children:"Accept an invitation"}),o("p",{children:"Review Team membership, device access, or exact Project access before accepting."}),o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:Z=>ie("accept",Z.currentTarget),type:"button",children:"Review invitation"}),o("p",{className:"small",children:"Legacy invitation import remains under Advanced, in Sync."})]}),r?o(gr,{ariaDescribedby:"recipient-invitation-description",ariaLabelledby:"recipient-invitation-title",contentClassName:"modal recipient-policy-invitation-dialog",contentId:"recipientInvitationDialog",onCloseAutoFocus:Z=>{Z.preventDefault(),C.current?.focus(),C.current=null},onOpenAutoFocus:Z=>{Z.preventDefault(),document.getElementById("recipient-invitation-title")?.focus()},onOpenChange:Z=>{Z||ne()},open:!0,overlayClassName:"modal-backdrop",overlayId:"recipientInvitationDialogBackdrop",children:o("div",{"aria-busy":F,className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-invitation-title",tabIndex:-1,children:b?"Invitation accepted":r==="create"?"Create invitation":"Review invitation"}),o(Zr,{ariaLabel:"Close invitation",className:"modal-close-button recipient-policy-sharing-target-24",disabled:F,onClick:ne})]}),o("div",{className:"modal-body",children:[o("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&&!B?o("label",{className:"field",htmlFor:"recipient-invitation-target",children:[o("span",{children:a==="team_member"?"Team":"Identity"}),o("select",{id:"recipient-invitation-target",onChange:Z=>l(Z.currentTarget.value),value:c,children:(a==="team_member"?t:n).map(Z=>o("option",{value:"teamId"in Z?Z.teamId:Z.identityId,children:Z.displayName},"teamId"in Z?Z.teamId:Z.identityId))})]}):r==="accept"&&!f&&!b?o("label",{className:"field",htmlFor:"recipient-invitation-value",children:[o("span",{children:"Invitation"}),o("textarea",{id:"recipient-invitation-value",onInput:Z=>{Re(Z.currentTarget.value),y(null),h(null),$(""),E("")},rows:5,value:d})]}):null,p?o(Dh,{preview:p}):null,fe&&!b?o(Dh,{preview:fe}):null,f?.kind==="team_member"&&!b?o(Gk,{error:Te,name:_,onChange:Z=>{I(Z),E("")}}):null,ae&&!g?o(Hk,{deviceName:x,deviceNameError:Be,invite:ae,onDeviceNameChange:Z=>{j(Z),E("")},onRecipientNameChange:Z=>{T(Z),E("")},recipientName:N,recipientNameError:ce}):null,g?o(Kk,{result:g}):null,b?o(Vk,{result:b}):null,B?o("div",{children:[o("p",{children:"Share the invitation with the recipient."}),o("button",{className:"settings-button",onClick:()=>{H()},type:"button",children:"Copy invitation"})]}):null,f?.kind==="legacy_team_invite"?o("p",{children:"Open Advanced, then Sync, to review and import this legacy invitation."}):null,o("p",{"aria-live":"polite",className:"small",role:"status",children:G}),A?o("p",{"aria-live":"assertive",role:"alert",children:A}):null]}),o("div",{className:"modal-footer recipient-policy-sharing-responsive-actions",children:[o("button",{className:"settings-button",disabled:F,onClick:ne,type:"button",children:B||g||b?"Done":"Cancel"}),r==="create"&&!B?o("button",{className:"settings-button sync-dialog-confirm",disabled:F||!c,onClick:()=>{p?re():Ce()},type:"button",children:F?"Working…":p?"Create invitation":"Review invitation"}):r==="accept"&&!f&&!b?o("button",{className:"settings-button sync-dialog-confirm",disabled:F,onClick:()=>{Pe()},type:"button",children:F?"Reviewing…":"Review invitation"}):fe&&!b||ae&&!g?o("button",{className:"settings-button sync-dialog-confirm",disabled:F||!!(f?.kind==="team_member"&&Te)||!!(ae&&(!ae.projects?.length||ce||Be)),onClick:()=>{ue()},type:"button",children:F?"Accepting…":ae?"Accept Project access":"Accept invitation"}):null]})]})}):null]})}function zk(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.":Ml(t)?"Enter a human-readable Team name.":"":"Team name is required."}function Jk(e){return e instanceof So?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 Yk({descriptionId:e,disabled:t,displayName:n,onRenamed:r,renameTeam:i=vC,teamId:a}){const[s,c]=D(!1),[l,d]=D(n),[u,p]=D(!1),[m,f]=D(""),[y,g]=D(""),h=q(null),b=q(null),w=q(null);W(()=>{y&&!u&&w.current?.focus()},[u,y]);const _=()=>{u||(c(!1),f(""),g(""))},I=async()=>{const N=zk(l);if(N){f(N);return}if(!u){p(!0),f(""),g("");try{const T=await i({teamId:a,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){f(Jk(T))}finally{p(!1)}}};return o(z,{children:[o("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),f(""),g(""),c(!0))},ref:h,type:"button",children:"Team settings"}),o(gr,{ariaDescribedby:"recipient-policy-team-settings-description",ariaLabelledby:"recipient-policy-team-settings-title",contentClassName:"modal recipient-policy-team-settings-dialog",contentId:"recipientPolicyTeamSettingsDialog",onCloseAutoFocus:N=>{N.preventDefault(),h.current?.focus()},onEscapeKeyDown:N=>{u&&N.preventDefault()},onInteractOutside:N=>{u&&N.preventDefault()},onOpenAutoFocus:N=>{N.preventDefault(),b.current?.focus(),b.current?.select()},onOpenChange:N=>{N||_()},open:s,overlayClassName:"modal-backdrop",overlayId:"recipientPolicyTeamSettingsDialogBackdrop",children:o("div",{"aria-busy":u?"true":"false",className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"recipient-policy-team-settings-title",children:"Team settings"}),o(Zr,{ariaLabel:"Close Team settings",disabled:u,onClick:_})]}),o("div",{className:"modal-body",children:[o("p",{className:"small",id:"recipient-policy-team-settings-description",children:"Change the name shown for this Team in Sharing."}),o("label",{className:"form-field",htmlFor:"recipient-policy-team-settings-name",children:[o("span",{children:"Team name"}),o("input",{disabled:u||!!y,id:"recipient-policy-team-settings-name",maxLength:120,onInput:N=>{d(N.currentTarget.value),f("")},ref:b,value:l})]}),u?o("p",{"aria-live":"polite",role:"status",children:"Saving Team name…"}):null,m?o("p",{"aria-live":"assertive",role:"alert",children:m}):null,y?o("p",{"aria-live":"polite",role:"status",children:y}):null]}),o("div",{className:"modal-footer recipient-policy-team-settings-actions",children:[o("button",{className:"settings-button",disabled:u,onClick:_,ref:w,type:"button",children:y?"Done":"Cancel"}),y?null:o("button",{className:"settings-button sync-dialog-confirm",disabled:u||!l.trim()||l.trim()===n,onClick:()=>{I()},type:"button",children:u?"Saving…":m?"Try again":"Save"})]})]})})]})}var $h={needs_setup:"Ready to review",in_progress:"Migration in progress",stale:"Migration review needs update"},Mh={needs_setup:"needs_attention",in_progress:"suggested",stale:"needs_attention"},Ol={role:"list"},Fl={role:"listitem"};function Xk(e){return typeof e=="string"&&Object.hasOwn($h,e)?$h[e]:"Ready to review"}function Qk(e){return typeof e=="string"&&Object.hasOwn(Mh,e)?Mh[e]:"needs_attention"}function Zk(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 eT({candidates:e,onOpenTeamSetup:t}){if(e.length===0)return null;const n=Zk(e);return o("aside",{"aria-labelledby":"sharing-team-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-team-setup-heading",children:"Legacy groups to migrate"}),o("p",{children:"Current devices are proposed for review. No Team membership or Project access changes happen until you finish the migration."}),o("ul",{...Ol,className:"recipient-policy-sharing-team-setup-list","aria-label":"Team setup status",children:n.map(r=>v("li",{...Fl,className:"recipient-policy-sharing-team-setup-group",key:r.displayName},r.candidates.length>1?o("div",{className:"recipient-policy-sharing-team-setup-group-title",children:[o("strong",{children:r.displayName}),o("span",{className:"small",children:[r.candidates.length," Teams"]})]}):null,o("div",{className:"recipient-policy-sharing-team-setup-rows",children:r.candidates.map((i,a)=>{const s=`${a+1} of ${r.candidates.length}`,c=`${Mt(i.deviceCount,"device")}, ${Mt(i.projectCount,"Project")}`,l=r.candidates.length>1?`Review and migrate ${r.displayName} ${s}: ${c}`:`Review and migrate ${i.displayName}: ${c}`;return o("div",{className:"recipient-policy-sharing-team-setup-row",children:[o("span",{className:"recipient-policy-sharing-team-setup-label",children:[r.candidates.length>1?o("span",{className:"small",children:["Team ",s," · ",c]}):o(z,{children:[o("strong",{children:i.displayName}),o("span",{className:"small",children:[" · ",c]})]}),o("span",{"aria-hidden":"true",className:"recipient-policy-sharing-team-setup-separator",children:[" ","—"," "]})]}),o("span",{className:"recipient-policy-sharing-team-setup-status",children:o("span",{className:`project-status-badge ${Qk(i.status)}`.trim(),children:Xk(i.status)})}),o("span",{className:"recipient-policy-sharing-team-setup-action",children:t?o("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 yr=[{id:"teams",label:"Teams"},{id:"identities",label:"Identities"},{id:"received",label:"Received"},{id:"invitations",label:"Invitations"}];function Mt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function tT(e,t){return e.length?e.join(", "):t}var jh=3;function Bl({empty:e,label:t,names:n}){return n.length===0?o(z,{children:e}):n.length<=jh?o(z,{children:tT(n,e)}):o(z,{children:[n.slice(0,jh).join(", "),o("span",{"aria-hidden":"true",children:", …"}),o("details",{className:"recipient-policy-sharing-name-details",children:[o("summary",{children:["View all ",Mt(n.length,t)]}),o("ul",{...Ol,"aria-label":`All ${t}s`,children:n.map((r,i)=>v("li",{...Fl,key:`${i}-${r}`},r))})]})]})}function Oh(e,t){return[...new Set(e)].map(n=>({canonicalId:n,displayName:t.get(n)?.displayName??"Unavailable Project"}))}var Fh=3;function Bh({empty:e,identities:t,qualifier:n}){if(t.length===0)return o(z,{children:e});const r=hk(t),i=s=>s.identityCount>1?`${s.displayName} (${Mt(s.identityCount,"identity","identities")})`:s.displayName,a=r.slice(0,Fh);return o(z,{children:[Mt(t.length,`${n} Project identity`,`${n} Project identities`)," ","— ",a.map(i).join(", "),r.length>Fh?o(z,{children:[o("span",{"aria-hidden":"true",children:", …"}),o("details",{className:"recipient-policy-sharing-project-details",children:[o("summary",{children:["View all ",Mt(r.length,"Project name group")]}),o("ul",{...Ol,"aria-label":`All ${n} Project identity groups`,children:r.map(s=>v("li",{...Fl,key:s.displayName},i(s)))})]})]}):null]})}function Uh({descriptionId:e,disabled:t,displayName:n,recipient:r}){const i=()=>{oa({mode:"recipient-manage",recipient:r})},a=()=>{oa({mode:"recipient-add",recipient:r})};return o(z,{children:[o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:[o("button",{"aria-describedby":e,"aria-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||a()},type:"button",children:"Add projects"}),o("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"})]}),o("p",{className:"small",id:e,children:t?"Team and Identity Project changes are disabled until a refresh succeeds.":"Add projects only adds the selected Projects after you preview the exact changes."})]})}function nT({disableMutations:e,intent:t,onTeamRenamed:n,projects:r,renameTeam:i}){const a=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 a.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Teams are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:a.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??""),m=new Set(t.identityDevices.filter(h=>h.status==="active"&&u.includes(h.identityId)).map(h=>h.deviceId)).size,f=Oh(t.projectRecipients.filter(h=>h.status==="active"&&h.recipientKind==="team"&&h.teamId===l.teamId).map(h=>h.canonicalProjectIdentity),c),y=`recipient-policy-sharing-team-title-${d}`,g=`recipient-policy-sharing-team-add-description-${d}`;return o("article",{"aria-labelledby":y,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-team-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:y,children:l.displayName}),o("span",{className:"badge actor-badge",children:"Team"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Current members"}),o("dd",{children:[Mt(p.length,"active member")," —"," ",o(Bl,{empty:"No active members",label:"member",names:p})]})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:Mt(m,"active registered device")})]}),o("div",{children:[o("dt",{children:"Shared projects"}),o("dd",{children:o(Bh,{empty:"No Projects shared",identities:f,qualifier:"active shared"})})]}),o("div",{children:[o("dt",{children:"Future Team members"}),o("dd",{children:"Yes — future Team members inherit the Team’s shared Projects."})]})]}),o(Uh,{descriptionId:g,disabled:e,displayName:l.displayName,recipient:{recipientKind:"team",teamId:l.teamId}}),o("div",{className:"peer-actions recipient-policy-sharing-actions recipient-policy-sharing-responsive-actions",children:o(Yk,{descriptionId:g,disabled:e,displayName:l.displayName,onRenamed:n,renameTeam:i,teamId:l.teamId})})]},l.teamId)})})}function rT({disableMutations:e,intent:t,projects:n}){const r=t.identities.filter(s=>s.status==="active"),i=new Map(t.teams.filter(s=>s.status==="active").map(s=>[s.teamId,s])),a=new Map(n.map(s=>[s.canonicalProjectIdentity,s]));return r.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No active Identities are available for Project sharing."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:r.map((s,c)=>{const l=t.identityDevices.filter(f=>f.status==="active"&&f.identityId===s.identityId),d=[...new Set(t.teamMemberships.filter(f=>f.status==="active"&&f.identityId===s.identityId&&i.has(f.teamId)).map(f=>f.teamId))].map(f=>i.get(f)?.displayName??""),u=Oh(t.projectRecipients.filter(f=>f.status==="active"&&f.recipientKind==="identity"&&f.identityId===s.identityId).map(f=>f.canonicalProjectIdentity),a),p=`recipient-policy-sharing-identity-title-${c}`,m=`recipient-policy-sharing-identity-add-description-${c}`;return o("article",{"aria-labelledby":p,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-identity-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:p,children:s.displayName}),o("span",{className:"badge actor-badge local",children:"Local identity"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Verification"}),o("dd",{children:"Local identity"})]}),o("div",{children:[o("dt",{children:"Registered devices"}),o("dd",{children:[Mt(l.length,"active registered device")," —"," ",o(Bl,{empty:"No active devices",label:"device",names:l.map(f=>f.displayName)})]})]}),o("div",{children:[o("dt",{children:"Team memberships"}),o("dd",{children:[Mt(d.length,"active Team membership")," —"," ",o(Bl,{empty:"No active Team memberships",label:"Team membership",names:d})]})]}),o("div",{children:[o("dt",{children:"Directly shared projects"}),o("dd",{children:o(Bh,{empty:"No Projects shared directly",identities:u,qualifier:"directly shared active"})})]})]}),o("p",{className:"small",children:"Team Projects are shown on Team cards because per-device eligibility cannot be inferred from Identity membership alone."}),o(Uh,{descriptionId:m,disabled:e,displayName:s.displayName,recipient:{recipientKind:"identity",identityId:s.identityId}})]},s.identityId)})})}function iT({received:e}){return e.length===0?o("p",{className:"small recipient-policy-sharing-empty",role:"status",children:"No received Projects on this device. Accepted invitations appear here once their first sync completes."}):o("div",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:e.map((t,n)=>{const r=`recipient-policy-sharing-received-title-${n}`;return o("article",{"aria-labelledby":r,className:"peer-card peer-card--padded recipient-policy-sharing-card recipient-policy-sharing-received-card",children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:r,children:t.displayName}),o("span",{className:"badge actor-badge",children:"Received"})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Memories on this device"}),o("dd",{children:Mt(t.existingMemoryCount,"memory","memories")})]}),o("div",{children:[o("dt",{children:"Latest activity"}),o("dd",{children:t.latestSessionAt?new Date(t.latestSessionAt).toLocaleString():"No recent sessions"})]})]}),o("p",{className:"small",children:"This Project is received from another device. Access is managed where the Project is shared from; this device keeps it read-only."})]},t.canonicalProjectIdentity)})})}function aT({intent:e,options:t,projects:n}){const[r,i]=D(()=>e.teams.some(f=>f.status==="active")?"teams":"identities"),a=q(t.loading===!0||t.loadError===!0),s=q([]),c=Ph(t.deviceInventory),l=c.length,d=t.coordinatorEnrollmentIssueCount??0,u=e.teams.some(f=>f.status==="active");W(()=>{if(a.current&&!t.loading&&!t.loadError){a.current=!1,i(u?"teams":"identities");return}u||i(f=>f==="teams"?"identities":f)},[u,t.loadError,t.loading]);const p=f=>{const y=yr[f];y&&(i(y.id),s.current[f]?.focus())},m=(f,y)=>{let g=null;f.key==="ArrowRight"?g=(y+1)%yr.length:f.key==="ArrowLeft"?g=(y-1+yr.length)%yr.length:f.key==="Home"?g=0:f.key==="End"&&(g=yr.length-1),g!==null&&(f.preventDefault(),p(g))};return o("section",{className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("header",{className:"recipient-policy-sharing-header",children:[o("h2",{children:"Sharing"}),o("p",{className:"small",children:"See who receives Projects, how Team membership carries Project access, and where to make changes."})]}),o(eT,{candidates:t.teamSetupSummary?.candidates??[],onOpenTeamSetup:t.onOpenTeamSetup}),t.teamSetupLoading&&!t.teamSetupSummary?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Team setup status is loading."}):null,t.teamSetupUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:t.teamSetupSummary?"Team setup status is temporarily unavailable. The previous Team setup status is being shown.":"Team setup status is temporarily unavailable."}):null,t.deviceInventoryUnavailable?o("p",{"aria-live":"polite",className:"small recipient-policy-sharing-empty",role:"status",children:"Device Identity information is unavailable. Devices needing setup or review cannot be shown until a refresh succeeds."}):null,l>0&&!t.deviceInventoryUnavailable?o("aside",{"aria-labelledby":"sharing-device-setup-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-device-setup-heading",children:"Identity setup needed"}),o("p",{children:[l.toLocaleString()," ",l===1?"device needs":"devices need"," setup, pairing, or review before ownership can be shown accurately."]}),o("p",{className:"small",children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(c[0]?.deviceId),type:"button",children:"Review devices"}):null]}):null,d>0?o("aside",{"aria-labelledby":"sharing-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"sharing-coordinator-reconciliation-heading",children:"Device setup reconciliation needs attention"}),o("p",{children:[d.toLocaleString()," coordinator enrollment",d===1?" could":"s could"," not be safely reconciled. Sharing remains unchanged until the device evidence is valid."]}),o("p",{className:"small",children:"Coordinator groups are discovery boundaries, not policy Teams, and do not prove device ownership."}),t.onReviewDevices?o("button",{className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onReviewDevices?.(),type:"button",children:"Review devices"}):null]}):null,t.refreshError?o("p",{"aria-live":"assertive",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,o("div",{"aria-label":"Sharing views",className:"recipient-policy-sharing-tabs recipient-policy-sharing-responsive-tabs",role:"tablist",children:yr.map((f,y)=>o("button",{"aria-controls":`recipient-policy-sharing-panel-${f.id}`,"aria-selected":r===f.id,className:`tab-btn recipient-policy-sharing-tab recipient-policy-sharing-target recipient-policy-sharing-target-24${r===f.id?" active":""}`,id:`recipient-policy-sharing-tab-${f.id}`,onClick:()=>i(f.id),onKeyDown:g=>m(g,y),ref:g=>{s.current[y]=g},role:"tab",tabIndex:r===f.id?0:-1,type:"button",children:f.label},f.id))}),yr.map(f=>o(z,{children:o("div",{"aria-labelledby":`recipient-policy-sharing-tab-${f.id}`,className:"recipient-policy-sharing-panel",hidden:r!==f.id,id:`recipient-policy-sharing-panel-${f.id}`,role:"tabpanel",tabIndex:0,children:t.loading?r===f.id?o(Rh,{detailRowCount:4,label:"Loading Sharing details"}):null:t.loadError?r===f.id?o("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:f.id==="teams"?o(nT,{disableMutations:t.refreshError===!0,intent:e,onTeamRenamed:t.onTeamRenamed,projects:n,renameTeam:t.renameTeam}):f.id==="identities"?o(rT,{disableMutations:t.refreshError===!0,intent:e,projects:n}):f.id==="received"?o(iT,{received:t.received??[]}):o(Wk,{intent:e})})},f.id))]})}function oT(e,t,n,r={}){He(o(aT,{intent:n,options:r,projects:t}),e)}var Ul={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]};async function sT(){const e=[];let t=0;for(;;){const n=await Wi({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return{manageable:Yo(e),received:Pk(e)}}var cT={loadDeviceInventory:Qc,loadIntent:Xc,loadProjects:sT,loadSyncStatus:Co,loadTeamSetupSummary:Nm,mountManagement:Th,mountSharing:oT};function lT(e={},t={}){const n={...cT,...e};let r=0,i=null,a=0,s,c,l=!1,d=!1,u=!1,p=!1,m=null;const f=(g={})=>{const h=y(++r,g);return i=h,h};async function y(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=m;n.mountSharing(b,E?.inventory.manageable??[],E?.intent??Ul,E?{coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:p,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>f({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)),[N,T,x,j]=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 B=x.status==="rejected";x.status==="fulfilled"&&(s=x.value),j.status==="fulfilled"&&(a=Dm(j.value));let P,F,O;const G=N.status==="fulfilled"&&T.status==="fulfilled";if(u=!G,p=B,G){const E=N.value,C=T.value;m={intent:C,inventory:E},P=E.manageable,F=C,O={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:B,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>f({requireTeamSetupSummary:!0}),received:E.received},w&&n.mountManagement(w,E.manageable,C,{onCommitted:async()=>{await f()}})}else if(m){const E=m;P=E.inventory.manageable,F=E.intent,O={coordinatorEnrollmentIssueCount:a,deviceInventory:s,deviceInventoryUnavailable:B,onOpenTeamSetup:t.onOpenTeamSetup,onReviewDevices:t.onReviewDevices,onTeamRenamed:()=>f({requireTeamSetupSummary:!0}),received:E.inventory.received,refreshError:!0}}else P=[],F=Ul,O={deviceInventoryUnavailable:B,loadError:!0};const $=()=>{n.mountSharing(b,P,F,{...O,teamSetupSummary:c,teamSetupLoading:l,teamSetupUnavailable:d})};if($(),_=$,!G&&w&&n.mountManagement(w,[],Ul,{loadError:!0}),!h.requireTeamSetupSummary)return G;const A=await I;return g!==r?!1:G&&A}return f}var dT=Symbol.for("preact-signals");function es(){if(mn>1)mn--;else{var e,t=!1;for((function(){var i=ns;for(ns=void 0;i!==void 0;)i.S.v===i.v&&(i.S.i=i.i),i=i.o})();la!==void 0;){var n=la;for(la=void 0,ts++;n!==void 0;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&Hh(n))try{n.c()}catch(i){t||(e=i,t=!0)}n=r}}if(ts=0,mn--,t)throw e}}function uT(e){if(mn>0)return e();Gl=++pT,mn++;try{return e()}finally{es()}}var Oe=void 0;function ql(e){var t=Oe;Oe=void 0;try{return e()}finally{Oe=t}}var qh,la=void 0,mn=0,ts=0,pT=0,Gl=0,ns=void 0,rs=0;function Gh(e){if(Oe!==void 0){var t=e.n;if(t===void 0||t.t!==Oe)return t={i:0,S:e,p:Oe.s,n:void 0,t:Oe,e:void 0,x:void 0,r:t},Oe.s!==void 0&&(Oe.s.n=t),Oe.s=t,e.n=t,32&Oe.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=Oe.s,t.n=void 0,Oe.s.n=t,Oe.s=t),t}}function et(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}et.prototype.brand=dT,et.prototype.h=function(){return!0},et.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:ql(function(){var r;(r=t.W)==null||r.call(t)}))},et.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&&ql(function(){var i;(i=t.Z)==null||i.call(t)}))}},et.prototype.subscribe=function(e){var t=this;return da(function(){var n=t.value,r=Oe;Oe=void 0;try{e(n)}finally{Oe=r}},{name:"sub"})},et.prototype.valueOf=function(){return this.value},et.prototype.toString=function(){return this.value+""},et.prototype.toJSON=function(){return this.value},et.prototype.peek=function(){var e=this;return ql(function(){return e.value})},Object.defineProperty(et.prototype,"value",{get:function(){var e=Gh(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){mn!==0&&ts===0&&n.l!==Gl&&(n.l=Gl,ns={S:n,v:n.v,i:n.i,o:ns})})(this),this.v=e,this.i++,rs++,mn++;try{for(var t=this.t;t!==void 0;t=t.x)t.t.N()}finally{es()}}}});function Hl(e,t){return new et(e,t)}function Hh(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 Kh(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 Vh(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 br(e,t){et.call(this,void 0),this.x=e,this.s=void 0,this.g=rs-1,this.f=4,this.W=t?.watched,this.Z=t?.unwatched,this.name=t?.name}br.prototype=new et,br.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===rs))return!0;if(this.g=rs,this.f|=1,this.i>0&&!Hh(this))return this.f&=-2,!0;var e=Oe;try{Kh(this),Oe=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 Oe=e,Vh(this),this.f&=-2,!0},br.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)}et.prototype.S.call(this,e)},br.prototype.U=function(e){if(this.t!==void 0&&(et.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)}},br.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(br.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=Gh(this);if(this.h(),e!==void 0&&(e.i=this.i),16&this.f)throw this.v;return this.v}});function Wh(e,t){return new br(e,t)}function zh(e){var t=e.m;if(e.m=void 0,typeof t=="function"){mn++;var n=Oe;Oe=void 0;try{t()}catch(r){throw e.f&=-2,e.f|=8,Kl(e),r}finally{Oe=n,es()}}}function Kl(e){for(var t=e.s;t!==void 0;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,zh(e)}function mT(e){if(Oe!==this)throw new Error("Out-of-order effect");Vh(this),Oe=e,this.f&=-2,8&this.f&&Kl(this),es()}function li(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=t?.name,qh&&qh.push(this)}li.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()}},li.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,zh(this),Kh(this),mn++;var e=Oe;return Oe=this,mT.bind(this,e)},li.prototype.N=function(){2&this.f||(this.f|=2,this.u=la,la=this)},li.prototype.d=function(){this.f|=8,1&this.f||Kl(this)},li.prototype.dispose=function(){this.d()};function da(e,t){var n=new li(e,t);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var Jh,Vl,is,fT=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,eU=[],Yh=[];da(function(){Jh=this.N})();function di(e,t){me[e]=t.bind(null,me[e]||function(){})}function as(e){if(is){var t=is;is=void 0,t()}is=e&&e.S()}function Xh(e){var t=this,n=e.data,r=gT(n);r.value=n;var i=Se(function(){for(var c=t,l=t.__v;l=l.__;)if(l.__c){l.__c.__$f|=4;break}var d=Wh(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),u=Wh(function(){return!Array.isArray(d.value)&&!$m(d.value)}),p=da(function(){if(this.N=Qh,u.value){var f=d.value;c.__v&&c.__v.__e&&c.__v.__e.nodeType===3&&(c.__v.__e.data=f)}}),m=t.__$u.d;return t.__$u.d=function(){p(),m.call(this)},[u,d]},[]),a=i[0],s=i[1];return a.value?s.peek():s.value}Xh.displayName="ReactiveTextNode",Object.defineProperties(et.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Xh},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 a=r[i];a instanceof et&&(n||(t.__np=n={}),n[i]=a,r[i]=a.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,a){var s;return da(function(){s=this},{name:a}),s.c=i,s})(function(){var i;fT&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof t.type=="function"?t.type.displayName||t.type.name:""))),Vl=r,as(n)}}),di("__e",function(e,t,n,r){as(),Vl=void 0,e(t,n,r)}),di("diffed",function(e,t){as(),Vl=void 0;var n;if(typeof t.type=="string"&&(n=t.__e)){var r=t.__np,i=t.props;if(r){var a=n.U;if(a)for(var s in a){var c=a[s];c!==void 0&&!(s in r)&&(c.d(),a[s]=void 0)}else a={},n.U=a;for(var l in r){var d=a[l],u=r[l];d===void 0?(d=hT(n,l,u),a[l]=d):d.o(u,i)}}}e(t)});function hT(e,t,n,r){var i=t in e&&e.ownerSVGElement===void 0,a=Hl(n),s=n.peek();return{o:function(c,l){a.value=c,s=c.peek()},d:da(function(){this.N=Qh;var c=a.value.value;s!==c?(s=void 0,i?e[t]=c:c!=null&&(c!==!1||t[4]==="-")?e.setAttribute(t,c):e.removeAttribute(t)):s=void 0})}}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 a=r[i];a&&a.d()}}}var s=t.__np;if(s){var c=t.props;for(var l in s)c[l]=s[l]}t.__np=void 0}else{var d=t.__c;if(d){var u=d.__$u;u&&(d.__$u=void 0,u.d())}}e(t)}),di("__h",function(e,t,n,r){(r<3||r===9)&&(t.__$f|=2),e(t,n,r)}),It.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in t)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(r||a||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var s in e)if(s!=="__source"&&e[s]!==this.props[s])return!0;for(var c in this.props)if(!(c in e))return!0;return!1};function gT(e,t){return Se(function(){return Hl(e,t)},[])}var tU=typeof requestAnimationFrame>"u"?setTimeout:function(e){var t=function(){clearTimeout(n),cancelAnimationFrame(r),e()},n=setTimeout(t,35),r=requestAnimationFrame(t)},vT=function(e){queueMicrotask(function(){queueMicrotask(e)})};function yT(){uT(function(){for(var e;e=Yh.shift();)Jh.call(e)})}function Qh(){Yh.push(this)===1&&(me.requestAnimationFrame||vT)(yT)}function os(e){const t=e+"CollectionProvider",[n,r]=dt(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=g=>{const{scope:h,children:b}=g,w=pn.useRef(null),_=pn.useRef(new Map).current;return o(i,{scope:h,itemMap:_,collectionRef:w,children:b})};s.displayName=t;const c=e+"CollectionSlot",l=pr(c),d=pn.forwardRef((g,h)=>{const{scope:b,children:w}=g;return o(l,{ref:be(h,a(c,b).collectionRef),children:w})});d.displayName=c;const u=e+"CollectionItemSlot",p="data-radix-collection-item",m=pr(u),f=pn.forwardRef((g,h)=>{const{scope:b,children:w,..._}=g,I=pn.useRef(null),N=be(h,I),T=a(u,b);return pn.useEffect(()=>(T.itemMap.set(I,{ref:I,..._}),()=>{T.itemMap.delete(I)})),o(m,{[p]:"",ref:N,children:w})});f.displayName=u;function y(g){const h=a(e+"CollectionConsumer",g);return pn.useCallback(()=>{const b=h.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${p}]`));return Array.from(h.itemMap.values()).sort((_,I)=>w.indexOf(_.ref.current)-w.indexOf(I.ref.current))},[h.collectionRef,h.itemMap])}return[{Provider:s,Slot:d,ItemSlot:f},y,r]}var Zh=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"}),bT="VisuallyHidden",ss=K((e,t)=>o(le.span,{...e,ref:t,style:{...Zh,...e.style}}));ss.displayName=bT;var _T=ss,Wl="ToastProvider",[zl,wT,ST]=os("Toast"),[eg,nU]=dt("Toast",[ST]),[CT,cs]=eg(Wl),tg=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:a=50,children:s}=e,[c,l]=D(null),[d,u]=D(0),p=q(!1),m=q(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Wl}\`. Expected non-empty \`string\`.`),o(zl.Provider,{scope:t,children:o(CT,{scope:t,label:n,duration:r,swipeDirection:i,swipeThreshold:a,toastCount:d,viewport:c,onViewportChange:l,onToastAdd:oe(()=>u(f=>f+1),[]),onToastRemove:oe(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:m,children:s})})};tg.displayName=Wl;var ng="ToastViewport",NT=["F8"],Jl="toast.viewportPause",Yl="toast.viewportResume",rg=K((e,t)=>{const{__scopeToast:n,hotkey:r=NT,label:i="Notifications ({hotkey})",...a}=e,s=cs(ng,n),c=wT(n),l=q(null),d=q(null),u=q(null),p=q(null),m=be(t,p,s.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),y=s.toastCount>0;W(()=>{const h=b=>{r.length!==0&&r.every(w=>b[w]||b.code===w)&&p.current?.focus()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[r]),W(()=>{const h=l.current,b=p.current;if(y&&h&&b){const w=()=>{if(!s.isClosePausedRef.current){const T=new CustomEvent(Jl);b.dispatchEvent(T),s.isClosePausedRef.current=!0}},_=()=>{if(s.isClosePausedRef.current){const T=new CustomEvent(Yl);b.dispatchEvent(T),s.isClosePausedRef.current=!1}},I=T=>{h.contains(T.relatedTarget)||_()},N=()=>{h.contains(document.activeElement)||_()};return h.addEventListener("focusin",w),h.addEventListener("focusout",I),h.addEventListener("pointermove",w),h.addEventListener("pointerleave",N),window.addEventListener("blur",w),window.addEventListener("focus",_),()=>{h.removeEventListener("focusin",w),h.removeEventListener("focusout",I),h.removeEventListener("pointermove",w),h.removeEventListener("pointerleave",N),window.removeEventListener("blur",w),window.removeEventListener("focus",_)}}},[y,s.isClosePausedRef]);const g=oe(({tabbingDirection:h})=>{const b=c().map(w=>{const _=w.ref.current,I=[_,...FT(_)];return h==="forwards"?I:I.reverse()});return(h==="forwards"?b.reverse():b).flat()},[c]);return W(()=>{const h=p.current;if(h){const b=w=>{const _=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!_){const I=document.activeElement,N=w.shiftKey;if(w.target===h&&N){d.current?.focus();return}const T=g({tabbingDirection:N?"backwards":"forwards"}),x=T.findIndex(j=>j===I);Zl(T.slice(x+1))?w.preventDefault():N?d.current?.focus():u.current?.focus()}};return h.addEventListener("keydown",b),()=>h.removeEventListener("keydown",b)}},[c,g]),o(ZN,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:y?void 0:"none"},children:[y&&o(Xl,{ref:d,onFocusFromOutsideViewport:()=>{Zl(g({tabbingDirection:"forwards"}))}}),o(zl.Slot,{scope:n,children:o(le.ol,{tabIndex:-1,...a,ref:m})}),y&&o(Xl,{ref:u,onFocusFromOutsideViewport:()=>{Zl(g({tabbingDirection:"backwards"}))}})]})});rg.displayName=ng;var ig="ToastFocusProxy",Xl=K((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=e,a=cs(ig,n);return o(ss,{tabIndex:0,...i,ref:t,style:{position:"fixed"},onFocus:s=>{const c=s.relatedTarget;a.viewport?.contains(c)||r()}})});Xl.displayName=ig;var ua="Toast",IT="toast.swipeStart",kT="toast.swipeMove",TT="toast.swipeCancel",RT="toast.swipeEnd",ag=K((e,t)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:a,...s}=e,[c,l]=kt({prop:r,defaultProp:i??!0,onChange:a,caller:ua});return o(ot,{present:n||c,children:o(ET,{open:c,...s,ref:t,onClose:()=>l(!1),onPause:pt(e.onPause),onResume:pt(e.onResume),onSwipeStart:X(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:X(e.onSwipeMove,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:X(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:X(e.onSwipeEnd,d=>{const{x:u,y:p}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});ag.displayName=ua;var[PT,AT]=eg(ua,{onClose(){}}),ET=K((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:a,onClose:s,onEscapeKeyDown:c,onPause:l,onResume:d,onSwipeStart:u,onSwipeMove:p,onSwipeCancel:m,onSwipeEnd:f,...y}=e,g=cs(ua,n),[h,b]=D(null),w=be(t,$=>b($)),_=q(null),I=q(null),N=i||g.duration,T=q(0),x=q(N),j=q(0),{onToastAdd:B,onToastRemove:P}=g,F=pt(()=>{h?.contains(document.activeElement)&&g.viewport?.focus(),s()}),O=oe($=>{!$||$===1/0||(window.clearTimeout(j.current),T.current=new Date().getTime(),j.current=window.setTimeout(F,$))},[F]);W(()=>{const $=g.viewport;if($){const A=()=>{O(x.current),d?.()},E=()=>{const C=new Date().getTime()-T.current;x.current=x.current-C,window.clearTimeout(j.current),l?.()};return $.addEventListener(Jl,E),$.addEventListener(Yl,A),()=>{$.removeEventListener(Jl,E),$.removeEventListener(Yl,A)}}},[g.viewport,N,l,d,O]),W(()=>{a&&!g.isClosePausedRef.current&&O(N)},[a,N,g.isClosePausedRef,O]),W(()=>(B(),()=>P()),[B,P]);const G=Se(()=>h?dg(h):null,[h]);return g.viewport?o(z,{children:[G&&o(xT,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:G}),o(PT,{scope:n,onClose:F,children:dn(o(zl.ItemSlot,{scope:n,children:o(QN,{asChild:!0,onEscapeKeyDown:X(c,()=>{g.isFocusedToastEscapeKeyDownRef.current||F(),g.isFocusedToastEscapeKeyDownRef.current=!1}),children:o(le.li,{tabIndex:0,"data-state":a?"open":"closed","data-swipe-direction":g.swipeDirection,...y,ref:w,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:X(e.onKeyDown,$=>{$.key==="Escape"&&(c?.($.nativeEvent),$.nativeEvent.defaultPrevented||(g.isFocusedToastEscapeKeyDownRef.current=!0,F()))}),onPointerDown:X(e.onPointerDown,$=>{$.button===0&&(_.current={x:$.clientX,y:$.clientY})}),onPointerMove:X(e.onPointerMove,$=>{if(!_.current)return;const A=$.clientX-_.current.x,E=$.clientY-_.current.y,C=!!I.current,L=["left","right"].includes(g.swipeDirection),U=["left","up"].includes(g.swipeDirection)?Math.min:Math.max,V=L?U(0,A):0,de=L?0:U(0,E),ie=$.pointerType==="touch"?10:2,ne={x:V,y:de},Re={originalEvent:$,delta:ne};C?(I.current=ne,ls(kT,p,Re,{discrete:!1})):ug(ne,g.swipeDirection,ie)?(I.current=ne,ls(IT,u,Re,{discrete:!1}),$.target.setPointerCapture($.pointerId)):(Math.abs(A)>ie||Math.abs(E)>ie)&&(_.current=null)}),onPointerUp:X(e.onPointerUp,$=>{const A=I.current,E=$.target;if(E.hasPointerCapture($.pointerId)&&E.releasePointerCapture($.pointerId),I.current=null,_.current=null,A){const C=$.currentTarget,L={originalEvent:$,delta:A};ug(A,g.swipeDirection,g.swipeThreshold)?ls(RT,f,L,{discrete:!0}):ls(TT,m,L,{discrete:!0}),C.addEventListener("click",U=>U.preventDefault(),{once:!0})}})})})}),g.viewport)})]}):null}),xT=e=>{const{__scopeToast:t,children:n,...r}=e,i=cs(ua,t),[a,s]=D(!1),[c,l]=D(!1);return jT(()=>s(!0)),W(()=>{const d=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(d)},[]),c?null:o(fr,{asChild:!0,children:o(ss,{...r,children:a&&o(z,{children:[i.label," ",n]})})})},DT="ToastTitle",LT=K((e,t)=>{const{__scopeToast:n,...r}=e;return o(le.div,{...r,ref:t})});LT.displayName=DT;var $T="ToastDescription",og=K((e,t)=>{const{__scopeToast:n,...r}=e;return o(le.div,{...r,ref:t})});og.displayName=$T;var sg="ToastAction",MT=K((e,t)=>{const{altText:n,...r}=e;return n.trim()?o(lg,{altText:n,asChild:!0,children:o(Ql,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${sg}\`. Expected non-empty \`string\`.`),null)});MT.displayName=sg;var cg="ToastClose",Ql=K((e,t)=>{const{__scopeToast:n,...r}=e,i=AT(cg,n);return o(lg,{asChild:!0,children:o(le.button,{type:"button",...r,ref:t,onClick:X(e.onClick,i.onClose)})})});Ql.displayName=cg;var lg=K((e,t)=>{const{__scopeToast:n,altText:r,...i}=e;return o(le.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:t})});function dg(e){const t=[];return Array.from(e.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),OT(n)){const r=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!r)if(i){const a=n.dataset.radixToastAnnounceAlt;a&&t.push(a)}else t.push(...dg(n))}}),t}function ls(e,t,n,{discrete:r}){const i=n.originalEvent.currentTarget,a=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&i.addEventListener(e,t,{once:!0}),r?wl(i,a):i.dispatchEvent(a)}var ug=(e,t,n=0)=>{const r=Math.abs(e.x),i=Math.abs(e.y),a=r>i;return t==="left"||t==="right"?a&&r>n:!a&&i>n};function jT(e=()=>{}){const t=pt(e);Je(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function OT(e){return e.nodeType===e.ELEMENT_NODE}function FT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Zl(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var BT=tg,UT=rg,qT=ag,GT=og,HT=Ql,pa=Hl([]),KT=1;function VT(e,t="success",n=8e3){if(!e)return;const r=KT++;pa.value=[...pa.value,{id:r,message:e,variant:t,durationMs:n}]}function WT(e){pa.value=pa.value.filter(t=>t.id!==e)}function zT(){const e=pa.value;return o(BT,{duration:8e3,swipeDirection:"right",children:[e.map(t=>o(qT,{className:`toast-root toast-${t.variant}`,duration:t.durationMs,onOpenChange:n=>{n||WT(t.id)},type:t.variant==="error"||t.variant==="warning"?"foreground":"background",children:[o(GT,{className:"toast-message",children:t.message}),o(HT,{"aria-label":"Dismiss",className:"toast-close",children:"×"})]},t.id)),o(UT,{className:"toast-viewport"})]})}function JT(e){He(o(zT,{}),e)}function ds(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 ed(e){return document.getElementById(e)}function td(e){return document.getElementById(e)}function pg(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function YT(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XT(e,t){const n=t.trim();if(!n)return pg(e);const r=pg(e);try{const i=new RegExp(`(${YT(n)})`,"ig");return r.replace(i,'<mark class="match">$1</mark>')}catch{return r}}async function ma(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 QT=new Set(["BUTTON","A","SELECT"]),ZT=new Set(["button","checkbox","color","file","image","radio","range","reset","submit"]);function eR(e){return!e||typeof e.closest!="function"?!1:e.closest('[data-primary-action-ignore="true"]')!==null}function tR(e){return e?!!(e instanceof HTMLTextAreaElement||"isContentEditable"in e&&e.isContentEditable):!1}function nR(e){return e?QT.has(e.tagName)?!0:e instanceof HTMLInputElement&&ZT.has(e.type):!1}function rR(e){return e.metaKey||e.ctrlKey}function ui(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(!eR(n)){if(e.key==="Escape"){if(!t.onCancel)return;e.preventDefault(),t.onCancel();return}nR(n)||tR(n)&&!rR(e)||(e.preventDefault(),t.onSubmit())}}var _r=["feed","projects","sharing","devices","health","advanced"],mg=["sync","coordinator-admin"],nd="codemem-tab",fg="codemem-advanced-section",hg="codemem-feed-filter",gg="codemem-feed-scope",iR="codemem-sync-diagnostics",vg="codemem-sync-pairing",yg="codemem-sync-redact",bg=["all","observations","summaries"],_g=["all","mine","theirs"],S={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 aR(e){return[..._r]}function fa(e,t){return e==="sync"||e==="coordinator-admin"?"advanced":_r.includes(e)?e:"feed"}function rd(e=window.location.hash){const t=e.replace(/^#/,"").split("/")[0];return mg.includes(t)?"advanced":_r.includes(t)?t:null}function id(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 oR(){const e=rd();if(e)return fa(e,S.lastCoordinatorAdminStatus);const t=localStorage.getItem(nd);return t&&(_r.includes(t)||mg.includes(t))?fa(t,S.lastCoordinatorAdminStatus):"feed"}function sR(){const e=id();if(e)return e;const t=localStorage.getItem(nd);return t==="coordinator-admin"?"teams":t==="sync"?"sync":localStorage.getItem(fg)==="teams"?"teams":"sync"}function ad(e,t=!1){S.advancedSection=e,localStorage.setItem(fg,e),t&&(window.location.hash=`advanced/${e}`)}function wg(e,t={}){const n=fa(e,S.lastCoordinatorAdminStatus);S.activeTab=n,localStorage.setItem(nd,n);const r=rd();t.canonicalHash?window.location.hash=n:r!==n&&(window.location.hash=n==="advanced"?`advanced/${S.advancedSection}`:n)}function cR(){const e=localStorage.getItem(hg)||"all";return bg.includes(e)?e:"all"}function lR(){const e=localStorage.getItem(gg)||"all";return _g.includes(e)?e:"all"}function dR(e){S.feedTypeFilter=bg.includes(e)?e:"all",localStorage.setItem(hg,S.feedTypeFilter)}function Sg(e){S.feedScopeFilter=_g.includes(e)?e:"all",localStorage.setItem(gg,S.feedScopeFilter)}function uR(){return localStorage.getItem(iR)==="1"}function pR(e){S.syncPairingOpen=e;try{localStorage.setItem(vg,e?"1":"0")}catch{}}function ha(){return localStorage.getItem(yg)!=="0"}function mR(e){localStorage.setItem(yg,e?"1":"0")}function fR(){S.activeTab=oR(),S.advancedSection=sR(),S.feedTypeFilter=cR(),S.feedScopeFilter=lR(),S.syncDiagnosticsOpen=uR();try{S.syncPairingOpen=localStorage.getItem(vg)==="1"}catch{S.syncPairingOpen=!1}}var od=[{id:"light",label:"Light",mode:"light"},{id:"dark",label:"Dark",mode:"dark"}],Cg="codemem-theme";function Ng(e){const t=od.find(r=>r.id===e);if(t)return t;const n=e.startsWith("dark")?"dark":"light";return od.find(r=>r.id===n)||od[0]}function sd(){const e=localStorage.getItem(Cg);return e?Ng(e).id:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Ig(e){const t=Ng(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(Cg,t.id)}function hR(e){if(!e)return;const t=n=>{const r=n==="dark"?"sun":"moon",i=n==="dark"?"Switch to light theme":"Switch to dark theme";e.setAttribute("aria-label",i),e.textContent="";const a=document.createElement("i");a.setAttribute("data-lucide",r),a.setAttribute("aria-hidden","true"),e.appendChild(a),globalThis.lucide?.createIcons?.()};t(sd()==="dark"?"dark":"light"),e.addEventListener("click",()=>{const n=sd()==="dark"?"light":"dark";Ig(n),t(n)})}var gR=lr(void 0);function ga(e){const t=Ln(gR);return e||t||"ltr"}var cd="rovingFocusGroup.onEntryFocus",vR={bubbles:!1,cancelable:!0},va="RovingFocusGroup",[ld,kg,yR]=os(va),[bR,pi]=dt(va,[yR]),[_R,wR]=bR(va),Tg=K((e,t)=>o(ld.Provider,{scope:e.__scopeRovingFocusGroup,children:o(ld.Slot,{scope:e.__scopeRovingFocusGroup,children:o(SR,{...e,ref:t})})}));Tg.displayName=va;var SR=K((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:s,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...p}=e,m=q(null),f=be(t,m),y=ga(a),[g,h]=kt({prop:s,defaultProp:c??null,onChange:l,caller:va}),[b,w]=D(!1),_=pt(d),I=kg(n),N=q(!1),[T,x]=D(0);return W(()=>{const j=m.current;if(j)return j.addEventListener(cd,_),()=>j.removeEventListener(cd,_)},[_]),o(_R,{scope:n,orientation:r,dir:y,loop:i,currentTabStopId:g,onItemFocus:oe(j=>h(j),[h]),onItemShiftTab:oe(()=>w(!0),[]),onFocusableItemAdd:oe(()=>x(j=>j+1),[]),onFocusableItemRemove:oe(()=>x(j=>j-1),[]),children:o(le.div,{tabIndex:b||T===0?-1:0,"data-orientation":r,...p,ref:f,style:{outline:"none",...e.style},onMouseDown:X(e.onMouseDown,()=>{N.current=!0}),onFocus:X(e.onFocus,j=>{const B=!N.current;if(j.target===j.currentTarget&&B&&!b){const P=new CustomEvent(cd,vR);if(j.currentTarget.dispatchEvent(P),!P.defaultPrevented){const F=I().filter(O=>O.focusable);Ag([F.find(O=>O.active),F.find(O=>O.id===g),...F].filter(Boolean).map(O=>O.ref.current),u)}}N.current=!1}),onBlur:X(e.onBlur,()=>w(!1))})})}),Rg="RovingFocusGroupItem",Pg=K((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:s,...c}=e,l=ut(),d=a||l,u=wR(Rg,n),p=u.currentTabStopId===d,m=kg(n),{onFocusableItemAdd:f,onFocusableItemRemove:y,currentTabStopId:g}=u;return W(()=>{if(r)return f(),()=>y()},[r,f,y]),o(ld.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:o(le.span,{tabIndex:p?0:-1,"data-orientation":u.orientation,...c,ref:t,onMouseDown:X(e.onMouseDown,h=>{r?u.onItemFocus(d):h.preventDefault()}),onFocus:X(e.onFocus,()=>u.onItemFocus(d)),onKeyDown:X(e.onKeyDown,h=>{if(h.key==="Tab"&&h.shiftKey){u.onItemShiftTab();return}if(h.target!==h.currentTarget)return;const b=IR(h,u.orientation,u.dir);if(b!==void 0){if(h.metaKey||h.ctrlKey||h.altKey||h.shiftKey)return;h.preventDefault();let w=m().filter(_=>_.focusable).map(_=>_.ref.current);if(b==="last")w.reverse();else if(b==="prev"||b==="next"){b==="prev"&&w.reverse();const _=w.indexOf(h.currentTarget);w=u.loop?kR(w,_+1):w.slice(_+1)}setTimeout(()=>Ag(w))}}),children:typeof s=="function"?s({isCurrentTabStop:p,hasTabStop:g!=null}):s})})});Pg.displayName=Rg;var CR={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function NR(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function IR(e,t,n){const r=NR(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return CR[r]}function Ag(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function kR(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var dd=Tg,ud=Pg,us="Tabs",[TR,rU]=dt(us,[pi]),Eg=pi(),[RR,pd]=TR(us),xg=K((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:a,orientation:s="horizontal",dir:c,activationMode:l="automatic",...d}=e,u=ga(c),[p,m]=kt({prop:r,onChange:i,defaultProp:a??"",caller:us});return o(RR,{scope:n,baseId:ut(),value:p,onValueChange:m,orientation:s,dir:u,activationMode:l,children:o(le.div,{dir:u,"data-orientation":s,...d,ref:t})})});xg.displayName=us;var Dg="TabsList",Lg=K((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,a=pd(Dg,n),s=Eg(n);return o(dd,{asChild:!0,...s,orientation:a.orientation,dir:a.dir,loop:r,children:o(le.div,{role:"tablist","aria-orientation":a.orientation,...i,ref:t})})});Lg.displayName=Dg;var $g="TabsTrigger",Mg=K((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...a}=e,s=pd($g,n),c=Eg(n),l=Fg(s.baseId,r),d=Bg(s.baseId,r),u=r===s.value;return o(ud,{asChild:!0,...c,focusable:!i,active:u,children:o(le.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...a,ref:t,onMouseDown:X(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:X(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:X(e.onFocus,()=>{const p=s.activationMode!=="manual";!u&&!i&&p&&s.onValueChange(r)})})})});Mg.displayName=$g;var jg="TabsContent",Og=K((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:a,...s}=e,c=pd(jg,n),l=Fg(c.baseId,r),d=Bg(c.baseId,r),u=r===c.value,p=q(u);return W(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),o(ot,{present:i||u,children:({present:m})=>o(le.div,{"data-state":u?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:d,tabIndex:0,...s,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&a})})});Og.displayName=jg;function Fg(e,t){return`${e}-trigger-${t}`}function Bg(e,t){return`${e}-content-${t}`}var PR=xg,AR=Lg,ER=Mg,xR=Og;function Ug({ariaLabel:e,children:t,listClassName:n,onValueChange:r,tabs:i,triggerClassName:a,value:s}){return o(PR,{onValueChange:r,value:s,children:[o(AR,{"aria-label":e,className:n,children:i.map(c=>o(ER,{className:a,disabled:c.disabled,value:c.value,children:c.label},c.value))}),t]})}function wr({children:e,className:t,forceMount:n=!1,value:r}){return o(xR,{className:t,forceMount:n?!0:void 0,value:r,children:e})}function _e(e){return o("input",{...e})}function ps(){return{aliases:new Map,duplicateDisplayNames:new Map,reservedDisplayNames:new Set}}function qg(e,t=ps()){for(const a of e){const s=String(a.display_name||"").trim();s&&t.reservedDisplayNames.add(s)}for(const[a,s]of t.aliases)t.reservedDisplayNames.has(s)&&t.aliases.delete(a);const n=new Set([...t.reservedDisplayNames,...t.aliases.values()]),r=e.filter(a=>!String(a.display_name||"").trim()).map(a=>String(a.device_id||"").trim()).filter(Boolean).sort((a,s)=>a.localeCompare(s));let i=Math.max(0,...[...t.aliases.values()].map(a=>{const s=/^Unnamed device (\d+)$/.exec(a);return s?Number(s[1]):0}));for(const a of r){if(t.aliases.has(a))continue;let s;do i+=1,s=`Unnamed device ${i}`;while(n.has(s));t.aliases.set(a,s),n.add(s)}return t.aliases}function ms(e,t=ps()){const n=qg(e,t),r=new Map,i=new Map,a=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}a.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=a.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,m)=>p.localeCompare(m))){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 m=0,f;do m+=1,f=`${l} · Device ${m}`;while(c.has(f));r.set(u,f),t.duplicateDisplayNames.set(u,{displayName:f,sourceName:l}),c.add(f)}return r}function DR(e,t,n=""){const r=String(e.device_id||"").trim(),i=String(e.group_id||t||"").trim(),a=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:a,statusLabel:s?"Enabled in this coordinator group":"Disabled in this coordinator group",teamId:i}}var Gg={status:"coordinator status",groups:"coordinator groups",joinRequests:"join requests",devices:"devices"};function fs(){return{availability:"unknown",retrying:!1}}function LR(){return{status:fs(),groups:fs(),joinRequests:fs(),devices:fs()}}function ya(e,t){e[t]={...e[t],retrying:!0}}function md(e,t){e[t]={...e[t],retrying:!1}}function hs(e,t){e[t]={availability:"fresh",retrying:!1}}function Wt(e,t,n){e[t]={availability:n??(e[t].availability==="fresh"||e[t].availability==="stale")?"stale":"unavailable",retrying:!1}}function fd(e,t){e[t]={availability:"not_applicable",retrying:!1}}function Sr(e,t){return e[t].availability==="fresh"||e[t].availability==="stale"}function fn(e,...t){return t.every(n=>e[n].availability==="fresh"&&!e[n].retrying)}function mi(e,t){return e[t].availability==="not_applicable"}function Hg(e){const t=Object.entries(e),n=t.filter(([,i])=>i.availability==="stale").map(([i])=>Gg[i]),r=t.filter(([,i])=>i.availability==="unavailable").map(([i])=>Gg[i]);return n.length===0&&r.length===0?null:{stale:n,unavailable:r,retrying:t.some(([,i])=>i.retrying)}}var $R="codemem-coordinator-admin-target-group",R={recovery:LR(),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:ps(),groupPreferencesOpen:new Set,groupPreferencesDrafts:new Map,groupScopeManagementOpen:new Set,groupScopeManagementDrafts:new Map,teamSetupGuide:null,availableProjects:[]};function Kg(){return R.loadGeneration+=1,R.loadGeneration}function hd(e){return R.loadGeneration===e}function MR(e){const{summary:t,fresh:n,runDevice:r,snapshotMatchesTarget:i}=e,a=i&&Sr(R.recovery,"devices"),s=mi(R.recovery,"devices"),c=a&&Array.isArray(S.lastCoordinatorAdminDevices)?S.lastCoordinatorAdminDevices:[],l=ms(c,R.unnamedDeviceAliases);return v(wr,{className:"coordinator-admin-panel",value:"devices"},v("h3",null,"Enrolled devices"),v("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?v("div",{class:"peer-meta"},"Complete legacy coordinator setup to load enrolled devices. No device data is expected yet."):a?c.length?v("div",{class:"peer-list"},c.map(d=>{const u=DR(d,String(S.lastCoordinatorAdminStatus?.active_group||""),l.get(String(d.device_id||"").trim())),{deviceId:p,displayName:m,teamId:f}=u,y=R.deviceActionPendingId===p,g=R.deviceRenameDrafts.get(p)??String(d.display_name||""),h=d.enabled!==!1&&d.enabled!==0,b=!n||!p||y;return v("div",{class:"peer-card peer-card--padded",key:p||String(d.fingerprint||"unknown")},v("div",{class:"peer-title"},v("strong",null,m)),v("div",{class:"peer-submeta"},u.statusLabel),v("details",{class:"coordinator-admin-diagnostics"},v("summary",null,"Diagnostics"),v("div",{class:"peer-meta"},u.advancedDetail)),v("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r(p,f,m,"rename")}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"Display name"),v(_e,{class:"peer-scope-input",disabled:!n||y,onInput:w=>{R.deviceRenameDrafts.set(p,String(w.currentTarget.value||""))},type:"text",value:g}))),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:b,type:"submit"},y&&R.deviceActionPendingKind==="rename"?"Renaming…":"Rename"),h?v("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,f,m,"disable"),type:"button"},y&&R.deviceActionPendingKind==="disable"?"Disabling…":"Disable"):v("button",{class:"settings-button",disabled:b,onClick:()=>r(p,f,m,"enable"),type:"button"},y&&R.deviceActionPendingKind==="enable"?"Enabling…":"Enable"),v("button",{class:"settings-button danger",disabled:b,onClick:()=>r(p,f,m,"remove"),type:"button"},y&&R.deviceActionPendingKind==="remove"?"Removing…":"Remove"))))})):v("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."):v("div",{class:"peer-meta"},"Enrolled devices are unavailable. Retry to load current devices; no empty result is being assumed."))}var gs="Collapsible",[jR,iU]=dt(gs),[OR,gd]=jR(gs),Vg=K((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:i,disabled:a,onOpenChange:s,...c}=e,[l,d]=kt({prop:r,defaultProp:i??!1,onChange:s,caller:gs});return o(OR,{scope:n,disabled:a,contentId:ut(),open:l,onOpenToggle:oe(()=>d(u=>!u),[d]),children:o(le.div,{"data-state":yd(l),"data-disabled":a?"":void 0,...c,ref:t})})});Vg.displayName=gs;var Wg="CollapsibleTrigger",zg=K((e,t)=>{const{__scopeCollapsible:n,...r}=e,i=gd(Wg,n);return o(le.button,{type:"button","aria-controls":i.contentId,"aria-expanded":i.open||!1,"data-state":yd(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...r,ref:t,onClick:X(e.onClick,i.onOpenToggle)})});zg.displayName=Wg;var vd="CollapsibleContent",Jg=K((e,t)=>{const{forceMount:n,...r}=e,i=gd(vd,e.__scopeCollapsible);return o(ot,{present:n||i.open,children:({present:a})=>o(FR,{...r,ref:t,present:a})})});Jg.displayName=vd;var FR=K((e,t)=>{const{__scopeCollapsible:n,present:r,children:i,...a}=e,s=gd(vd,n),[c,l]=D(r),d=q(null),u=be(t,d),p=q(0),m=p.current,f=q(0),y=f.current,g=s.open||c,h=q(g),b=q(void 0);return W(()=>{const w=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(w)},[]),Je(()=>{const w=d.current;if(w){b.current=b.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const _=w.getBoundingClientRect();p.current=_.height,f.current=_.width,h.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),l(r)}},[s.open,r]),o(le.div,{"data-state":yd(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!g,...a,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...e.style},children:g&&i})});function yd(e){return e?"open":"closed"}var ba=Vg,bd=zg,_a=Jg,BR=["top","right","bottom","left"],Mn=Math.min,wt=Math.max,vs=Math.round,ys=Math.floor,zt=e=>({x:e,y:e}),UR={left:"right",right:"left",bottom:"top",top:"bottom"};function _d(e,t,n){return wt(e,Mn(t,n))}function hn(e,t){return typeof e=="function"?e(t):e}function gn(e){return e.split("-")[0]}function fi(e){return e.split("-")[1]}function wd(e){return e==="x"?"y":"x"}function Sd(e){return e==="y"?"height":"width"}function Jt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Cd(e){return wd(Jt(e))}function qR(e,t,n){n===void 0&&(n=!1);const r=fi(e),i=Cd(e),a=Sd(i);let s=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[a]>t.floating[a]&&(s=bs(s)),[s,bs(s)]}function GR(e){const t=bs(e);return[Nd(e),t,Nd(t)]}function Nd(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}var Yg=["left","right"],Xg=["right","left"],HR=["top","bottom"],KR=["bottom","top"];function VR(e,t,n){switch(e){case"top":case"bottom":return n?t?Xg:Yg:t?Yg:Xg;case"left":case"right":return t?HR:KR;default:return[]}}function WR(e,t,n,r){const i=fi(e);let a=VR(gn(e),n==="start",r);return i&&(a=a.map(s=>s+"-"+i),t&&(a=a.concat(a.map(Nd)))),a}function bs(e){const t=gn(e);return UR[t]+e.slice(t.length)}function zR(e){return{top:0,right:0,bottom:0,left:0,...e}}function Qg(e){return typeof e!="number"?zR(e):{top:e,right:e,bottom:e,left:e}}function _s(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 Zg(e,t,n){let{reference:r,floating:i}=e;const a=Jt(t),s=Cd(t),c=Sd(s),l=gn(t),d=a==="y",u=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,m=r[c]/2-i[c]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:p};break;case"left":f={x:r.x-i.width,y:p};break;default:f={x:r.x,y:r.y}}switch(fi(t)){case"start":f[s]-=m*(n&&d?-1:1);break;case"end":f[s]+=m*(n&&d?-1:1);break}return f}async function JR(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:a,rects:s,elements:c,strategy:l}=e,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:p="floating",altBoundary:m=!1,padding:f=0}=hn(t,e),y=Qg(f),g=c[m?p==="floating"?"reference":"floating":p],h=_s(await a.getClippingRect({element:(n=await(a.isElement==null?void 0:a.isElement(g)))==null||n?g:g.contextElement||await(a.getDocumentElement==null?void 0:a.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(a.getOffsetParent==null?void 0:a.getOffsetParent(c.floating)),_=await(a.isElement==null?void 0:a.isElement(w))?await(a.getScale==null?void 0:a.getScale(w))||{x:1,y:1}:{x:1,y:1},I=_s(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:b,offsetParent:w,strategy:l}):b);return{top:(h.top-I.top+y.top)/_.y,bottom:(I.bottom-h.bottom+y.bottom)/_.y,left:(h.left-I.left+y.left)/_.x,right:(I.right-h.right+y.right)/_.x}}var YR=50,XR=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:a=[],platform:s}=n,c=s.detectOverflow?s:{...s,detectOverflow:JR},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}=Zg(d,r,l),m=r,f=0;const y={};for(let g=0;g<a.length;g++){const h=a[g];if(!h)continue;const{name:b,fn:w}=h,{x:_,y:I,data:N,reset:T}=await w({x:u,y:p,initialPlacement:r,placement:m,strategy:i,middlewareData:y,rects:d,platform:c,elements:{reference:e,floating:t}});u=_??u,p=I??p,y[b]={...y[b],...N},T&&f<YR&&(f++,typeof T=="object"&&(T.placement&&(m=T.placement),T.rects&&(d=T.rects===!0?await s.getElementRects({reference:e,floating:t,strategy:i}):T.rects),{x:u,y:p}=Zg(d,m,l)),g=-1)}return{x:u,y:p,placement:m,strategy:i,middlewareData:y}},QR=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:a,platform:s,elements:c,middlewareData:l}=t,{element:d,padding:u=0}=hn(e,t)||{};if(d==null)return{};const p=Qg(u),m={x:n,y:r},f=Cd(i),y=Sd(f),g=await s.getDimensions(d),h=f==="y",b=h?"top":"left",w=h?"bottom":"right",_=h?"clientHeight":"clientWidth",I=a.reference[y]+a.reference[f]-m[f]-a.floating[y],N=m[f]-a.reference[f],T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let x=T?T[_]:0;(!x||!await(s.isElement==null?void 0:s.isElement(T)))&&(x=c.floating[_]||a.floating[y]);const j=I/2-N/2,B=x/2-g[y]/2-1,P=Mn(p[b],B),F=Mn(p[w],B),O=P,G=x-g[y]-F,$=x/2-g[y]/2+j,A=_d(O,$,G),E=!l.arrow&&fi(i)!=null&&$!==A&&a.reference[y]/2-($<O?P:F)-g[y]/2<0,C=E?$<O?$-O:$-G:0;return{[f]:m[f]+C,data:{[f]:A,centerOffset:$-A-C,...E&&{alignmentOffset:C}},reset:E}}}),ZR=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:a,rects:s,initialPlacement:c,platform:l,elements:d}=t,{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:m,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:g=!0,...h}=hn(e,t);if((n=a.arrow)!=null&&n.alignmentOffset)return{};const b=gn(i),w=Jt(c),_=gn(c)===c,I=await(l.isRTL==null?void 0:l.isRTL(d.floating)),N=m||(_||!g?[bs(c)]:GR(c)),T=y!=="none";!m&&T&&N.push(...WR(c,g,y,I));const x=[c,...N],j=await l.detectOverflow(t,h),B=[];let P=((r=a.flip)==null?void 0:r.overflows)||[];if(u&&B.push(j[b]),p){const $=qR(i,s,I);B.push(j[$[0]],j[$[1]])}if(P=[...P,{placement:i,overflows:B}],!B.every($=>$<=0)){var F,O;const $=(((F=a.flip)==null?void 0:F.index)||0)+1,A=x[$];if(A&&(!(p==="alignment"&&w!==Jt(A))||P.every(C=>Jt(C.placement)===w?C.overflows[0]>0:!0)))return{data:{index:$,overflows:P},reset:{placement:A}};let E=(O=P.filter(C=>C.overflows[0]<=0).sort((C,L)=>C.overflows[1]-L.overflows[1])[0])==null?void 0:O.placement;if(!E)switch(f){case"bestFit":{var G;const C=(G=P.filter(L=>{if(T){const U=Jt(L.placement);return U===w||U==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(U=>U>0).reduce((U,V)=>U+V,0)]).sort((L,U)=>L[1]-U[1])[0])==null?void 0:G[0];C&&(E=C);break}case"initialPlacement":E=c;break}if(i!==E)return{reset:{placement:E}}}return{}}}};function ev(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function tv(e){return BR.some(t=>e[t]>=0)}var eP=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...a}=hn(e,t);switch(i){case"referenceHidden":{const s=ev(await r.detectOverflow(t,{...a,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:tv(s)}}}case"escaped":{const s=ev(await r.detectOverflow(t,{...a,altBoundary:!0}),n.floating);return{data:{escapedOffsets:s,escaped:tv(s)}}}default:return{}}}}},nv=new Set(["left","top"]);async function tP(e,t){const{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),s=gn(n),c=fi(n),l=Jt(n)==="y",d=nv.has(s)?-1:1,u=a&&l?-1:1,p=hn(t,e);let{mainAxis:m,crossAxis:f,alignmentAxis:y}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return c&&typeof y=="number"&&(f=c==="end"?y*-1:y),l?{x:f*u,y:m*d}:{x:m*d,y:f*u}}var nP=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:a,placement:s,middlewareData:c}=t,l=await tP(t,e);return s===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:a+l.y,data:{...l,placement:s}}}}},rP=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:a}=t,{mainAxis:s=!0,crossAxis:c=!1,limiter:l={fn:b=>{let{x:w,y:_}=b;return{x:w,y:_}}},...d}=hn(e,t),u={x:n,y:r},p=await a.detectOverflow(t,d),m=Jt(gn(i)),f=wd(m);let y=u[f],g=u[m];if(s){const b=f==="y"?"top":"left",w=f==="y"?"bottom":"right",_=y+p[b],I=y-p[w];y=_d(_,y,I)}if(c){const b=m==="y"?"top":"left",w=m==="y"?"bottom":"right",_=g+p[b],I=g-p[w];g=_d(_,g,I)}const h=l.fn({...t,[f]:y,[m]:g});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[f]:s,[m]:c}}}}}},iP=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:a,middlewareData:s}=t,{offset:c=0,mainAxis:l=!0,crossAxis:d=!0}=hn(e,t),u={x:n,y:r},p=Jt(i),m=wd(p);let f=u[m],y=u[p];const g=hn(c,t),h=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const _=m==="y"?"height":"width",I=a.reference[m]-a.floating[_]+h.mainAxis,N=a.reference[m]+a.reference[_]-h.mainAxis;f<I?f=I:f>N&&(f=N)}if(d){var b,w;const _=m==="y"?"width":"height",I=nv.has(gn(i)),N=a.reference[p]-a.floating[_]+(I&&((b=s.offset)==null?void 0:b[p])||0)+(I?0:h.crossAxis),T=a.reference[p]+a.reference[_]+(I?0:((w=s.offset)==null?void 0:w[p])||0)-(I?h.crossAxis:0);y<N?y=N:y>T&&(y=T)}return{[m]:f,[p]:y}}}},aP=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:a,platform:s,elements:c}=t,{apply:l=()=>{},...d}=hn(e,t),u=await s.detectOverflow(t,d),p=gn(i),m=fi(i),f=Jt(i)==="y",{width:y,height:g}=a.floating;let h,b;p==="top"||p==="bottom"?(h=p,b=m===(await(s.isRTL==null?void 0:s.isRTL(c.floating))?"start":"end")?"left":"right"):(b=p,h=m==="end"?"top":"bottom");const w=g-u.top-u.bottom,_=y-u.left-u.right,I=Mn(g-u[h],w),N=Mn(y-u[b],_),T=!t.middlewareData.shift;let x=I,j=N;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=_),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(x=w),T&&!m){const P=wt(u.left,0),F=wt(u.right,0),O=wt(u.top,0),G=wt(u.bottom,0);f?j=y-2*(P!==0||F!==0?P+F:wt(u.left,u.right)):x=g-2*(O!==0||G!==0?O+G:wt(u.top,u.bottom))}await l({...t,availableWidth:j,availableHeight:x});const B=await s.getDimensions(c.floating);return y!==B.width||g!==B.height?{reset:{rects:!0}}:{}}}};function ws(){return typeof window<"u"}function hi(e){return rv(e)?(e.nodeName||"").toLowerCase():"#document"}function St(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Yt(e){var t;return(t=(rv(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function rv(e){return ws()?e instanceof Node||e instanceof St(e).Node:!1}function jt(e){return ws()?e instanceof Element||e instanceof St(e).Element:!1}function vn(e){return ws()?e instanceof HTMLElement||e instanceof St(e).HTMLElement:!1}function iv(e){return!ws()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof St(e).ShadowRoot}function wa(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=Ot(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function oP(e){return/^(table|td|th)$/.test(hi(e))}function Ss(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}var sP=/transform|translate|scale|rotate|perspective|filter/,cP=/paint|layout|strict|content/,Cr=e=>!!e&&e!=="none",Id;function kd(e){const t=jt(e)?Ot(e):e;return Cr(t.transform)||Cr(t.translate)||Cr(t.scale)||Cr(t.rotate)||Cr(t.perspective)||!Td()&&(Cr(t.backdropFilter)||Cr(t.filter))||sP.test(t.willChange||"")||cP.test(t.contain||"")}function lP(e){let t=jn(e);for(;vn(t)&&!gi(t);){if(kd(t))return t;if(Ss(t))return null;t=jn(t)}return null}function Td(){return Id==null&&(Id=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Id}function gi(e){return/^(html|body|#document)$/.test(hi(e))}function Ot(e){return St(e).getComputedStyle(e)}function Cs(e){return jt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function jn(e){if(hi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||iv(e)&&e.host||Yt(e);return iv(t)?t.host:t}function av(e){const t=jn(e);return gi(t)?e.ownerDocument?e.ownerDocument.body:e.body:vn(t)&&wa(t)?t:av(t)}function Sa(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=av(e),a=i===((r=e.ownerDocument)==null?void 0:r.body),s=St(i);if(a){const c=Rd(s);return t.concat(s,s.visualViewport||[],wa(i)?i:[],c&&n?Sa(c):[])}else return t.concat(i,Sa(i,[],n))}function Rd(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ov(e){const t=Ot(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=vn(e),a=i?e.offsetWidth:n,s=i?e.offsetHeight:r,c=vs(n)!==a||vs(r)!==s;return c&&(n=a,r=s),{width:n,height:r,$:c}}function Pd(e){return jt(e)?e:e.contextElement}function vi(e){const t=Pd(e);if(!vn(t))return zt(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:a}=ov(t);let s=(a?vs(n.width):n.width)/r,c=(a?vs(n.height):n.height)/i;return(!s||!Number.isFinite(s))&&(s=1),(!c||!Number.isFinite(c))&&(c=1),{x:s,y:c}}var dP=zt(0);function sv(e){const t=St(e);return!Td()||!t.visualViewport?dP:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function uP(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==St(e)?!1:t}function Nr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),a=Pd(e);let s=zt(1);t&&(r?jt(r)&&(s=vi(r)):s=vi(e));const c=uP(a,n,r)?sv(a):zt(0);let l=(i.left+c.x)/s.x,d=(i.top+c.y)/s.y,u=i.width/s.x,p=i.height/s.y;if(a){const m=St(a),f=r&&jt(r)?St(r):r;let y=m,g=Rd(y);for(;g&&r&&f!==y;){const h=vi(g),b=g.getBoundingClientRect(),w=Ot(g),_=b.left+(g.clientLeft+parseFloat(w.paddingLeft))*h.x,I=b.top+(g.clientTop+parseFloat(w.paddingTop))*h.y;l*=h.x,d*=h.y,u*=h.x,p*=h.y,l+=_,d+=I,y=St(g),g=Rd(y)}}return _s({width:u,height:p,x:l,y:d})}function Ns(e,t){const n=Cs(e).scrollLeft;return t?t.left+n:Nr(Yt(e)).left+n}function cv(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Ns(e,n),y:n.top+t.scrollTop}}function pP(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const a=i==="fixed",s=Yt(r),c=t?Ss(t.floating):!1;if(r===s||c&&a)return n;let l={scrollLeft:0,scrollTop:0},d=zt(1);const u=zt(0),p=vn(r);if((p||!p&&!a)&&((hi(r)!=="body"||wa(s))&&(l=Cs(r)),p)){const f=Nr(r);d=vi(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=s&&!p&&!a?cv(s,l):zt(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-l.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-l.scrollTop*d.y+u.y+m.y}}function mP(e){return Array.from(e.getClientRects())}function fP(e){const t=Yt(e),n=Cs(e),r=e.ownerDocument.body,i=wt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),a=wt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+Ns(e);const c=-n.scrollTop;return Ot(r).direction==="rtl"&&(s+=wt(t.clientWidth,r.clientWidth)-i),{width:i,height:a,x:s,y:c}}var lv=25;function hP(e,t){const n=St(e),r=Yt(e),i=n.visualViewport;let a=r.clientWidth,s=r.clientHeight,c=0,l=0;if(i){a=i.width,s=i.height;const u=Td();(!u||u&&t==="fixed")&&(c=i.offsetLeft,l=i.offsetTop)}const d=Ns(r);if(d<=0){const u=r.ownerDocument,p=u.body,m=getComputedStyle(p),f=u.compatMode==="CSS1Compat"&&parseFloat(m.marginLeft)+parseFloat(m.marginRight)||0,y=Math.abs(r.clientWidth-p.clientWidth-f);y<=lv&&(a-=y)}else d<=lv&&(a+=d);return{width:a,height:s,x:c,y:l}}function gP(e,t){const n=Nr(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=vn(e)?vi(e):zt(1);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function dv(e,t,n){let r;if(t==="viewport")r=hP(e,n);else if(t==="document")r=fP(Yt(e));else if(jt(t))r=gP(t,n);else{const i=sv(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return _s(r)}function uv(e,t){const n=jn(e);return n===t||!jt(n)||gi(n)?!1:Ot(n).position==="fixed"||uv(n,t)}function vP(e,t){const n=t.get(e);if(n)return n;let r=Sa(e,[],!1).filter(c=>jt(c)&&hi(c)!=="body"),i=null;const a=Ot(e).position==="fixed";let s=a?jn(e):e;for(;jt(s)&&!gi(s);){const c=Ot(s),l=kd(s);!l&&c.position==="fixed"&&(i=null),(a?!l&&!i:!l&&c.position==="static"&&i&&(i.position==="absolute"||i.position==="fixed")||wa(s)&&!l&&uv(e,s))?r=r.filter(d=>d!==s):i=c,s=jn(s)}return t.set(e,r),r}function yP(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const a=[...n==="clippingAncestors"?Ss(t)?[]:vP(t,this._c):[].concat(n),r],s=dv(t,a[0],i);let c=s.top,l=s.right,d=s.bottom,u=s.left;for(let p=1;p<a.length;p++){const m=dv(t,a[p],i);c=wt(m.top,c),l=Mn(m.right,l),d=Mn(m.bottom,d),u=wt(m.left,u)}return{width:l-u,height:d-c,x:u,y:c}}function bP(e){const{width:t,height:n}=ov(e);return{width:t,height:n}}function _P(e,t,n){const r=vn(t),i=Yt(t),a=n==="fixed",s=Nr(e,!0,a,t);let c={scrollLeft:0,scrollTop:0};const l=zt(0);function d(){l.x=Ns(i)}if(r||!r&&!a)if((hi(t)!=="body"||wa(i))&&(c=Cs(t)),r){const p=Nr(t,!0,a,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else i&&d();a&&!r&&i&&d();const u=i&&!r&&!a?cv(i,c):zt(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 Ad(e){return Ot(e).position==="static"}function pv(e,t){if(!vn(e)||Ot(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Yt(e)===n&&(n=n.ownerDocument.body),n}function mv(e,t){const n=St(e);if(Ss(e))return n;if(!vn(e)){let i=jn(e);for(;i&&!gi(i);){if(jt(i)&&!Ad(i))return i;i=jn(i)}return n}let r=pv(e,t);for(;r&&oP(r)&&Ad(r);)r=pv(r,t);return r&&gi(r)&&Ad(r)&&!kd(r)?n:r||lP(e)||n}var wP=async function(e){const t=this.getOffsetParent||mv,n=this.getDimensions,r=await n(e.floating);return{reference:_P(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function SP(e){return Ot(e).direction==="rtl"}var CP={convertOffsetParentRelativeRectToViewportRelativeRect:pP,getDocumentElement:Yt,getClippingRect:yP,getOffsetParent:mv,getElementRects:wP,getClientRects:mP,getDimensions:bP,getScale:vi,isElement:jt,isRTL:SP};function fv(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function NP(e,t){let n=null,r;const i=Yt(e);function a(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function s(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),a();const d=e.getBoundingClientRect(),{left:u,top:p,width:m,height:f}=d;if(c||t(),!m||!f)return;const y=ys(p),g=ys(i.clientWidth-(u+m)),h=ys(i.clientHeight-(p+f)),b=ys(u),w={rootMargin:-y+"px "+-g+"px "+-h+"px "+-b+"px",threshold:wt(0,Mn(1,l))||1};let _=!0;function I(N){const T=N[0].intersectionRatio;if(T!==l){if(!_)return s();T?s(!1,T):r=setTimeout(()=>{s(!1,1e-7)},1e3)}T===1&&!fv(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),a}function IP(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,d=Pd(e),u=i||a?[...d?Sa(d):[],...t?Sa(t):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),a&&b.addEventListener("resize",n)});const p=d&&c?NP(d,n):null;let m=-1,f=null;s&&(f=new ResizeObserver(b=>{let[w]=b;w&&w.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var _;(_=f)==null||_.observe(t)})),n()}),d&&!l&&f.observe(d),t&&f.observe(t));let y,g=l?Nr(e):null;l&&h();function h(){const b=Nr(e);g&&!fv(g,b)&&n(),g=b,y=requestAnimationFrame(h)}return n(),()=>{var b;u.forEach(w=>{i&&w.removeEventListener("scroll",n),a&&w.removeEventListener("resize",n)}),p?.(),(b=f)==null||b.disconnect(),f=null,l&&cancelAnimationFrame(y)}}var kP=nP,TP=rP,RP=ZR,PP=aP,AP=eP,hv=QR,EP=iP,xP=(e,t,n)=>{const r=new Map,i={platform:CP,...n},a={...i.platform,_c:r};return XR(e,t,{...i,platform:a})},Is=typeof document<"u"?gt:function(){};function ks(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(!ks(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const a=i[r];if(!(a==="_owner"&&e.$$typeof)&&!ks(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function gv(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function vv(e,t){const n=gv(e);return Math.round(t*n)/n}function Ed(e){const t=q(e);return Is(()=>{t.current=e}),t}function DP(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:a,floating:s}={},transform:c=!0,whileElementsMounted:l,open:d}=e,[u,p]=D({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=D(r);ks(m,r)||f(r);const[y,g]=D(null),[h,b]=D(null),w=oe(L=>{L!==T.current&&(T.current=L,g(L))},[]),_=oe(L=>{L!==x.current&&(x.current=L,b(L))},[]),I=a||y,N=s||h,T=q(null),x=q(null),j=q(u),B=l!=null,P=Ed(l),F=Ed(i),O=Ed(d),G=oe(()=>{if(!T.current||!x.current)return;const L={placement:t,strategy:n,middleware:m};F.current&&(L.platform=F.current),xP(T.current,x.current,L).then(U=>{const V={...U,isPositioned:O.current!==!1};$.current&&!ks(j.current,V)&&(j.current=V,Lo(()=>{p(V)}))})},[m,t,n,F,O]);Is(()=>{d===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,p(L=>({...L,isPositioned:!1})))},[d]);const $=q(!1);Is(()=>($.current=!0,()=>{$.current=!1}),[]),Is(()=>{if(I&&(T.current=I),N&&(x.current=N),I&&N){if(P.current)return P.current(I,N,G);G()}},[I,N,G,P,B]);const A=Se(()=>({reference:T,floating:x,setReference:w,setFloating:_}),[w,_]),E=Se(()=>({reference:I,floating:N}),[I,N]),C=Se(()=>{const L={position:n,left:0,top:0};if(!E.floating)return L;const U=vv(E.floating,u.x),V=vv(E.floating,u.y);return c?{...L,transform:"translate("+U+"px, "+V+"px)",...gv(E.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:U,top:V}},[n,c,E.floating,u.x,u.y]);return Se(()=>({...u,update:G,refs:A,elements:E,floatingStyles:C}),[u,G,A,E,C])}var LP=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?hv({element:r.current,padding:i}).fn(n):{}:r?hv({element:r,padding:i}).fn(n):{}}}},$P=(e,t)=>{const n=kP(e);return{name:n.name,fn:n.fn,options:[e,t]}},MP=(e,t)=>{const n=TP(e);return{name:n.name,fn:n.fn,options:[e,t]}},jP=(e,t)=>({fn:EP(e).fn,options:[e,t]}),OP=(e,t)=>{const n=RP(e);return{name:n.name,fn:n.fn,options:[e,t]}},FP=(e,t)=>{const n=PP(e);return{name:n.name,fn:n.fn,options:[e,t]}},BP=(e,t)=>{const n=AP(e);return{name:n.name,fn:n.fn,options:[e,t]}},UP=(e,t)=>{const n=LP(e);return{name:n.name,fn:n.fn,options:[e,t]}},qP="Arrow",yv=K((e,t)=>{const{children:n,width:r=10,height:i=5,...a}=e;return o(le.svg,{...a,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:o("polygon",{points:"0,0 30,0 15,10"})})});yv.displayName=qP;var GP=yv;function xd(e){const[t,n]=D(void 0);return Je(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let s,c;if("borderBoxSize"in a){const l=a.borderBoxSize,d=Array.isArray(l)?l[0]:l;s=d.inlineSize,c=d.blockSize}else s=e.offsetWidth,c=e.offsetHeight;n({width:s,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Dd="Popper",[bv,On]=dt(Dd),[HP,_v]=bv(Dd),wv=e=>{const{__scopePopper:t,children:n}=e,[r,i]=D(null);return o(HP,{scope:t,anchor:r,onAnchorChange:i,children:n})};wv.displayName=Dd;var Sv="PopperAnchor",Cv=K((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,a=_v(Sv,n),s=q(null),c=be(t,s),l=q(null);return W(()=>{const d=l.current;l.current=r?.current||s.current,d!==l.current&&a.onAnchorChange(l.current)}),r?null:o(le.div,{...i,ref:c})});Cv.displayName=Sv;var Ld="PopperContent",[KP,VP]=bv(Ld),Nv=K((e,t)=>{const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:a="center",alignOffset:s=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:p="partial",hideWhenDetached:m=!1,updatePositionStrategy:f="optimized",onPlaced:y,...g}=e,h=_v(Ld,n),[b,w]=D(null),_=be(t,re=>w(re)),[I,N]=D(null),T=xd(I),x=T?.width??0,j=T?.height??0,B=r+(a!=="center"?"-"+a:""),P=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},F=Array.isArray(d)?d:[d],O=F.length>0,G={padding:P,boundary:F.filter(zP),altBoundary:O},{refs:$,floatingStyles:A,placement:E,isPositioned:C,middlewareData:L}=DP({strategy:"fixed",placement:B,whileElementsMounted:(...re)=>IP(...re,{animationFrame:f==="always"}),elements:{reference:h.anchor},middleware:[$P({mainAxis:i+j,alignmentAxis:s}),l&&MP({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?jP():void 0,...G}),l&&OP({...G}),FP({...G,apply:({elements:re,rects:Pe,availableWidth:ue,availableHeight:H})=>{const{width:fe,height:ae}=Pe.reference,Te=re.floating.style;Te.setProperty("--radix-popper-available-width",`${ue}px`),Te.setProperty("--radix-popper-available-height",`${H}px`),Te.setProperty("--radix-popper-anchor-width",`${fe}px`),Te.setProperty("--radix-popper-anchor-height",`${ae}px`)}}),I&&UP({element:I,padding:c}),JP({arrowWidth:x,arrowHeight:j}),m&&BP({strategy:"referenceHidden",...G})]}),[U,V]=Tv(E),de=pt(y);Je(()=>{C&&de?.()},[C,de]);const ie=L.arrow?.x,ne=L.arrow?.y,Re=L.arrow?.centerOffset!==0,[ye,Ce]=D();return Je(()=>{b&&Ce(window.getComputedStyle(b).zIndex)},[b]),o("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...A,transform:C?A.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ye,"--radix-popper-transform-origin":[L.transformOrigin?.x,L.transformOrigin?.y].join(" "),...L.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:o(KP,{scope:n,placedSide:U,onArrowChange:N,arrowX:ie,arrowY:ne,shouldHideArrow:Re,children:o(le.div,{"data-side":U,"data-align":V,...g,ref:_,style:{...g.style,animation:C?void 0:"none"}})})})});Nv.displayName=Ld;var Iv="PopperArrow",WP={top:"bottom",right:"left",bottom:"top",left:"right"},kv=K(function(t,n){const{__scopePopper:r,...i}=t,a=VP(Iv,r),s=WP[a.placedSide];return o("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:o(GP,{...i,ref:n,style:{...i.style,display:"block"}})})});kv.displayName=Iv;function zP(e){return e!==null}var JP=e=>({name:"transformOrigin",options:e,fn(t){const{placement:n,rects:r,middlewareData:i}=t,a=i.arrow?.centerOffset!==0,s=a?0:e.arrowWidth,c=a?0:e.arrowHeight,[l,d]=Tv(n),u={start:"0%",center:"50%",end:"100%"}[d],p=(i.arrow?.x??0)+s/2,m=(i.arrow?.y??0)+c/2;let f="",y="";return l==="bottom"?(f=a?u:`${p}px`,y=`${-c}px`):l==="top"?(f=a?u:`${p}px`,y=`${r.floating.height+c}px`):l==="right"?(f=`${-c}px`,y=a?u:`${m}px`):l==="left"&&(f=`${r.floating.width+c}px`,y=a?u:`${m}px`),{data:{x:f,y}}}});function Tv(e){const[t,n="center"]=e.split("-");return[t,n]}var Ca=wv,Na=Cv,Ts=Nv,Rs=kv,Ps="Popover",[Rv,aU]=dt(Ps,[On]),Ia=On(),[YP,Fn]=Rv(Ps),Pv=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:a,modal:s=!1}=e,c=Ia(t),l=q(null),[d,u]=D(!1),[p,m]=kt({prop:r,defaultProp:i??!1,onChange:a,caller:Ps});return o(Ca,{...c,children:o(YP,{scope:t,contentId:ut(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:oe(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:oe(()=>u(!0),[]),onCustomAnchorRemove:oe(()=>u(!1),[]),modal:s,children:n})})};Pv.displayName=Ps;var Av="PopoverAnchor",Ev=K((e,t)=>{const{__scopePopover:n,...r}=e,i=Fn(Av,n),a=Ia(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:c}=i;return W(()=>(s(),()=>c()),[s,c]),o(Na,{...a,...r,ref:t})});Ev.displayName=Av;var xv="PopoverTrigger",Dv=K((e,t)=>{const{__scopePopover:n,...r}=e,i=Fn(xv,n),a=Ia(n),s=be(t,i.triggerRef),c=o(le.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Ov(i.open),...r,ref:s,onClick:X(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:o(Na,{asChild:!0,...a,children:c})});Dv.displayName=xv;var $d="PopoverPortal",[XP,QP]=Rv($d,{forceMount:void 0}),Lv=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,a=Fn($d,t);return o(XP,{scope:t,forceMount:n,children:o(ot,{present:n||a.open,children:o(fr,{asChild:!0,container:i,children:r})})})};Lv.displayName=$d;var yi="PopoverContent",$v=K((e,t)=>{const n=QP(yi,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,a=Fn(yi,e.__scopePopover);return o(ot,{present:r||a.open,children:a.modal?o(eA,{...i,ref:t}):o(tA,{...i,ref:t})})});$v.displayName=yi;var ZP=pr("PopoverContent.RemoveScroll"),eA=K((e,t)=>{const n=Fn(yi,e.__scopePopover),r=q(null),i=be(t,r),a=q(!1);return W(()=>{const s=r.current;if(s)return Ko(s)},[]),o(na,{as:ZP,allowPinchZoom:!0,children:o(Mv,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:X(e.onCloseAutoFocus,s=>{s.preventDefault(),a.current||n.triggerRef.current?.focus()}),onPointerDownOutside:X(e.onPointerDownOutside,s=>{const c=s.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0;a.current=c.button===2||l},{checkForDefaultPrevented:!1}),onFocusOutside:X(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),tA=K((e,t)=>{const n=Fn(yi,e.__scopePopover),r=q(!1),i=q(!1);return o(Mv,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(r.current||n.triggerRef.current?.focus(),a.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(r.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const s=a.target;n.triggerRef.current?.contains(s)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Mv=K((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:s,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:u,...p}=e,m=Fn(yi,n),f=Ia(n);return jo(),o(ea,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o(mr,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:o(Ts,{"data-state":Ov(m.open),role:"dialog",id:m.contentId,...f,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),jv="PopoverClose",nA=K((e,t)=>{const{__scopePopover:n,...r}=e,i=Fn(jv,n);return o(le.button,{type:"button",...r,ref:t,onClick:X(e.onClick,()=>i.onOpenChange(!1))})});nA.displayName=jv;var rA="PopoverArrow",iA=K((e,t)=>{const{__scopePopover:n,...r}=e,i=Ia(n);return o(Rs,{...i,...r,ref:t})});iA.displayName=rA;function Ov(e){return e?"open":"closed"}var Fv=Pv,aA=Ev,oA=Dv,Bv=Lv,Uv=$v;function Md(e){return e.trim()}function qv({values:e,onValuesChange:t,availableProjects:n,placeholder:r,emptyLabel:i,disabled:a,"aria-labelledby":s}){const[c,l]=D(!1),[d,u]=D(""),[p,m]=D(0),f=q(null),y=Se(()=>{const P=new Set,F=[];for(const O of[...n,...e]){const G=Md(O);!G||P.has(G)||(P.add(G),F.push(G))}return F.sort((O,G)=>O.localeCompare(G))},[n,e]),g=Md(d),h=g.toLowerCase(),b=Se(()=>h?y.filter(P=>P.toLowerCase().includes(h)):y,[y,h]),w=g?y.some(P=>P.toLowerCase()===h):!1,_=!!g&&!w,I=b.length+(_?1:0);W(()=>{p>=I&&m(Math.max(0,I-1))},[I,p]),W(()=>{if(!c)return;const P=requestAnimationFrame(()=>f.current?.focus());return()=>cancelAnimationFrame(P)},[c]);const N=P=>{e.includes(P)?t(e.filter(F=>F!==P)):t(Array.from(new Set([...e,P])))},T=P=>{const F=Md(P);F&&(t(Array.from(new Set([...e,F]))),u(""),m(0))},x=P=>{if(P<b.length){const F=b[P];F&&N(F);return}_&&T(g)},j=P=>{if(P.key==="ArrowDown"){P.preventDefault(),m(F=>Math.min(I-1,F+1));return}if(P.key==="ArrowUp"){P.preventDefault(),m(F=>Math.max(0,F-1));return}if(P.key==="Enter"){P.preventDefault(),x(p);return}},B=P=>{t(e.filter(F=>F!==P))};return o("div",{class:"project-scope-picker",children:[o("ul",{"aria-labelledby":s,class:"project-scope-picker-selected",children:e.length===0?o("li",{class:"project-scope-picker-selected-empty",children:i||"No projects selected."}):e.map(P=>o("li",{class:"project-scope-picker-selected-chip",children:[o("span",{children:P}),a?null:o("button",{"aria-label":`Remove ${P}`,class:"project-scope-picker-selected-remove",onClick:()=>B(P),type:"button",children:"×"})]},P))}),o(Fv,{onOpenChange:P=>{l(P),P||(u(""),m(0))},open:c,children:[o(oA,{asChild:!0,children:o("button",{class:"project-scope-picker-trigger settings-button",disabled:a,type:"button",children:[o("span",{"aria-hidden":"true",children:"+"}),o("span",{children:r||"Add project"})]})}),o(Bv,{children:o(Uv,{align:"start",class:"project-scope-picker-popover",sideOffset:6,children:[o("input",{"aria-label":"Search projects",class:"project-scope-picker-search",onInput:P=>{u(P.currentTarget.value),m(0)},onKeyDown:j,placeholder:"Search or create…",ref:f,type:"text",value:d}),o("div",{class:"project-scope-picker-results",role:"listbox",children:[b.length===0&&!_?o("div",{class:"project-scope-picker-empty-row",children:"No projects yet. Type a name to create one."}):null,b.map((P,F)=>{const O=e.includes(P);return o("button",{"aria-selected":O,class:F===p?"project-scope-picker-row project-scope-picker-row--active":"project-scope-picker-row",onClick:()=>{m(F),N(P)},onMouseEnter:()=>m(F),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:O?"✓":""}),o("span",{class:"project-scope-picker-row-label",children:P})]},P)}),_?o("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:()=>m(b.length),role:"option",type:"button",children:[o("span",{class:"project-scope-picker-row-check","aria-hidden":"true",children:"+"}),o("span",{class:"project-scope-picker-row-label",children:`Create "${g}"`})]}):null]})]})})]})]})}function jd(e){const t=q({value:e,previous:e});return Se(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var As="Switch",[sA,oU]=dt(As),[cA,lA]=sA(As),Gv=K((e,t)=>{const{__scopeSwitch:n,name:r,checked:i,defaultChecked:a,required:s,disabled:c,value:l="on",onCheckedChange:d,form:u,...p}=e,[m,f]=D(null),y=be(t,_=>f(_)),g=q(!1),h=m?u||!!m.closest("form"):!0,[b,w]=kt({prop:i,defaultProp:a??!1,onChange:d,caller:As});return o(cA,{scope:n,checked:b,disabled:c,children:[o(le.button,{type:"button",role:"switch","aria-checked":b,"aria-required":s,"data-state":Wv(b),"data-disabled":c?"":void 0,disabled:c,value:l,...p,ref:y,onClick:X(e.onClick,_=>{w(I=>!I),h&&(g.current=_.isPropagationStopped(),g.current||_.stopPropagation())})}),h&&o(Vv,{control:m,bubbles:!g.current,name:r,value:l,checked:b,required:s,disabled:c,form:u,style:{transform:"translateX(-100%)"}})]})});Gv.displayName=As;var Hv="SwitchThumb",Kv=K((e,t)=>{const{__scopeSwitch:n,...r}=e,i=lA(Hv,n);return o(le.span,{"data-state":Wv(i.checked),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Kv.displayName=Hv;var dA="SwitchBubbleInput",Vv=K(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=q(null),c=be(s,a),l=jd(n),d=xd(t);return W(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Vv.displayName=dA;function Wv(e){return e?"checked":"unchecked"}var uA=Gv,pA=Kv;function bi({"aria-labelledby":e,checked:t,className:n,disabled:r=!1,id:i,name:a,onCheckedChange:s,thumbClassName:c}){return o(uA,{"aria-labelledby":e,checked:t,className:n,disabled:r,id:i,name:a,onCheckedChange:s,children:o(pA,{className:c})})}function J(e,t="success"){VT(e,t)}function yn(e){return String(e||"").trim().replace(/\/+$/u,"")}function zv(e){return`${$R}:${yn(e)}`}function mA(e){try{return localStorage.getItem(zv(e))||""}catch{return""}}function fA(e,t){try{localStorage.setItem(zv(e),t)}catch{}}function bn(){return String(S.coordinatorAdminTargetGroup||"").trim()}function Es(){const e=String(S.lastCoordinatorAdminStatus?.coordinator_url||"").trim(),t=bn()||String(S.lastCoordinatorAdminStatus?.active_group||"").trim()||Bn()[0]?.group_id||"";return e&&t?{coordinatorUrl:e,groupId:t}:null}function Ct(e){const t=Es();return!!(e&&t&&yn(e.coordinatorUrl)===yn(t.coordinatorUrl)&&e.groupId===t.groupId)}function Od(e){S.coordinatorAdminTargetGroup=e,fA(S.lastCoordinatorAdminStatus?.coordinator_url||null,e)}function Bn(){return(Array.isArray(S.lastCoordinatorAdminGroups)?S.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 Fd(e,t){const n=String(t||"").trim(),r=Bn(),i=new Set(r.map(l=>String(l.display_name||"").trim()).filter(Boolean));n&&i.add(n);for(const[l,d]of R.groupPresentationAliases)i.has(d)&&R.groupPresentationAliases.delete(l);if(n)return n;const a=R.groupPresentationAliases.get(e);if(a)return a;for(const l of R.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 R.groupPresentationAliases.set(e,c),c}function hA(){const e=new Map;for(const t of Bn())e.set(t.group_id,t.display_name||"");R.groupRenameDrafts.clear();for(const[t,n]of e.entries())R.groupRenameDrafts.set(t,n)}function gA(){const e=bn();return Bn().find(t=>t.group_id===e)||null}function Jv(){const e=S.lastCoordinatorAdminStatus,t=Bn(),n=String(e?.active_group||"").trim(),r=mA(e?.coordinator_url||null),i=bn(),a=new Set(t.map(l=>l.group_id)),s=i||r||n||t[0]?.group_id||"",c=s&&(a.size===0||a.has(s))?s:n||t[0]?.group_id||"";return Od(c),c}function vA(){const e=new Map,t=new Map,n=Array.isArray(S.lastCoordinatorAdminDevices)?S.lastCoordinatorAdminDevices:[];for(const r of n){const i=String(r.device_id||"").trim();if(!i)continue;const a=String(r.display_name||""),s=R.deviceRenameDrafts.get(i),c=R.deviceRenameServerNames.get(i),l=s!==void 0&&(c===void 0||s!==c);e.set(i,l?s:a),t.set(i,a)}R.deviceRenameDrafts.clear();for(const[r,i]of e.entries())R.deviceRenameDrafts.set(r,i);R.deviceRenameServerNames.clear();for(const[r,i]of t.entries())R.deviceRenameServerNames.set(r,i)}function yA(e,t){return t&&t.groupId===e?t:null}function bA(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 _A(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 wA(e){return e?.loaded?e.scopes.filter(t=>String(t.status||"active")==="active").length:null}function SA(e){const t=wA(e);return t===null?"Open Spaces to inspect access grants":`${t} active ${t===1?"Space":"Spaces"}`}function CA(e){const t=yA(e.groupId,e.setupGuide);return{autoGrant:_A(e.preferences,t),defaultSpace:bA(e.preferences,t),spaces:SA(e.scopeManagement)}}var Bd=null,xs=null,Ud=null;function NA(){return Bd}function qd(e){xs=e}function Yv(e){Ud=e}function IA(e){return Ud===e}function kA(e){return e?e.kind==="confirm"?!1:e.kind==="input"?null:{action:"cancel"}:null}function Gd(e){return!Bd||!xs?!0:(console.warn(`Ignored sync ${e} dialog request because another sync dialog is already open.`),!1)}function Ds(e){Bd=e,Ud?.(e)}function Un(e){const t=xs;xs=null,Ds(null),t?.(e)}function TA(e){return e==="danger"?"sync-dialog-confirm danger":"sync-dialog-confirm"}var RA=K(function({value:t,onValueChange:n,suggestions:r,onSubmit:i,maxSuggestions:a=20,onKeyDown:s,onFocus:c,onBlur:l,className:d,...u},p){const m=q(null);Eo(p,()=>m.current,[]);const[f,y]=D(!1),[g,h]=D(-1),b=Se(()=>{const N=t.trim().toLowerCase();return(N?r.filter(T=>T.toLowerCase().includes(N)):r).slice(0,a)},[t,r,a]);W(()=>{g>=b.length&&h(b.length-1)},[b.length,g]);const w=f&&b.length>0,_=N=>{n(N),y(!1),h(-1),m.current?.focus()};return o(Fv,{open:w,onOpenChange:y,children:[o(aA,{asChild:!0,children:o("input",{...u,ref:m,className:d,value:t,onInput:N=>{n(N.currentTarget.value),y(!0),h(-1)},onFocus:N=>{c?.(N)},onBlur:N=>{window.setTimeout(()=>y(!1),120),l?.(N)},onKeyDown:N=>{if(N.key==="ArrowDown"){N.preventDefault(),y(!0),h(T=>b.length===0?-1:Math.min(T+1,b.length-1));return}if(N.key==="ArrowUp"){N.preventDefault(),f||y(!0),h(T=>Math.max(T-1,-1));return}if(N.key==="Escape"&&w){N.preventDefault(),y(!1),h(-1);return}if((N.key==="Tab"||N.key==="Enter")&&g>=0){const T=b[g];if(T){N.preventDefault(),_(T);return}}if(N.key==="Enter"&&i){N.preventDefault(),i();return}s?.(N)},role:"combobox","aria-autocomplete":"list","aria-expanded":w,"aria-controls":"autocompleteListbox","aria-activedescendant":g>=0?`autocomplete-option-${g}`:void 0})}),o(Bv,{children:o(Uv,{align:"start",className:"autocomplete-popover",onOpenAutoFocus:N=>N.preventDefault(),onCloseAutoFocus:N=>N.preventDefault(),sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},children:o("div",{className:"autocomplete-listbox",id:"autocompleteListbox",role:"listbox",children:b.map((N,T)=>{const x=T===g;return o("div",{"aria-selected":x,className:x?"autocomplete-option active":"autocomplete-option",id:`autocomplete-option-${T}`,onMouseDown:j=>{j.preventDefault(),_(N)},onMouseEnter:()=>h(T),role:"option",tabIndex:-1,children:N},N)})})})})]})}),Hd="Radio",[PA,Xv]=dt(Hd),[AA,EA]=PA(Hd),Qv=K((e,t)=>{const{__scopeRadio:n,name:r,checked:i=!1,required:a,disabled:s,value:c="on",onCheck:l,form:d,...u}=e,[p,m]=D(null),f=be(t,h=>m(h)),y=q(!1),g=p?d||!!p.closest("form"):!0;return o(AA,{scope:n,checked:i,disabled:s,children:[o(le.button,{type:"button",role:"radio","aria-checked":i,"data-state":ny(i),"data-disabled":s?"":void 0,disabled:s,value:c,...u,ref:f,onClick:X(e.onClick,h=>{i||l?.(),g&&(y.current=h.isPropagationStopped(),y.current||h.stopPropagation())})}),g&&o(ty,{control:p,bubbles:!y.current,name:r,value:c,checked:i,required:a,disabled:s,form:d,style:{transform:"translateX(-100%)"}})]})});Qv.displayName=Hd;var Zv="RadioIndicator",ey=K((e,t)=>{const{__scopeRadio:n,forceMount:r,...i}=e,a=EA(Zv,n);return o(ot,{present:r||a.checked,children:o(le.span,{"data-state":ny(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:t})})});ey.displayName=Zv;var xA="RadioBubbleInput",ty=K(({__scopeRadio:e,control:t,checked:n,bubbles:r=!0,...i},a)=>{const s=q(null),c=be(s,a),l=jd(n),d=xd(t);return W(()=>{const u=s.current;if(!u)return;const p=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&m){const f=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(f)}},[l,n,r]),o(le.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...i,tabIndex:-1,ref:c,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});ty.displayName=xA;function ny(e){return e?"checked":"unchecked"}var DA=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ls="RadioGroup",[LA,sU]=dt(Ls,[pi,Xv]),ry=pi(),iy=Xv(),[$A,MA]=LA(Ls),ay=K((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:i,value:a,required:s=!1,disabled:c=!1,orientation:l,dir:d,loop:u=!0,onValueChange:p,...m}=e,f=ry(n),y=ga(d),[g,h]=kt({prop:a,defaultProp:i??null,onChange:p,caller:Ls});return o($A,{scope:n,name:r,required:s,disabled:c,value:g,onValueChange:h,children:o(dd,{asChild:!0,...f,orientation:l,dir:y,loop:u,children:o(le.div,{role:"radiogroup","aria-required":s,"aria-orientation":l,"data-disabled":c?"":void 0,dir:y,...m,ref:t})})})});ay.displayName=Ls;var oy="RadioGroupItem",sy=K((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...i}=e,a=MA(oy,n),s=a.disabled||r,c=ry(n),l=iy(n),d=q(null),u=be(t,d),p=a.value===i.value,m=q(!1);return W(()=>{const f=g=>{DA.includes(g.key)&&(m.current=!0)},y=()=>m.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",y)}},[]),o(ud,{asChild:!0,...c,focusable:!s,active:p,children:o(Qv,{disabled:s,required:a.required,checked:p,...l,...i,name:a.name,ref:u,onCheck:()=>a.onValueChange(i.value),onKeyDown:X(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:X(i.onFocus,()=>{m.current&&d.current?.click()})})})});sy.displayName=oy;var jA="RadioGroupIndicator",cy=K((e,t)=>{const{__scopeRadioGroup:n,...r}=e;return o(ey,{...iy(n),...r,ref:t})});cy.displayName=jA;var OA=ay,FA=sy,BA=cy;function UA({ariaDescribedby:e,ariaLabel:t,autoFocusValue:n,indicatorClassName:r,itemClassName:i,itemLabelClassName:a,name:s,onValueChange:c,options:l,rootClassName:d,value:u}){return o(OA,{"aria-describedby":e,"aria-label":t,className:d,name:s,onValueChange:c,value:u,children:l.map((p,m)=>{const f=`radio-option-input-${m}`,y=`radio-option-label-${m}`;return o("label",{className:i,htmlFor:f,children:[o(FA,{id:f,"aria-labelledby":y,autoFocus:n===p.value,disabled:p.disabled,value:p.value,children:o(BA,{className:r})}),o("span",{className:a,id:y,children:p.label})]},p.value)})})}function ly(e,[t,n]){return Math.min(n,Math.max(t,e))}var qA=[" ","Enter","ArrowUp","ArrowDown"],GA=[" ","Enter"],Ir="Select",[$s,Ms,HA]=os(Ir),[_i,cU]=dt(Ir,[HA,On]),js=On(),[KA,qn]=_i(Ir),[VA,WA]=_i(Ir),dy=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:a,value:s,defaultValue:c,onValueChange:l,dir:d,name:u,autoComplete:p,disabled:m,required:f,form:y}=e,g=js(t),[h,b]=D(null),[w,_]=D(null),[I,N]=D(!1),T=ga(d),[x,j]=kt({prop:r,defaultProp:i??!1,onChange:a,caller:Ir}),[B,P]=kt({prop:s,defaultProp:c,onChange:l,caller:Ir}),F=q(null),O=h?y||!!h.closest("form"):!0,[G,$]=D(new Set),A=Array.from(G).map(E=>E.props.value).join(";");return o(Ca,{...g,children:o(KA,{required:f,scope:t,trigger:h,onTriggerChange:b,valueNode:w,onValueNodeChange:_,valueNodeHasChildren:I,onValueNodeHasChildrenChange:N,contentId:ut(),value:B,onValueChange:P,open:x,onOpenChange:j,dir:T,triggerPointerDownPosRef:F,disabled:m,children:[o($s.Provider,{scope:t,children:o(VA,{scope:e.__scopeSelect,onNativeOptionAdd:oe(E=>{$(C=>new Set(C).add(E))},[]),onNativeOptionRemove:oe(E=>{$(C=>{const L=new Set(C);return L.delete(E),L})},[]),children:n})}),O?o(Ay,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:p,value:B,onChange:E=>P(E.target.value),disabled:m,form:y,children:[B===void 0?o("option",{value:""}):null,Array.from(G)]},A):null]})})};dy.displayName=Ir;var uy="SelectTrigger",py=K((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,a=js(n),s=qn(uy,n),c=s.disabled||r,l=be(t,s.onTriggerChange),d=Ms(n),u=q("touch"),[p,m,f]=xy(g=>{const h=d().filter(w=>!w.disabled),b=Dy(h,g,h.find(w=>w.value===s.value));b!==void 0&&s.onValueChange(b.value)}),y=g=>{c||(s.onOpenChange(!0),f()),g&&(s.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return o(Na,{asChild:!0,...a,children:o(le.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Ey(s.value)?"":void 0,...i,ref:l,onClick:X(i.onClick,g=>{g.currentTarget.focus(),u.current!=="mouse"&&y(g)}),onPointerDown:X(i.onPointerDown,g=>{u.current=g.pointerType;const h=g.target;h.hasPointerCapture(g.pointerId)&&h.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(y(g),g.preventDefault())}),onKeyDown:X(i.onKeyDown,g=>{const h=p.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&m(g.key),!(h&&g.key===" ")&&qA.includes(g.key)&&(y(),g.preventDefault())})})})});py.displayName=uy;var my="SelectValue",fy=K((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:a,placeholder:s="",...c}=e,l=qn(my,n),{onValueNodeHasChildrenChange:d}=l,u=a!==void 0,p=be(t,l.onValueNodeChange);return Je(()=>{d(u)},[d,u]),o(le.span,{...c,ref:p,style:{pointerEvents:"none"},children:Ey(l.value)?o(z,{children:s}):a})});fy.displayName=my;var zA="SelectIcon",hy=K((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return o(le.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});hy.displayName=zA;var JA="SelectPortal",gy=e=>o(fr,{asChild:!0,...e});gy.displayName=JA;var kr="SelectContent",vy=K((e,t)=>{const n=qn(kr,e.__scopeSelect),[r,i]=D();if(Je(()=>{i(new DocumentFragment)},[]),!n.open){const a=r;return a?dn(o(yy,{scope:e.__scopeSelect,children:o($s.Slot,{scope:e.__scopeSelect,children:o("div",{children:e.children})})}),a):null}return o(by,{...e,ref:t})});vy.displayName=kr;var Ft=10,[yy,Gn]=_i(kr),YA="SelectContentImpl",XA=pr("SelectContent.RemoveScroll"),by=K((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:s,side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:y,hideWhenDetached:g,avoidCollisions:h,...b}=e,w=qn(kr,n),[_,I]=D(null),[N,T]=D(null),x=be(t,re=>I(re)),[j,B]=D(null),[P,F]=D(null),O=Ms(n),[G,$]=D(!1),A=q(!1);W(()=>{if(_)return Ko(_)},[_]),jo();const E=oe(re=>{const[Pe,...ue]=O().map(ae=>ae.ref.current),[H]=ue.slice(-1),fe=document.activeElement;for(const ae of re)if(ae===fe||(ae?.scrollIntoView({block:"nearest"}),ae===Pe&&N&&(N.scrollTop=0),ae===H&&N&&(N.scrollTop=N.scrollHeight),ae?.focus(),document.activeElement!==fe))return},[O,N]),C=oe(()=>E([j,_]),[E,j,_]);W(()=>{G&&C()},[G,C]);const{onOpenChange:L,triggerPointerDownPosRef:U}=w;W(()=>{if(_){let re={x:0,y:0};const Pe=H=>{re={x:Math.abs(Math.round(H.pageX)-(U.current?.x??0)),y:Math.abs(Math.round(H.pageY)-(U.current?.y??0))}},ue=H=>{re.x<=10&&re.y<=10?H.preventDefault():_.contains(H.target)||L(!1),document.removeEventListener("pointermove",Pe),U.current=null};return U.current!==null&&(document.addEventListener("pointermove",Pe),document.addEventListener("pointerup",ue,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Pe),document.removeEventListener("pointerup",ue,{capture:!0})}}},[_,L,U]),W(()=>{const re=()=>L(!1);return window.addEventListener("blur",re),window.addEventListener("resize",re),()=>{window.removeEventListener("blur",re),window.removeEventListener("resize",re)}},[L]);const[V,de]=xy(re=>{const Pe=O().filter(H=>!H.disabled),ue=Dy(Pe,re,Pe.find(H=>H.ref.current===document.activeElement));ue&&setTimeout(()=>ue.ref.current.focus())}),ie=oe((re,Pe,ue)=>{const H=!A.current&&!ue;(w.value!==void 0&&w.value===Pe||H)&&(B(re),H&&(A.current=!0))},[w.value]),ne=oe(()=>_?.focus(),[_]),Re=oe((re,Pe,ue)=>{const H=!A.current&&!ue;(w.value!==void 0&&w.value===Pe||H)&&F(re)},[w.value]),ye=r==="popper"?Kd:_y,Ce=ye===Kd?{side:c,sideOffset:l,align:d,alignOffset:u,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:y,hideWhenDetached:g,avoidCollisions:h}:{};return o(yy,{scope:n,content:_,viewport:N,onViewportChange:T,itemRefCallback:ie,selectedItem:j,onItemLeave:ne,itemTextRefCallback:Re,focusSelectedItem:C,selectedItemText:P,position:r,isPositioned:G,searchRef:V,children:o(na,{as:XA,allowPinchZoom:!0,children:o(ea,{asChild:!0,trapped:w.open,onMountAutoFocus:re=>{re.preventDefault()},onUnmountAutoFocus:X(i,re=>{w.trigger?.focus({preventScroll:!0}),re.preventDefault()}),children:o(mr,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:re=>re.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:o(ye,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:re=>re.preventDefault(),...b,...Ce,onPlaced:()=>$(!0),ref:x,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:X(b.onKeyDown,re=>{const Pe=re.ctrlKey||re.altKey||re.metaKey;if(re.key==="Tab"&&re.preventDefault(),!Pe&&re.key.length===1&&de(re.key),["ArrowUp","ArrowDown","Home","End"].includes(re.key)){let ue=O().filter(H=>!H.disabled).map(H=>H.ref.current);if(["ArrowUp","End"].includes(re.key)&&(ue=ue.slice().reverse()),["ArrowUp","ArrowDown"].includes(re.key)){const H=re.target,fe=ue.indexOf(H);ue=ue.slice(fe+1)}setTimeout(()=>E(ue)),re.preventDefault()}})})})})})})});by.displayName=YA;var QA="SelectItemAlignedPosition",_y=K((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,a=qn(kr,n),s=Gn(kr,n),[c,l]=D(null),[d,u]=D(null),p=be(t,T=>u(T)),m=Ms(n),f=q(!1),y=q(!0),{viewport:g,selectedItem:h,selectedItemText:b,focusSelectedItem:w}=s,_=oe(()=>{if(a.trigger&&a.valueNode&&c&&d&&g&&h&&b){const T=a.trigger.getBoundingClientRect(),x=d.getBoundingClientRect(),j=a.valueNode.getBoundingClientRect(),B=b.getBoundingClientRect();if(a.dir!=="rtl"){const ue=B.left-x.left,H=j.left-ue,fe=T.left-H,ae=T.width+fe,Te=Math.max(ae,x.width),ce=window.innerWidth-Ft,Be=ly(H,[Ft,Math.max(Ft,ce-Te)]);c.style.minWidth=ae+"px",c.style.left=Be+"px"}else{const ue=x.right-B.right,H=window.innerWidth-j.right-ue,fe=window.innerWidth-T.right-H,ae=T.width+fe,Te=Math.max(ae,x.width),ce=window.innerWidth-Ft,Be=ly(H,[Ft,Math.max(Ft,ce-Te)]);c.style.minWidth=ae+"px",c.style.right=Be+"px"}const P=m(),F=window.innerHeight-Ft*2,O=g.scrollHeight,G=window.getComputedStyle(d),$=parseInt(G.borderTopWidth,10),A=parseInt(G.paddingTop,10),E=parseInt(G.borderBottomWidth,10),C=parseInt(G.paddingBottom,10),L=$+A+O+C+E,U=Math.min(h.offsetHeight*5,L),V=window.getComputedStyle(g),de=parseInt(V.paddingTop,10),ie=parseInt(V.paddingBottom,10),ne=T.top+T.height/2-Ft,Re=F-ne,ye=h.offsetHeight/2,Ce=h.offsetTop+ye,re=$+A+Ce,Pe=L-re;if(re<=ne){const ue=P.length>0&&h===P[P.length-1].ref.current;c.style.bottom="0px";const H=d.clientHeight-g.offsetTop-g.offsetHeight,fe=re+Math.max(Re,ye+(ue?ie:0)+H+E);c.style.height=fe+"px"}else{const ue=P.length>0&&h===P[0].ref.current;c.style.top="0px";const H=Math.max(ne,$+g.offsetTop+(ue?de:0)+ye)+Pe;c.style.height=H+"px",g.scrollTop=re-ne+g.offsetTop}c.style.margin=`${Ft}px 0`,c.style.minHeight=U+"px",c.style.maxHeight=F+"px",r?.(),requestAnimationFrame(()=>f.current=!0)}},[m,a.trigger,a.valueNode,c,d,g,h,b,a.dir,r]);Je(()=>_(),[_]);const[I,N]=D();return Je(()=>{d&&N(window.getComputedStyle(d).zIndex)},[d]),o(eE,{scope:n,contentWrapper:c,shouldExpandOnScrollRef:f,onScrollButtonChange:oe(T=>{T&&y.current===!0&&(_(),w?.(),y.current=!1)},[_,w]),children:o("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:I},children:o(le.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});_y.displayName=QA;var ZA="SelectPopperPosition",Kd=K((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Ft,...a}=e,s=js(n);return o(Ts,{...s,...a,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...a.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});Kd.displayName=ZA;var[eE,Vd]=_i(kr,{}),Wd="SelectViewport",wy=K((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,a=Gn(Wd,n),s=Vd(Wd,n),c=be(t,a.onViewportChange),l=q(0);return o(z,{children:[o("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),o($s.Slot,{scope:n,children:o(le.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:X(i.onScroll,d=>{const u=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=s;if(m?.current&&p){const f=Math.abs(l.current-u.scrollTop);if(f>0){const y=window.innerHeight-Ft*2,g=parseFloat(p.style.minHeight),h=parseFloat(p.style.height),b=Math.max(g,h);if(b<y){const w=b+f,_=Math.min(y,w),I=w-_;p.style.height=_+"px",p.style.bottom==="0px"&&(u.scrollTop=I>0?I:0,p.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});wy.displayName=Wd;var Sy="SelectGroup",[tE,nE]=_i(Sy),rE=K((e,t)=>{const{__scopeSelect:n,...r}=e,i=ut();return o(tE,{scope:n,id:i,children:o(le.div,{role:"group","aria-labelledby":i,...r,ref:t})})});rE.displayName=Sy;var Cy="SelectLabel",iE=K((e,t)=>{const{__scopeSelect:n,...r}=e,i=nE(Cy,n);return o(le.div,{id:i.id,...r,ref:t})});iE.displayName=Cy;var Os="SelectItem",[aE,Ny]=_i(Os),Iy=K((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:a,...s}=e,c=qn(Os,n),l=Gn(Os,n),d=c.value===r,[u,p]=D(a??""),[m,f]=D(!1),y=be(t,w=>l.itemRefCallback?.(w,r,i)),g=ut(),h=q("touch"),b=()=>{i||(c.onValueChange(r),c.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return o(aE,{scope:n,value:r,disabled:i,textId:g,isSelected:d,onItemTextChange:oe(w=>{p(_=>_||(w?.textContent??"").trim())},[]),children:o($s.ItemSlot,{scope:n,value:r,disabled:i,textValue:u,children:o(le.div,{role:"option","aria-labelledby":g,"data-highlighted":m?"":void 0,"aria-selected":d&&m,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...s,ref:y,onFocus:X(s.onFocus,()=>f(!0)),onBlur:X(s.onBlur,()=>f(!1)),onClick:X(s.onClick,()=>{h.current!=="mouse"&&b()}),onPointerUp:X(s.onPointerUp,()=>{h.current==="mouse"&&b()}),onPointerDown:X(s.onPointerDown,w=>{h.current=w.pointerType}),onPointerMove:X(s.onPointerMove,w=>{h.current=w.pointerType,i?l.onItemLeave?.():h.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:X(s.onPointerLeave,w=>{w.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:X(s.onKeyDown,w=>{l.searchRef?.current!==""&&w.key===" "||(GA.includes(w.key)&&b(),w.key===" "&&w.preventDefault())})})})})});Iy.displayName=Os;var ka="SelectItemText",ky=K((e,t)=>{const{__scopeSelect:n,className:r,style:i,...a}=e,s=qn(ka,n),c=Gn(ka,n),l=Ny(ka,n),d=WA(ka,n),[u,p]=D(null),m=be(t,b=>p(b),l.onItemTextChange,b=>c.itemTextRefCallback?.(b,l.value,l.disabled)),f=u?.textContent,y=Se(()=>o("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:g,onNativeOptionRemove:h}=d;return Je(()=>(g(y),()=>h(y)),[g,h,y]),o(z,{children:[o(le.span,{id:l.textId,...a,ref:m}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?dn(a.children,s.valueNode):null]})});ky.displayName=ka;var Ty="SelectItemIndicator",Ry=K((e,t)=>{const{__scopeSelect:n,...r}=e;return Ny(Ty,n).isSelected?o(le.span,{"aria-hidden":!0,...r,ref:t}):null});Ry.displayName=Ty;var zd="SelectScrollUpButton",oE=K((e,t)=>{const n=Gn(zd,e.__scopeSelect),r=Vd(zd,e.__scopeSelect),[i,a]=D(!1),s=be(t,r.onScrollButtonChange);return Je(()=>{if(n.viewport&&n.isPositioned){let c=function(){a(l.scrollTop>0)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Py,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop-l.offsetHeight)}}):null});oE.displayName=zd;var Jd="SelectScrollDownButton",sE=K((e,t)=>{const n=Gn(Jd,e.__scopeSelect),r=Vd(Jd,e.__scopeSelect),[i,a]=D(!1),s=be(t,r.onScrollButtonChange);return Je(()=>{if(n.viewport&&n.isPositioned){let c=function(){const d=l.scrollHeight-l.clientHeight;a(Math.ceil(l.scrollTop)<d)};const l=n.viewport;return c(),l.addEventListener("scroll",c),()=>l.removeEventListener("scroll",c)}},[n.viewport,n.isPositioned]),i?o(Py,{...e,ref:s,onAutoScroll:()=>{const{viewport:c,selectedItem:l}=n;c&&l&&(c.scrollTop=c.scrollTop+l.offsetHeight)}}):null});sE.displayName=Jd;var Py=K((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,a=Gn("SelectScrollButton",n),s=q(null),c=Ms(n),l=oe(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return W(()=>()=>l(),[l]),Je(()=>{c().find(d=>d.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[c]),o(le.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:X(i.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:X(i.onPointerMove,()=>{a.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:X(i.onPointerLeave,()=>{l()})})}),cE="SelectSeparator",lE=K((e,t)=>{const{__scopeSelect:n,...r}=e;return o(le.div,{"aria-hidden":!0,...r,ref:t})});lE.displayName=cE;var Yd="SelectArrow",dE=K((e,t)=>{const{__scopeSelect:n,...r}=e,i=js(n),a=qn(Yd,n),s=Gn(Yd,n);return a.open&&s.position==="popper"?o(Rs,{...i,...r,ref:t}):null});dE.displayName=Yd;var uE="SelectBubbleInput",Ay=K(({__scopeSelect:e,value:t,...n},r)=>{const i=q(null),a=be(r,i),s=jd(t);return W(()=>{const c=i.current;if(!c)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==t&&d){const u=new Event("change",{bubbles:!0});d.call(c,t),c.dispatchEvent(u)}},[s,t]),o(le.select,{...n,style:{...Zh,...n.style},ref:a,defaultValue:t})});Ay.displayName=uE;function Ey(e){return e===""||e===void 0}function xy(e){const t=pt(e),n=q(""),r=q(0),i=oe(s=>{const c=n.current+s;t(c),(function l(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(c)},[t]),a=oe(()=>{n.current="",window.clearTimeout(r.current)},[]);return W(()=>()=>window.clearTimeout(r.current),[]),[n,i,a]}function Dy(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=pE(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.textValue.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function pE(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var mE=dy,fE=py,hE=fy,gE=hy,vE=gy,yE=vy,bE=wy,_E=Iy,wE=ky,SE=Ry,Ly="__codemem-empty-select__";function CE(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Open"}),o("path",{d:"m6 9 6 6 6-6"})]})}function NE(){return o("svg",{"aria-hidden":"true",fill:"none",height:"14",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",width:"14",children:[o("title",{children:"Selected"}),o("path",{d:"M20 6 9 17l-5-5"})]})}function Xd(e){return e===""?Ly:e}function IE(e){return e===Ly?"":e}function Hn({ariaLabel:e,className:t,contentClassName:n,disabled:r=!1,id:i,itemClassName:a,onValueChange:s,options:c,placeholder:l,triggerClassName:d,value:u,viewportClassName:p}){const m=u?Xd(u):void 0;return o(mE,{disabled:r,onValueChange:f=>s(IE(f)),value:m,children:[o(fE,{"aria-label":e,className:d??t,"data-value":u,id:i,type:"button",children:[o(hE,{placeholder:l}),o(gE,{className:"sync-radix-select-icon","aria-hidden":"true",children:o(CE,{})})]}),o(vE,{children:o(yE,{className:n,position:"popper",children:o(bE,{className:p,children:c.map(f=>o(_E,{className:a,disabled:f.disabled,value:Xd(f.value),children:[o(wE,{children:f.label}),o(SE,{className:"sync-radix-select-indicator",children:o(NE,{})})]},Xd(f.value)))})})})]})}function kE({descriptionId:e,request:t}){const[n,r]=D("choice"),[i,a]=D(t.actors.find(h=>h.isLocal)?.actorId||t.actors[0]?.actorId||""),[s,c]=D("");W(()=>{r("choice");const h=t.actors.find(w=>w.isLocal)?.actorId||t.actors[0]?.actorId||"",b=t.actors.find(w=>w.actorId!==h)?.actorId||"";a(h),c(b)},[t]);const l=t.actors.find(h=>h.actorId===i)||t.actors[0],d=t.actors.filter(h=>h.actorId!==i),u=d.find(h=>h.actorId===s)||d[0],p=t.actors.map(h=>({label:o(z,{children:[h.label,h.isLocal?" (You)":""]}),value:h.actorId})),m=d.map(h=>({label:`${h.label}${h.isLocal?" (You)":""}`,value:h.actorId})),f=!!(l?.actorId&&u?.actorId),y=()=>{!l?.actorId||!u?.actorId||Un({action:"merge",primaryActorId:l.actorId,secondaryActorId:u.actorId})},g=h=>{const b=h.target instanceof HTMLElement?h.target:null;h.defaultPrevented||h.isComposing||h.key!=="Enter"||b?.closest(".sync-dialog-radio-list")&&f&&(h.preventDefault(),y())};return n==="choice"?o("div",{className:"sync-dialog-stack",children:o("ul",{className:"sync-dialog-choice-list",children:[o("li",{children:o("button",{autoFocus:!0,className:"settings-button","data-primary-action":"true","data-sync-primary-action":"true",onClick:()=>r("merge"),type:"button",children:"These are both me"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>Un({action:"different-people"}),type:"button",children:"These are different people"})}),o("li",{children:o("button",{className:"settings-button",onClick:()=>Un({action:"cancel"}),type:"button",children:"Decide later"})})]})}):o("div",{className:"sync-dialog-stack",onKeyDown:h=>{g(h),ui(h,{onSubmit:y,disabled:!f})},children:[o("div",{className:"small",id:e,children:"Choose which person should remain after combining these duplicates."}),o(UA,{ariaDescribedby:e,ariaLabel:"Person to keep after combining duplicates",autoFocusValue:i,indicatorClassName:"sync-dialog-radio-indicator",itemClassName:"sync-dialog-radio-option",itemLabelClassName:"sync-dialog-radio-label",name:"syncDuplicatePrimaryActor",onValueChange:a,options:p,rootClassName:"sync-dialog-radio-list",value:i}),o("div",{className:"field",children:[o("label",{className:"small",htmlFor:"syncDuplicateSecondaryActor",children:"Person to combine into the selected record"}),o(Hn,{ariaLabel:"Person to combine into the selected record",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:m.length===0,id:"syncDuplicateSecondaryActor",itemClassName:"sync-radix-select-item",onValueChange:c,options:m,placeholder:"No merge target available",triggerClassName:"sync-radix-select-trigger sync-dialog-input",value:u?.actorId||"",viewportClassName:"sync-radix-select-viewport"})]}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button",onClick:()=>r("choice"),type:"button",children:"Back"}),o("button",{className:"settings-button","data-primary-action":"true",disabled:!f,onClick:y,type:"button",children:"Combine people"})]})]})}function TE({descriptionId:e,request:t,titleId:n}){const[r,i]=D(t.kind==="input"&&t.initialValue||""),[a,s]=D(null),c=t.kind!=="duplicate-person",l="syncDialogInputError";W(()=>{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"){Un(!0);return}if(t.kind==="duplicate-person")return;const m=r.trim(),f=t.validate?.(m)||null;if(f){s(f);return}Un(m)};return o("div",{className:"modal-card sync-dialog-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:n,children:t.title}),o(Zr,{ariaLabel:`Close ${t.title}`,onClick:()=>Un(t.kind==="confirm"?!1:null)})]}),o("div",{className:"modal-body",children:[t.kind!=="duplicate-person"?o("div",{className:"small",id:e,children:t.description}):null,t.kind==="duplicate-person"?o("div",{className:"small",id:e,children:t.summary}):null,t.kind==="input"?o("div",{className:"field",children:[t.suggestions?.length?o(RA,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onSubmit:p,onValueChange:m=>{i(m),a&&s(null)},placeholder:t.placeholder,suggestions:t.suggestions,value:r}):o(_e,{"aria-describedby":a?`${e} ${l}`:e,autoFocus:!0,className:a?"sync-dialog-input sync-field-error":"sync-dialog-input","data-sync-primary-action":"true",onInput:m=>{i(m.currentTarget.value),a&&s(null)},onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},placeholder:t.placeholder,type:"text",value:r}),a?o("div",{className:"sync-field-hint",id:l,children:a}):null]}):null,t.kind==="duplicate-person"?o(kE,{descriptionId:e,request:t}):null]}),o("div",{className:"modal-footer",children:[o("div",{className:"small"}),o("div",{className:"sync-dialog-actions",children:[o("button",{className:"settings-button","data-sync-dialog-action":"cancel",onClick:()=>Un(t.kind==="confirm"?!1:null),type:"button",children:d}),t.kind!=="duplicate-person"?o("button",{autoFocus:!0,className:`settings-button ${TA(t.kind==="confirm"?t.tone:void 0)}`,"data-sync-dialog-action":"confirm",onClick:p,type:"button",children:u}):null]})]})]})}function RE(){const[e,t]=D(NA());W(()=>(Yv(t),()=>{IA(t)&&Yv(null)}),[]);const n=!!e,r=Se(()=>`sync-dialog-title-${e?.kind||"none"}`,[e?.kind]),i=Se(()=>`sync-dialog-description-${e?.kind||"none"}`,[e?.kind]);return e?o(gr,{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||Un(e?.kind==="confirm"?!1:null)},open:n,overlayClassName:"modal-backdrop",overlayId:"syncDialogBackdrop",children:e?o(TE,{descriptionId:i,request:e,titleId:r}):null}):null}var Tr=null;function Fs(){Tr?.isConnected||(Tr=document.getElementById("syncDialogMount"),Tr||(Tr=document.createElement("div"),Tr.id="syncDialogMount",document.body.appendChild(Tr)),He(o(RE,{}),Tr))}function Xt(e){return Fs(),Gd("confirm")?new Promise(t=>{qd(n=>t(!!n)),Ds({kind:"confirm",...e})}):Promise.resolve(!1)}function Qd(e){return Fs(),Gd("input")?new Promise(t=>{qd(n=>t(typeof n=="string"?n:null)),Ds({kind:"input",...e})}):Promise.resolve(null)}function PE(e){return Fs(),Gd("duplicate-person")?new Promise(t=>{qd(n=>t(n||{action:"cancel"})),Ds({kind:"duplicate-person",...e})}):Promise.resolve(kA({kind:"duplicate-person",...e}))}function AE(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 EE(e){const t=String(e||"active").trim();return t?t.replaceAll("_"," "):"active"}function $y(e){const t=String(e.label||"").trim()||"Untitled Space",n=EE(e.status),r=String(e.kind||"user").replaceAll("_"," "),i=String(e.scope_id||"").trim()||"unknown",a=e.membership_epoch==null?"—":String(e.membership_epoch);return{title:t,summary:`${n} Space · ${r}`,advancedDetail:`Space ID ${i} · Membership epoch ${a}`}}function xE(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 DE(e,t,n){return`Revoke ${t||"this device"} from ${$y(e).title}?`}function LE(e,t,n=ps()){const r=ms(e,n),i=new Map(t.map(a=>[String(a.device_id||"").trim(),a]).filter(([a])=>a.length>0));return e.map(a=>{const s=String(a.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:a.enabled!==!1&&a.enabled!==0,status:d,role:String(c?.role||"member"),membershipEpoch:u,updatedAt:c?.updated_at?String(c.updated_at):null}}).filter(a=>a!==null).sort((a,s)=>{const c={active:0,revoked:1,not_member:2};return c[a.status]-c[s.status]||a.displayName.localeCompare(s.displayName,void 0,{numeric:!0})})}function $E(e,t,n,r){const i=String(n||"").trim();return r||e.length>0||!i?e:t.filter(a=>String(a.group_id||"").trim()===i)}var lU=8;function ME(){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 Bs(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 Fe(e){let t=R.groupScopeManagementDrafts.get(e);return t||(t=ME(),R.groupScopeManagementDrafts.set(e,t)),t}function qe(e,t){R.groupScopeManagementDrafts.set(e,t)}function Zd(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 Ta(){J("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning")}function wi(e,t){return e.availability==="fresh"&&!e.loading&&(!t||e.memberAvailabilityByScope.get(t)==="fresh")&&fn(R.recovery,"status","groups")}async function jE(e,t,n){const r=new Array(e.length);let i=0;async function a(){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)},()=>a())),r}async function Rr(e,t,n=Fe(e).includeInactive){const r=Fe(e),i=r.loadGeneration+1;qe(e,{...r,loading:!0,error:"",includeInactive:n,loadGeneration:i,recoveryAnnouncement:r.recoveryRetryRequested?r.recoveryAnnouncement:""});const a=()=>R.groupScopeManagementDrafts.get(e)?.loadGeneration===i;t();try{const[l,d]=await Promise.all([YS(e,n),um(e,!0)]);if(!a())return;const u=Bs(l),p=Bs(d),m=await jE(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:Bs(await dm(e,_,!0))}}catch{return{scopeId:_,attempted:!0}}});if(!a())return;const f=Fe(e),y=[...m,...u.slice(8).map(w=>({scopeId:String(w.scope_id||"").trim(),attempted:!1}))],g=new Map,h=new Map;for(const w of y){if(!w.scopeId)continue;if(w.members){g.set(w.scopeId,w.members),h.set(w.scopeId,"fresh");continue}const _=f.membersByScope.get(w.scopeId),I=f.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 b=y.filter(w=>w.attempted&&w.scopeId&&!w.members).length;qe(e,{...f,loaded:!0,loading:!1,availability:"fresh",recoveryAnnouncement:b?"":f.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(!a())return;const l=Fe(e),d=l.availability==="fresh"||l.availability==="stale";qe(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(!a())return;const s=Fe(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;qe(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&&qe(e,{...s,recoveryAnnouncement:"Retry finished, but some Space data still needs attention. Retained details remain unchanged.",recoveryFocusPending:!0,recoveryRetryRequested:!1});t();const c=Fe(e);c.recoveryFocusPending&&(qe(e,{...c,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coordinatorAdminSpacesStatus-${e}`)?.focus()))}function eu(e,t){R.groupScopeManagementOpen.add(e),Fe(e),t(),Rr(e,t)}function My(e,t){R.groupScopeManagementOpen.delete(e),t()}async function OE(e,t,n){const r=Fe(e);if(!wi(r)){Ta();return}if(r.actionPendingKey)return;const i=r.loadGeneration,a=R.loadGeneration;qe(e,{...r,actionPendingKey:`load:${t}`,actionPendingKind:"load"}),n();try{const s=await dm(e,t,!0),c=Fe(e);if(c.loadGeneration!==i||R.loadGeneration!==a||!wi(c)){c.actionPendingKey===`load:${t}`&&(qe(e,{...c,actionPendingKey:"",actionPendingKind:""}),n()),Ta();return}const l=new Map(c.membersByScope);l.set(t,Bs(s));const d=new Map(c.memberAvailabilityByScope);d.set(t,"fresh"),qe(e,{...c,membersByScope:l,memberAvailabilityByScope:d,actionPendingKey:"",actionPendingKind:"",error:""})}catch{const s=Fe(e);if(s.loadGeneration!==i)return;const c=new Map(s.memberAvailabilityByScope);c.set(t,s.membersByScope.has(t)?"stale":"unavailable"),qe(e,{...s,memberAvailabilityByScope:c,actionPendingKey:"",actionPendingKind:"",error:"Membership details could not be loaded. Existing Space data is unchanged."})}n()}async function FE(e,t){const n=Fe(e);if(!wi(n)){Ta();return}if(n.actionPendingKey)return;const r=n.createScopeId.trim(),i=n.createLabel.trim(),a=n.createKind.trim()||"team";if(!r||!i){J("Enter a Space ID and label before creating a Space.","warning");return}qe(e,{...n,actionPendingKey:`create:${r}`,actionPendingKind:"create",error:""}),t();try{await XS(e,{scope_id:r,label:i,kind:a});const s=Fe(e);qe(e,{...s,createScopeId:"",createLabel:"",createKind:"team",createPanelOpen:!1,actionPendingKey:"",actionPendingKind:""}),J("Space created. Grant devices explicitly before data can sync."),await Rr(e,t,s.includeInactive),queueMicrotask(()=>document.getElementById(`coordinatorAdminCreateSpaceTrigger-${e}`)?.focus())}catch(s){qe(e,{...Fe(e),actionPendingKey:"",actionPendingKind:"",error:Zd(s,"Could not create the legacy Space. Sharing policy is unchanged; retry after coordinator recovery.")}),t()}}async function BE(e,t,n,r){const i=Fe(e);if(!wi(i,t)){Ta();return}const a=`grant:${t}:${n}`;if(!i.actionPendingKey){qe(e,{...i,actionPendingKey:a,actionPendingKind:"grant",error:""}),r();try{await QS(e,t,{device_id:n,role:"member"});const s=Fe(e);qe(e,{...s,actionPendingKey:"",actionPendingKind:""}),J("Device granted access to the Space."),await Rr(e,r,s.includeInactive)}catch(s){qe(e,{...Fe(e),actionPendingKey:"",actionPendingKind:"",error:Zd(s,"Could not grant legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),r()}}}async function UE(e,t,n,r,i){const a=String(t.scope_id||"").trim();if(!a)return;const s=Fe(e);if(!wi(s,a)){Ta();return}const c=s.loadGeneration,l=R.loadGeneration;if(!await Xt({title:DE(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=Fe(e),u=d.scopes.find(f=>String(f.scope_id||"").trim()===a),p=d.membersByScope.get(a)?.find(f=>String(f.device_id||"")===n&&String(f.status||"active")==="active");if(d.loadGeneration!==c||R.loadGeneration!==l||!wi(d,a)||!u||!p||d.actionPendingKey){J("Space membership data changed while confirmation was open. Review current access and try again.","warning");return}const m=`revoke:${a}:${n}`;qe(e,{...d,actionPendingKey:m,actionPendingKind:"revoke",error:""}),i();try{await ZS(e,a,n);const f=Fe(e);qe(e,{...f,actionPendingKey:"",actionPendingKind:""}),J("Space access revoked. Future sync is blocked for that device."),await Rr(e,i,f.includeInactive)}catch(f){qe(e,{...Fe(e),actionPendingKey:"",actionPendingKind:"",error:Zd(f,"Could not revoke legacy Space transport access. Sharing policy is unchanged; retry after coordinator recovery.")}),i()}}function qE(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=Ct(R.devicesSnapshotTarget)?S.lastCoordinatorAdminDevices:[],c=LE($E(n.devices,s,e,n.devicesLoaded),n.membersByScope.get(a)??[],R.unnamedDeviceAliases);return c.length?v("div",{class:"coordinator-admin-scope-member-list"},c.map(l=>{const d=`${n.actionPendingKind}:${a}:${l.deviceId}`,u=n.actionPendingKey===d,p=l.enabled&&l.status!=="active",m=l.status==="active",f=xE(l);return v("div",{class:"coordinator-admin-scope-member-row",key:l.deviceId},v("div",{class:"coordinator-admin-scope-member-copy"},v("strong",null,l.displayName),v("span",null,f.detail),v("details",{class:"coordinator-admin-diagnostics"},v("summary",null,"Diagnostics"),v("span",{class:"peer-meta"},f.advancedDetail)),l.enabled?null:v("span",null,"Device is disabled in this coordinator group.")),v("div",{class:"peer-actions"},p?v("button",{class:"settings-button",disabled:!r||!!n.actionPendingKey,onClick:()=>{BE(e,a,l.deviceId,i)},type:"button"},u&&n.actionPendingKind==="grant"?"Granting…":"Grant access"):null,m?v("button",{class:"settings-button danger",disabled:!r||!!n.actionPendingKey,onClick:()=>{UE(e,t,l.deviceId,l.displayName,i)},type:"button"},u&&n.actionPendingKind==="revoke"?"Revoking…":"Revoke access"):null))})):v("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 GE(e,t,n,r,i){const a=String(t.scope_id||"").trim(),s=$y(t),c=n.memberAvailabilityByScope.get(a),l=n.actionPendingKey===`load:${a}`,d=c==="stale"||c==="unavailable"||c==="deferred";return v("div",{class:"peer-card peer-card--padded coordinator-admin-scope-card",key:a||s.title},v("div",{class:"peer-title"},v("h5",{class:"coordinator-admin-card-title"},s.title),v("span",{class:"badge actor-badge"},"Legacy Space")),v("div",{class:"peer-submeta"},s.summary),v("details",{class:"coordinator-admin-diagnostics"},v("summary",null,"Diagnostics"),v("div",{class:"peer-meta"},s.advancedDetail)),v("div",{class:"peer-submeta"},"Devices below are enrolled in the coordinator group; only active Space members can sync this transport boundary."),c==="stale"?v("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"?v("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"?v("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?v("button",{class:"settings-button",disabled:!!n.actionPendingKey,onClick:()=>{OE(e,a,i)},type:"button"},l?"Loading membership…":c==="stale"?"Refresh membership":"Load membership"):null,c==="unavailable"||c==="deferred"?null:qE(e,t,n,r&&c==="fresh",i))}function tu(e,t,n){const r=[...t.memberAvailabilityByScope.values()].filter(s=>s==="stale"||s==="unavailable").length,i=t.availability==="stale"||t.availability==="unavailable"||r>0,a=()=>{const s=Fe(e);s.loading||s.actionPendingKey||(qe(e,{...s,recoveryAnnouncement:"Retrying Spaces and membership details…",recoveryRetryRequested:!0}),Rr(e,n,s.includeInactive))};return v("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?v(z,null,v("div",{class:"coordinator-admin-legacy-notice-copy"},v("h4",{class:"coordinator-admin-drawer-title"},"Spaces need attention"),t.recoveryAnnouncement?v("p",{class:"peer-submeta"},t.recoveryAnnouncement):null,v("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.`)),v("button",{class:"settings-button",disabled:t.loading||!!t.actionPendingKey,onClick:a,type:"button"},t.loading?"Retrying…":"Retry")):t.recoveryAnnouncement)}function HE(e){const{groupId:t,ready:n,summary:r,renderShell:i}=e,a=R.groupScopeManagementDrafts.get(t);if(!a)return null;const s=AE(r);if(s)return v("div",{class:"peer-meta coordinator-admin-inline-warning"},s);if(a.availability==="unavailable")return v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),v("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."),tu(t,a,i));if(!a.loaded)return v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),v("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."),tu(t,a,i),v("div",{"aria-live":"polite",class:"peer-submeta",role:"status"},"Loading Spaces…"));const c=!n||a.availability!=="fresh"||!!a.actionPendingKey||a.loading,l=a.loading||!!a.actionPendingKey,d=`coordinatorAdminCreateSpacePanel-${t}`,u=`coordinatorAdminCreateSpaceTrigger-${t}`,p=`coordinatorAdminCreateSpaceId-${t}`;return v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Spaces"),v("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."),tu(t,a,i),v(ba,{onOpenChange:m=>{qe(t,{...Fe(t),createPanelOpen:m}),i(),m&&queueMicrotask(()=>document.getElementById(p)?.focus())},open:a.createPanelOpen},v(z,null,v("div",{class:"section-actions coordinator-admin-space-toolbar"},v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:`coord-admin-domain-inactive-${t}`},"Show inactive Spaces"),v(bi,{"aria-labelledby":`coord-admin-domain-inactive-${t}`,checked:a.includeInactive,className:"coordinator-admin-switch",disabled:l,onCheckedChange:m=>{Fe(t).actionPendingKey||Rr(t,i,m)},thumbClassName:"coordinator-admin-switch-thumb"})),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:l,onClick:()=>{Fe(t).actionPendingKey||Rr(t,i,a.includeInactive)},type:"button"},a.loading?"Refreshing…":"Refresh"),v(bd,{"aria-controls":d,"aria-expanded":a.createPanelOpen,class:"settings-button coordinator-admin-scope-trigger",id:u,type:"button"},"Create legacy Space"))),v(_a,{"aria-busy":a.actionPendingKind==="create"?"true":"false","aria-labelledby":u,class:"coordinator-admin-create-space-panel",forceMount:!0,id:d},v("form",{class:"coordinator-admin-form",onSubmit:m=>{m.preventDefault(),!c&&FE(t,i)}},v("p",{class:"peer-submeta"},"Create a Space only for legacy transport or recovery. Team membership and Project access stay in Sharing."),v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"Space ID"),v(_e,{class:"peer-scope-input",disabled:c,id:p,onInput:m=>{qe(t,{...Fe(t),createScopeId:String(m.currentTarget.value||"")})},placeholder:"acme-work",type:"text",value:a.createScopeId})),v("label",{class:"coordinator-admin-field"},v("span",null,"Label"),v(_e,{class:"peer-scope-input",disabled:c,onInput:m=>{qe(t,{...Fe(t),createLabel:String(m.currentTarget.value||"")})},placeholder:"Acme Work",type:"text",value:a.createLabel})),v("label",{class:"coordinator-admin-field"},v("span",null,"Kind"),v(_e,{class:"peer-scope-input",disabled:c,onInput:m=>{qe(t,{...Fe(t),createKind:String(m.currentTarget.value||"")})},placeholder:"team",type:"text",value:a.createKind}))),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:c,type:"submit"},a.actionPendingKind==="create"?"Creating…":"Create Space")))))),a.error?v("div",{"aria-live":"assertive",class:"peer-submeta coordinator-admin-error",role:"alert"},a.error):null,a.scopes.length?v("div",{class:"coordinator-admin-scope-card-list"},a.scopes.map(m=>GE(t,m,a,n&&a.availability==="fresh"&&!a.loading,i))):v("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 jy(){return v("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"},v("title",null,"Chevron"),v("path",{d:"m9 18 6-6-6-6"}))}function KE(){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 Oy(e,t){const n=R.groupPreferencesDrafts.get(e)??KE(),r=n.loadGeneration+1;R.groupPreferencesDrafts.set(e,{...n,loading:!0,error:"",loadGeneration:r,recoveryAnnouncement:n.recoveryRetryRequested?n.recoveryAnnouncement:""});const i=()=>R.groupPreferencesDrafts.get(e)?.loadGeneration===r;t();try{const s=await rN(e);if(!i())return;const c=R.groupPreferencesDrafts.get(e)??n;R.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=R.groupPreferencesDrafts.get(e)??n,c=s.availability==="fresh"||s.availability==="stale",l=s.recoveryRetryRequested;R.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 a=R.groupPreferencesDrafts.get(e);a?.recoveryFocusPending&&(R.groupPreferencesDrafts.set(e,{...a,recoveryFocusPending:!1}),queueMicrotask(()=>document.getElementById(`coord-admin-group-defaults-recovery-${e}`)?.focus()))}async function nu(e,t){R.groupPreferencesOpen.add(e),t(),await Oy(e,t)}function Us(e,t){R.groupPreferencesOpen.delete(e),t()}function Fy(e,t){const n=R.groupPreferencesDrafts.get(e);n&&(R.groupPreferencesDrafts.set(e,{...n,recoveryAnnouncement:"Retrying group defaults…",recoveryRetryRequested:!0}),Oy(e,t))}async function VE(e,t){const n=R.groupPreferencesDrafts.get(e);if(!n||n.availability!=="fresh"||n.loading||!fn(R.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};R.groupPreferencesDrafts.set(e,{...n,saving:!0,error:""}),t();try{await iN(e,r),J("Legacy coordinator group defaults saved. Sharing policy and Project access are unchanged."),Us(e,t)}catch{const i=R.groupPreferencesDrafts.get(e);if(!i)return;R.groupPreferencesDrafts.set(e,{...i,saving:!1,error:"Could not save legacy group defaults. Sharing policy is unchanged; retry after coordinator recovery."}),t()}}function WE(e,t,n){const r=R.groupPreferencesDrafts.get(e);if(!r)return null;const i=`coord-admin-group-defaults-recovery-${e}`;if(!r.loaded&&r.availability!=="unavailable")return v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),v("div",{"aria-atomic":"true","aria-live":"polite",id:i,role:"status",tabIndex:-1},"Loading project defaults…"));if(r.availability==="unavailable")return v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),v("div",{"aria-atomic":"true","aria-live":"polite",class:"coordinator-admin-inline-warning coordinator-admin-recovery-notice",id:i,role:"status",tabIndex:-1},v("div",{class:"coordinator-admin-legacy-notice-copy"},v("strong",null,"Group defaults are unavailable"),r.recoveryAnnouncement?v("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,v("span",{class:"peer-submeta"},"Current values could not be loaded. No defaults are being assumed or changed.")),v("button",{class:"settings-button",disabled:r.loading,onClick:()=>Fy(e,t),type:"button"},r.loading?"Retrying…":"Retry")));const a=`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 v(z,null,v("h4",{class:"coordinator-admin-drawer-title"},"Legacy group defaults"),v("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"?v(z,null,v("span",{class:"peer-submeta"},"Previously loaded group defaults are shown. Saving is disabled until refresh succeeds."),r.recoveryAnnouncement?v("span",{class:"peer-submeta"},r.recoveryAnnouncement):null,v("button",{class:"settings-button",disabled:r.loading,onClick:()=>Fy(e,t),type:"button"},r.loading?"Retrying…":"Retry")):r.recoveryAnnouncement),v("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."),v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:a},"Auto-apply advanced rules to new devices"),v(bi,{"aria-labelledby":a,checked:r.auto_seed_scope,className:"coordinator-admin-switch",disabled:!d||r.saving,onCheckedChange:p=>{const m=R.groupPreferencesDrafts.get(e)??r;R.groupPreferencesDrafts.set(e,{...m,auto_seed_scope:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:s},"Auto-grant default Space on coordinator join"),v(bi,{"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 m=R.groupPreferencesDrafts.get(e)??r;R.groupPreferencesDrafts.set(e,{...m,auto_grant_default_space_on_join:p}),t()},thumbClassName:"coordinator-admin-switch-thumb"})),r.default_space_scope_id?v("div",{class:"peer-submeta"},"Default Space configured."):v("div",{class:"peer-submeta"},"No default Space has been created yet."),v("div",{class:"coordinator-admin-field"},v("span",{id:c},"Include template"),v(qv,{"aria-labelledby":c,availableProjects:R.availableProjects,disabled:u,emptyLabel:"All projects allowed.",onValuesChange:p=>{const m=R.groupPreferencesDrafts.get(e)??r;R.groupPreferencesDrafts.set(e,{...m,projects_include:p}),t()},placeholder:"Add project",values:r.projects_include}),v("span",{class:"peer-submeta"},"Leave empty to allow every project inside the granted Space. Type to search or create a new name.")),v("div",{class:"coordinator-admin-field"},v("span",{id:l},"Exclude template"),v(qv,{"aria-labelledby":l,availableProjects:R.availableProjects,disabled:u,emptyLabel:"Nothing excluded.",onValuesChange:p=>{const m=R.groupPreferencesDrafts.get(e)??r;R.groupPreferencesDrafts.set(e,{...m,projects_exclude:p}),t()},placeholder:"Add project",values:r.projects_exclude})),r.error?v("div",{class:"peer-submeta coordinator-admin-error"},r.error):null,v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:!d||r.saving,onClick:()=>{VE(e,t)},type:"button"},r.saving?"Saving…":"Save defaults"),v("button",{class:"settings-button",disabled:r.saving,onClick:()=>Us(e,t),type:"button"},"Cancel")))}function zE(e){const t=R.teamSetupGuide;if(!t)return null;const n=Fd(t.groupId,t.displayName),r={default_space:"default Space setup",default_space_grant:"default Space access grant"}[t.setupWarning?.step||""]||"default Space setup";return v("div",{class:"peer-meta coordinator-admin-empty-state"},v("h4",{class:"coordinator-admin-drawer-title"},`Set up legacy group ${n}`),v("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?v("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.`):v("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."),v("ol",{class:"peer-submeta"},v("li",null,"Review legacy group defaults and the auto-grant default Space setting."),v("li",null,"Use legacy enrollment only when compatibility or recovery requires it."),v("li",null,"Open Sharing for Team membership and Project access.")),v("div",{class:"peer-actions"},v("button",{class:"settings-button",onClick:()=>{R.groupPreferencesOpen.add(t.groupId),nu(t.groupId,e)},type:"button"},"Review legacy defaults"),v("button",{class:"settings-button",onClick:()=>{eu(t.groupId,e)},type:"button"},"Check Spaces"),v("button",{class:"settings-button",onClick:()=>{R.inviteGroup=t.groupId,R.activeSection="invites",e()},type:"button"},"Create legacy device invite"),v("button",{class:"settings-button",onClick:()=>{window.location.hash="projects"},type:"button"},"Open Projects"),v("button",{class:"settings-button",onClick:()=>{R.teamSetupGuide=null,e()},type:"button"},"Dismiss")))}function JE(e,t){return t?e?"Unarchiving…":"Archiving…":e?"Unarchive":"Archive"}function YE(e){const{summary:t,fresh:n,createGroup:r,runGroup:i,renderShell:a,reloadData:s}=e,c=Sr(R.recovery,"groups"),l=mi(R.recovery,"groups"),d=String(S.lastCoordinatorAdminStatus?.active_group||"").trim(),u=bn(),p=Bn(),m=p.filter(b=>!b.archived_at),f=p.filter(b=>b.archived_at),y=R.showArchivedGroups?p:m,g=u?p.some(b=>b.group_id===u):!1,h=[`${m.length} active`];return f.length&&h.push(`${f.length} archived`),v(wr,{className:"coordinator-admin-panel",value:"groups"},v("h3",null,"Coordinator groups"),v("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?v("p",{class:"peer-submeta"},h.join(" · ")):null,!g&&u?v("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,zE(a),(()=>{const b=!n||R.groupActionPendingKind==="create";return v("form",{class:"coordinator-admin-form",onSubmit:w=>{w.preventDefault(),!b&&r()}},v("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."),v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"New coordinator group ID"),v(_e,{class:"peer-scope-input",disabled:b,onInput:w=>{R.createGroupId=String(w.currentTarget.value||"")},placeholder:"group-alpha",type:"text",value:R.createGroupId})),v("label",{class:"coordinator-admin-field"},v("span",null,"Legacy group display name"),v(_e,{class:"peer-scope-input",disabled:b,onInput:w=>{R.createGroupDisplayName=String(w.currentTarget.value||"")},placeholder:"Legacy group Alpha",type:"text",value:R.createGroupDisplayName}))),v("div",{class:"section-actions coordinator-admin-groups-toolbar"},v("div",{class:"coordinator-admin-primary-actions"},v("button",{class:"settings-button",disabled:b,type:"submit"},R.groupActionPendingKind==="create"?"Creating…":"Create coordinator group")),v("div",{class:"coordinator-admin-secondary-actions"},v("label",{class:"coordinator-admin-inline-filter"},v("span",{class:"section-meta",id:"coordinatorAdminShowArchivedLabel"},"Show archived"),v(bi,{"aria-labelledby":"coordinatorAdminShowArchivedLabel",checked:R.showArchivedGroups,className:"coordinator-admin-switch",onCheckedChange:w=>{R.showArchivedGroups=w,a()},thumbClassName:"coordinator-admin-switch-thumb"})))))})(),l?v("div",{class:"peer-meta"},"Complete legacy coordinator setup before loading coordinator groups. No group list is expected yet."):c?y.length?v("div",{class:"peer-list"},y.map(b=>{const w=b.group_id===u,_=R.groupActionPendingId===b.group_id,I=!!b.archived_at,N=R.groupRenameDrafts.get(b.group_id)??b.display_name??"",T=N.trim()||Fd(b.group_id,b.display_name),x=R.groupPreferencesOpen.has(b.group_id),j=R.groupScopeManagementOpen.has(b.group_id),B=I?"unarchive":"archive",P=JE(I,_&&R.groupActionPendingKind===B),F=CA({groupId:b.group_id,preferences:R.groupPreferencesDrafts.get(b.group_id),scopeManagement:R.groupScopeManagementDrafts.get(b.group_id),setupGuide:R.teamSetupGuide});return v("div",{class:"peer-card peer-card--padded",key:b.group_id},v("div",{class:"peer-title"},v("strong",null,T)),v("div",{class:"peer-submeta"},I?"Archived coordinator group":"Active coordinator group"),v("details",{class:"coordinator-admin-diagnostics"},v("summary",null,"Diagnostics"),v("div",{class:"peer-meta"},`Group ID ${b.group_id}`)),v("div",{class:"coordinator-admin-summary-grid"},v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Default Space"),v("strong",null,F.defaultSpace)),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Auto-grant"),v("strong",null,F.autoGrant)),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Spaces"),v("strong",null,F.spaces))),d===b.group_id?v("div",{class:"peer-submeta"},"This node uses this coordinator group for discovery."):null,v("label",{class:"coordinator-admin-field"},v("span",null,"Legacy group display name"),v(_e,{class:"peer-scope-input",disabled:!n||_,onInput:O=>{R.groupRenameDrafts.set(b.group_id,String(O.currentTarget.value||""))},type:"text",value:N})),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:!n||w,onClick:()=>{Od(b.group_id),s()},type:"button"},w?"Managing":"Manage group"),v("button",{class:"settings-button",disabled:!n||_,onClick:()=>i(b.group_id,N,"rename"),type:"button"},_&&R.groupActionPendingKind==="rename"?"Renaming…":"Rename group"),v("button",{"aria-expanded":x,"aria-controls":`coord-admin-project-defaults-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":x?"open":"closed",disabled:_,onClick:()=>{x?Us(b.group_id,a):nu(b.group_id,a)},type:"button"},v("span",null,"Legacy group defaults"),v("span",{"aria-hidden":"true",class:"device-row-chevron"},v(jy,null))),v("button",{"aria-expanded":j,"aria-controls":`coord-admin-spaces-drawer-${b.group_id}`,class:"settings-button coordinator-admin-scope-trigger","data-state":j?"open":"closed",disabled:_,onClick:()=>{j?My(b.group_id,a):eu(b.group_id,a)},type:"button"},v("span",null,"Spaces & access"),v("span",{"aria-hidden":"true",class:"device-row-chevron"},v(jy,null))),v("button",{class:I?"settings-button":"settings-button danger",disabled:!n||_,onClick:()=>i(b.group_id,b.display_name||b.group_id,B),type:"button"},P)),v(ba,{open:x,onOpenChange:O=>{O?nu(b.group_id,a):Us(b.group_id,a)}},v(_a,{"aria-label":`Project defaults for ${T}`,class:"coordinator-admin-group-preferences",id:`coord-admin-project-defaults-drawer-${b.group_id}`},x?WE(b.group_id,a,n):null)),v(ba,{open:j,onOpenChange:O=>{O?eu(b.group_id,a):My(b.group_id,a)}},v(_a,{"aria-label":`Spaces for ${T}`,class:"coordinator-admin-group-preferences coordinator-admin-domain-management",id:`coord-admin-spaces-drawer-${b.group_id}`},j?HE({groupId:b.group_id,ready:n,renderShell:a,summary:t}):null)))})):v("div",{class:"peer-meta coordinator-admin-empty-state"},t.readiness==="ready"?R.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."):v("div",{class:"peer-meta coordinator-admin-empty-state"},"Coordinator groups are unavailable. Retry to load current groups; no empty result is being assumed."))}function Si(e){return o("textarea",{...e})}function XE(e){const{summary:t,fresh:n,createInvite:r,renderShell:i}=e,a=S.lastCoordinatorAdminStatus,s=bn()||String(a?.active_group||"").trim(),c=R.inviteGroup.trim()||s,l=String(S.lastTeamInvite?.encoded||"").trim(),d=Array.isArray(S.lastTeamInvite?.warnings)?S.lastTeamInvite?.warnings:[],u=!n||R.invitePending;return v(wr,{className:"coordinator-admin-panel",value:"invites"},v("h3",null,"Legacy coordinator invites"),v("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."),v("form",{class:"coordinator-admin-form",onSubmit:p=>{p.preventDefault(),!u&&r()}},v("div",{class:"coordinator-admin-form-grid"},v("label",{class:"coordinator-admin-field"},v("span",null,"Coordinator group"),v(_e,{class:"peer-scope-input",disabled:!n,onInput:p=>{R.inviteGroup=String(p.currentTarget.value||""),i()},placeholder:s||"group-alpha",type:"text",value:R.inviteGroup})),v("label",{class:"coordinator-admin-field"},v("span",null,"Join policy"),v(Hn,{ariaLabel:"Invite join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:!n,id:"coordinatorAdminInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:p=>{R.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:R.invitePolicy,viewportClassName:"sync-radix-select-viewport"})),v("label",{class:"coordinator-admin-field"},v("span",null,"Expires in (hours)"),v(_e,{class:"peer-scope-input",disabled:!n,min:"1",onInput:p=>{R.inviteTtlHours=String(p.currentTarget.value||"")},type:"number",value:R.inviteTtlHours}))),v("div",{class:"section-actions"},v("button",{class:"settings-button",disabled:u,type:"submit"},R.invitePending?"Creating…":"Create legacy coordinator invite"),c?v("span",{class:"peer-submeta"},"Using the selected coordinator group"):null)),l?v("label",{class:"coordinator-admin-field"},v("span",null,"Generated invite"),v(Si,{class:"feed-search coordinator-admin-output",readOnly:!0,value:l}),v("button",{class:"settings-button sync-action-copy",type:"button",onClick:p=>ma(l,p.currentTarget)},"Copy")):null,d?.length?v("div",{class:"peer-meta coordinator-admin-warning-list"},d.join(" · ")):null,v("h3",null,"Project sharing operations"),v("p",{class:"peer-submeta"},"Read-only status from the project-first sharing flow. Start new sharing from Projects."),S.lastShareOperations.length>0?v("ul",{class:"peer-scope-rejections-list","aria-label":"Project sharing operations"},...S.lastShareOperations.map(p=>v("li",{key:p.operation_id},v("strong",null,p.person.display_name),v("span",null,` — ${p.projects.map(m=>m.display_name).join(", ")} — ${p.lifecycle.label}`)))):v("div",{class:"peer-meta"},"No project sharing operations yet."))}function QE(e){const{summary:t,fresh:n,reviewJoinRequest:r,snapshotMatchesTarget:i}=e,a=i&&Sr(R.recovery,"joinRequests"),s=mi(R.recovery,"joinRequests"),c=a&&Array.isArray(S.lastCoordinatorAdminJoinRequests)?S.lastCoordinatorAdminJoinRequests:[],l=ms(c.map(d=>({device_id:String(d.device_id||"").trim()||`join-request:${String(d.request_id||"").trim()}`,display_name:d.display_name})),R.unnamedDeviceAliases);return v(wr,{className:"coordinator-admin-panel",value:"join-requests"},v("h3",null,"Pending join requests"),v("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?v("div",{class:"peer-meta"},"Complete legacy coordinator setup to load join requests. No join queue is expected yet."):a?c.length?v("div",{class:"peer-list"},c.map(d=>{const u=String(d.request_id||"").trim(),p=String(d.device_id||"").trim(),m=p||`join-request:${u}`,f=l.get(m)||"Unnamed device",y=String(d.fingerprint||"").trim(),g=[`Device ID ${p||"unknown"}`];y&&g.push(`Fingerprint ${y}`);const h=R.joinReviewPendingId===u;return v("div",{class:"peer-card peer-card--padded",key:u||p},v("div",{class:"peer-title"},v("strong",null,f)),v("details",{class:"coordinator-admin-diagnostics"},v("summary",null,"Diagnostics"),v("div",{class:"peer-meta"},`Advanced: ${g.join(" · ")}`)),v("div",{class:"peer-actions"},v("button",{class:"settings-button",disabled:!n||!u||h,onClick:()=>r(u,"approve"),type:"button"},h&&R.joinReviewPendingAction==="approve"?"Approving…":"Approve"),v("button",{class:"settings-button danger",disabled:!n||!u||h,onClick:()=>r(u,"deny"),type:"button"},h&&R.joinReviewPendingAction==="deny"?"Denying…":"Deny")))})):v("div",{class:"peer-meta"},t.readiness==="ready"?"No pending join requests right now.":"Join request review will appear here once setup is complete."):v("div",{class:"peer-meta"},"Join requests are unavailable. Retry to load the current queue; no empty result is being assumed."))}var ZE=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 ex(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 tx(e){return e instanceof Error?e.message.includes("request_not_found")||e.message.includes("join request not found"):!1}function nx(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("group_not_found")||t.includes("group not found")}function rx(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("device_not_found")||t.includes("device not found")}function ix(e){const{renderShell:t,reloadData:n}=e,r=(...d)=>fn(R.recovery,...d)?!0:(J("Coordinator data changed or is refreshing. Wait for recovery to finish, then try again.","warning"),!1);async function i(){if(!r("status","groups")||R.groupActionPendingKind)return;const d=yn(S.lastCoordinatorAdminStatus?.coordinator_url),u=R.createGroupId.trim();if(!u){J("Enter a coordinator group ID before creating a legacy group.","warning");return}const p=R.createGroupDisplayName.trim();R.groupActionPendingKind="create",t();try{const m=await VS({group_id:u,display_name:p||null});if(yn(S.lastCoordinatorAdminStatus?.coordinator_url)!==d)return;const f=m.default_space,y=(f&&"scope"in f?f.scope:f)??{},g=f&&"preferences"in f?f.preferences:null,h=String(y?.scope_id||"");R.createGroupId="",R.createGroupDisplayName="",R.teamSetupGuide={groupId:u,displayName:String(m.group?.display_name||p||""),defaultSpaceScopeId:h,defaultSpaceLabel:String(y?.label||""),autoGrantDefaultSpaceOnJoin:typeof g?.auto_grant_default_space_on_join=="boolean"?g.auto_grant_default_space_on_join:null,setupWarning:m.setup_warning||null};try{await n(),Od(u),await n()}catch{J("Legacy coordinator group created, but coordinator data could not refresh. Check coordinator recovery status before retrying.","warning");return}m.setup_warning?J("Legacy coordinator group created, but default Space setup needs repair. Sharing policy is unchanged.","warning"):h?J("Legacy coordinator group created with a default Space. Sharing policy is unchanged.","success"):J("Legacy coordinator group created, but default Space status is unknown. Sharing policy is unchanged.","warning")}catch{J("Could not create the legacy coordinator group. No Sharing policy or Project access changed; check coordinator recovery status and retry.","warning")}finally{R.groupActionPendingKind="",t()}}async function a(d,u,p){if(!r("status","groups")||!d||R.groupActionPendingId)return;const m=u.trim();if(p==="rename"&&!m){J("Enter a legacy group display name before renaming it.","warning");return}const f=Fd(d,S.lastCoordinatorAdminGroups.find(b=>b.group_id===d)?.display_name),y=Es();if(!await Xt({title:p==="rename"?`Rename ${f}?`:`${p==="archive"?"Archive":"Unarchive"} ${f}?`,description:p==="rename"?`Target: ${f}. New name: ${m}. 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: ${f}. 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: ${f}. 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(!Ct(y)){J("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}if(!fn(R.recovery,"status","groups")){J("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const g=S.lastCoordinatorAdminGroups.find(b=>String(b.group_id||"")===d);if(!g||R.groupActionPendingId){J("Coordinator group data changed while confirmation was open. Review the current group and try again.","warning");return}const h=R.groupRenameDrafts.get(d)??String(g.display_name||"");R.groupActionPendingId=d,R.groupActionPendingKind=p,t();try{const b=p==="rename"?"renamed":p==="archive"?"archived":"unarchived";p==="rename"&&await WS(d,h),p==="archive"&&await zS(d),p==="unarchive"&&await JS(d);try{await n()}catch{J(`Legacy coordinator group ${b}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}J(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(b){if(nx(b))try{await n(),J("This legacy coordinator group changed or no longer exists. Coordinator groups were refreshed.","warning")}catch{J("This legacy coordinator group changed or no longer exists. Refresh coordinator groups before trying another action.","warning")}else J(`Could not ${p} the legacy coordinator group. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{R.groupActionPendingId="",R.groupActionPendingKind="",t()}}async function s(){if(!r("status","groups")||R.invitePending)return;const d=S.lastCoordinatorAdminStatus,u=yn(d?.coordinator_url),p=bn()||String(d?.active_group||"").trim(),m=R.inviteGroup.trim()||p,f=Number(R.inviteTtlHours);if(!m){J("Choose a coordinator group before creating a legacy invite.","warning");return}if(!Number.isFinite(f)||f<1){J("Invite lifetime must be at least 1 hour.","warning");return}R.invitePending=!0,t();try{const y=await pm({group_id:m,policy:R.invitePolicy,ttl_hours:f}),g=S.lastCoordinatorAdminStatus,h=bn()||String(g?.active_group||"").trim(),b=R.inviteGroup.trim()||h;if(yn(g?.coordinator_url)!==u||b!==m)return;S.lastTeamInvite=y,R.inviteGroup=m;const w=Array.isArray(y.warnings)?y.warnings:[];J(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(y){J(ex(y),"warning")}finally{R.invitePending=!1,t()}}async function c(d,u){if(!Ct(R.joinRequestsSnapshotTarget)||!r("status","joinRequests")||R.joinReviewPendingId)return;const p=R.joinRequestsSnapshotTarget;R.joinReviewPendingId=d,R.joinReviewPendingAction=u,t();try{const m=await tC(d,u);if(!Ct(p))return;try{await n()}catch{J(`Join request ${u==="approve"?"approved":"denied"}, but pending requests could not refresh. Check coordinator recovery status before reviewing another request.`,"warning");return}u==="approve"&&m.setup_warning?J("Join request approved, but default Space access needs repair.","warning"):J(u==="approve"?"Join request approved.":"Join request denied.","success")}catch(m){if(!Ct(p))return;if(tx(m))try{await n(),J("This legacy coordinator join request no longer exists. Pending requests were refreshed.","warning")}catch{J("This legacy coordinator join request no longer exists. Refresh pending requests before reviewing another request.","warning")}else J("Could not review the legacy coordinator join request. Sharing policy is unchanged; check coordinator recovery status and retry.","warning")}finally{R.joinReviewPendingId="",R.joinReviewPendingAction="",t()}}async function l(d,u,p,m){if(Ct(R.devicesSnapshotTarget)&&r("status","devices")&&!(!d||R.deviceActionPendingId)){if(m==="disable"||m==="remove"){const f=Es();if(!await Xt({title:`${m==="disable"?"Disable":"Remove"} ${p||"this device"}?`,description:m==="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:m==="disable"?"Disable device":"Remove device",cancelLabel:m==="disable"?"Keep device enabled":"Keep device enrolled",tone:"danger"}))return;if(!Ct(f)){J("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!fn(R.recovery,"status","devices")){J("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}if(!S.lastCoordinatorAdminDevices.find(y=>String(y.device_id||"")===d&&String(y.group_id||"")===u)||R.deviceActionPendingId){J("Coordinator device data changed while confirmation was open. Review the current device and try again.","warning");return}}R.deviceActionPendingId=d,R.deviceActionPendingKind=m,t();try{const f=m==="rename"?"renamed":m==="disable"?"disabled":m==="enable"?"enabled":"removed";if(m==="rename"){const y=String(R.deviceRenameDrafts.get(d)||"").trim();if(!y){J("Enter a device name before renaming it.","warning");return}await nC(d,u,y)}m==="disable"&&await rC(d,u),m==="enable"&&await iC(d,u),m==="remove"&&await aC(d,u);try{await n()}catch{J(`Device ${f}, but coordinator data could not refresh. Check coordinator recovery status before retrying.`,"warning");return}J(`Device ${f}.`,"success")}catch(f){const y=m==="rename"&&f instanceof Error?ZE.get(f.message.trim()):void 0;if(rx(f))try{await n(),J("This legacy coordinator device no longer exists. Enrolled devices were refreshed.","warning")}catch{J("This legacy coordinator device no longer exists. Refresh enrolled devices before trying another action.","warning")}else J(y||`Could not ${m} the legacy coordinator device. Sharing policy is unchanged; check coordinator recovery status and retry.`,"warning")}finally{R.deviceActionPendingId="",R.deviceActionPendingKind="",t()}}}return{createGroupFromAdminPanel:i,runGroupAction:a,createInviteFromAdminPanel:s,reviewJoinRequestFromAdminPanel:c,runDeviceAction:l}}function ax(){S.lastCoordinatorAdminGroups=[],S.lastCoordinatorAdminJoinRequests=[],S.lastCoordinatorAdminDevices=[],S.lastTeamInvite=null,S.coordinatorAdminTargetGroup="",Wt(R.recovery,"groups",!1),Wt(R.recovery,"joinRequests",!1),Wt(R.recovery,"devices",!1),R.joinRequestsSnapshotTarget=null,R.devicesSnapshotTarget=null,R.groupRenameDrafts.clear(),R.groupPresentationAliases.clear(),R.deviceRenameDrafts.clear(),R.deviceRenameServerNames.clear(),R.groupPreferencesOpen.clear(),R.groupPreferencesDrafts.clear(),R.groupScopeManagementOpen.clear(),R.groupScopeManagementDrafts.clear(),R.inviteGroup="",R.teamSetupGuide=null}function ox(){const e=Kg();return ya(R.recovery,"status"),md(R.recovery,"groups"),md(R.recovery,"joinRequests"),md(R.recovery,"devices"),e}async function By(e){try{const t=await Vc();if(!hd(e))return"superseded";if(!t||typeof t!="object")throw new Error("Invalid status payload");const n=S.lastCoordinatorAdminStatus;return yn(n?.coordinator_url)!==yn(t.coordinator_url)&&ax(),S.lastCoordinatorAdminStatus=t,hs(R.recovery,"status"),"fresh"}catch{return hd(e)?(Wt(R.recovery,"status"),"failed"):"superseded"}}function sx(){const e=S.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."}:R.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:cx,runGroupAction:lx,createInviteFromAdminPanel:dx,reviewJoinRequestFromAdminPanel:ux,runDeviceAction:px}=ix({renderShell:()=>Pr(),reloadData:()=>qs()});function Pr(){const e=document.getElementById("coordinatorAdminMount");if(!e)return;const t=S.lastCoordinatorAdminStatus,n=sx(),r=String(t?.coordinator_url||"").trim(),i=String(t?.active_group||"").trim(),s=!!gA()?.archived_at,c=fn(R.recovery,"status","groups"),l=c&&!s,d=Ct(R.joinRequestsSnapshotTarget),u=Ct(R.devicesSnapshotTarget),p=fn(R.recovery,"status","joinRequests")&&d,m=fn(R.recovery,"status","devices")&&u,f=bn(),y=Bn().filter(F=>!F.archived_at).length,g=Bn().filter(F=>F.archived_at).length,h=d&&Array.isArray(S.lastCoordinatorAdminJoinRequests)?S.lastCoordinatorAdminJoinRequests.length:0,b=u&&Array.isArray(S.lastCoordinatorAdminDevices)?S.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.":"",_=Hg(R.recovery),I=Sr(R.recovery,"status"),N=Sr(R.recovery,"groups"),T=d&&Sr(R.recovery,"joinRequests"),x=u&&Sr(R.recovery,"devices"),j=mi(R.recovery,"groups"),B=mi(R.recovery,"joinRequests"),P=mi(R.recovery,"devices");He(v("div",{class:"coordinator-admin-shell"},v("div",{class:"card coordinator-admin-header"},v("div",{class:"section-header"},v("h2",null,"Legacy coordinator administration")),v("div",{"aria-atomic":"true","aria-live":"polite",class:_?"coordinator-admin-inline-warning coordinator-admin-recovery-notice":R.recoveryAnnouncement?"peer-meta coordinator-admin-recovery-status":"coordinator-admin-recovery-status",id:"coordinatorAdminRecoveryStatus",role:"status",tabIndex:-1},_?v(z,null,v("div",{class:"coordinator-admin-legacy-notice-copy"},v("h3",null,"Advanced coordinator data needs attention"),R.recoveryAnnouncement?v("p",{class:"peer-submeta"},R.recoveryAnnouncement):null,_.stale.length?v("p",{class:"peer-submeta"},`Stale: ${_.stale.join(", ")}. Previously loaded data is still shown.`):null,_.unavailable.length?v("p",{class:"peer-submeta"},`Unavailable: ${_.unavailable.join(", ")}. No current data is shown for ${_.unavailable.length===1?"that surface":"those surfaces"}.`):null,v("p",{class:"peer-submeta"},"Actions that depend on current coordinator data are disabled. This does not mean coordinator data was deleted.")),v("button",{class:"settings-button",disabled:_.retrying,onClick:()=>{R.recoveryAnnouncement="Retrying coordinator data…",R.recoveryRetryRequested=!0,qs()},type:"button"},_.retrying?"Retrying…":"Retry")):R.recoveryAnnouncement),v("div",{class:"coordinator-admin-summary-grid"},v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Coordinator group target"),v("strong",null,I||N?f||"None selected":"Unavailable")),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Node discovery group"),v("strong",null,I?i||"None":"Unavailable")),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Coordinator groups"),v("strong",null,N?`${y} active${g?` · ${g} archived`:""}`:j?"Setup required":"Unavailable")),v("div",{class:"coordinator-admin-summary-card"},v("span",{class:"section-meta"},"Selected group activity"),v("strong",null,`${T?h:B?"Setup required":"Unavailable"} join requests · ${x?b:P?"Setup required":"Unavailable"} devices`))),w?v("div",{class:"peer-meta coordinator-admin-inline-warning"},w):null,r?v("div",{class:"section-meta coordinator-admin-inline-meta"},`Coordinator: ${r}`):null),v("div",{class:"card coordinator-admin-sections"},v(Ug,{ariaLabel:"Legacy coordinator administration sections",listClassName:"coordinator-admin-tabs-list",onValueChange:F=>{R.activeSection=F||"groups",Pr()},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:R.activeSection},YE({summary:n,fresh:c,createGroup:()=>{cx()},runGroup:(F,O,G)=>{lx(F,O,G)},renderShell:Pr,reloadData:()=>{qs()}}),XE({summary:n,fresh:l,createInvite:()=>{dx()},renderShell:Pr}),QE({summary:n,fresh:p,snapshotMatchesTarget:d,reviewJoinRequest:(F,O)=>{ux(F,O)}}),MR({summary:n,fresh:m,snapshotMatchesTarget:u,runDevice:(F,O,G,$)=>{px(F,O,G,$)}})),v("div",{class:"section-meta coordinator-admin-context-line"},s?"The selected coordinator group is archived. Switch or restore it to enable legacy invite operations.":f?"Actions below apply to the selected coordinator group.":"Select a coordinator group to manage legacy enrollment and Spaces."))),e),R.recoveryFocusPending&&(R.recoveryFocusPending=!1,queueMicrotask(()=>document.getElementById("coordinatorAdminRecoveryStatus")?.focus()))}function mx(){Pr()}async function qs(){const e=Kg(),t=()=>hd(e);if(R.recoveryRetryRequested||(R.recoveryAnnouncement=""),ya(R.recovery,"status"),ya(R.recovery,"groups"),ya(R.recovery,"joinRequests"),ya(R.recovery,"devices"),Pr(),await By(e)==="superseded")return;const n=String(S.lastCoordinatorAdminStatus?.active_group||"").trim();if(Jv(),S.lastCoordinatorAdminStatus?.readiness==="ready"&&fn(R.recovery,"status")){try{const a=await Em();if(!t())return;S.lastShareOperations=Array.isArray(a.items)?a.items:[]}catch{if(!t())return}try{const a=await lm(R.showArchivedGroups);if(!t())return;if(!Array.isArray(a?.items))throw new Error("Invalid groups payload");S.lastCoordinatorAdminGroups=a.items,hs(R.recovery,"groups"),hA(),Jv()}catch{if(!t())return;Wt(R.recovery,"groups")}const r=bn(),i=Es();try{if(!i)throw new Error("Missing coordinator administration target");const a=await eC(r||n);if(!t())return;if(!Array.isArray(a?.items))throw new Error("Invalid join requests payload");S.lastCoordinatorAdminJoinRequests=a.items,R.joinRequestsSnapshotTarget=i,hs(R.recovery,"joinRequests")}catch{if(!t())return;Wt(R.recovery,"joinRequests",Ct(R.joinRequestsSnapshotTarget))}try{if(!i)throw new Error("Missing coordinator administration target");const a=await um(r||n,!0);if(!t())return;if(!Array.isArray(a?.items))throw new Error("Invalid devices payload");S.lastCoordinatorAdminDevices=a.items,R.devicesSnapshotTarget=i,hs(R.recovery,"devices"),vA()}catch{if(!t())return;Wt(R.recovery,"devices",Ct(R.devicesSnapshotTarget))}try{const a=await wo();if(!t())return;R.availableProjects=a}catch{if(!t())return}}else R.recovery.status.availability==="fresh"?(fd(R.recovery,"groups"),fd(R.recovery,"joinRequests"),fd(R.recovery,"devices"),R.joinRequestsSnapshotTarget=null,R.devicesSnapshotTarget=null):(Wt(R.recovery,"groups"),Wt(R.recovery,"joinRequests",Ct(R.joinRequestsSnapshotTarget)),Wt(R.recovery,"devices",Ct(R.devicesSnapshotTarget)));t()&&(qg([...S.lastCoordinatorAdminDevices,...S.lastCoordinatorAdminJoinRequests.map(r=>({device_id:String(r.device_id||"").trim()||`join-request:${String(r.request_id||"").trim()}`,display_name:r.display_name}))],R.unnamedDeviceAliases),ms(S.lastCoordinatorAdminDevices,R.unnamedDeviceAliases),R.recoveryRetryRequested&&(R.recoveryAnnouncement=Hg(R.recovery)?"Retry finished, but some coordinator data still needs attention. Retained data remains unchanged.":S.lastCoordinatorAdminStatus?.readiness==="ready"?"Coordinator data refreshed. Current data is available.":"Coordinator status refreshed. Complete setup to load administration data.",R.recoveryFocusPending=!0),R.recoveryRetryRequested=!1,Pr())}function ru(e){return e.inventoryUnavailable===!0||e.refreshError===!0}var iu=new WeakMap,Uy={active:0,verifying:1,pending:2,waiting:3,needs_attention:4},fx={state:"pending",label:"Recipient policy pending",explanation:"Current access remains in place while this Project is prepared.",deliveredCopiesMayRemain:!0},hx={available:"Available",offline:"Offline",unknown:"Availability unknown"};function gx(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function vx(e,t){return t.get(e)??fx}function yx(e){return e.reduce((t,n)=>!t||Uy[n.state]>Uy[t.state]?n:t,null)}function bx(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 _x(e,t,n,r,i=[]){const a=new Map(e.identities.filter(u=>u.status==="active"&&u.mergedIntoIdentityId===null).map(u=>[u.identityId,u.displayName])),s=new Map(n.map(u=>[u.canonicalProjectIdentity,u.displayName])),c=new Map(r.map(u=>[u.deviceId,u.state])),l=new Map(i.map(u=>[u.deviceId,u])),d=new Map(t.items.map(u=>[u.canonicalProjectIdentity,u]));return{devices:e.identityDevices.filter(u=>u.status==="active"&&a.has(u.identityId)).map(u=>{const p=l.get(u.deviceId),m=gx(e.projectRecipients.filter(_=>_.status==="active"&&_.recipientKind==="identity"&&_.identityId===u.identityId).map(_=>_.canonicalProjectIdentity)),f=_=>{const I=s.get(_);if(!I)return null;const N=vx(_,d);return{canonicalProjectIdentity:_,displayName:I,state:N.state,statusLabel:N.label,statusCopy:N.explanation,deliveredCopiesMayRemain:N.deliveredCopiesMayRemain}},y=m.flatMap(_=>{const I=f(_);return I?[I]:[]}),g=[],h=[...y,...g],b=yx(h),w=c.get(u.deviceId)??"unknown";return{deviceId:u.deviceId,displayName:u.displayName,identityName:a.get(u.identityId)??"Identity unavailable",availability:w,availabilityLabel:hx[w],isPairedPeer:p!==void 0,reportedRuntimeVersion:p?.runtimeVersion??null,runtimeVersionObservedAt:p?.runtimeVersionObservedAt??null,directProjects:y,inheritedProjects:g,unavailableProjectCount:m.length-y.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:bx(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"&&a.has(u.identityId)).length}}function qy({empty:e,projects:t}){return t.length===0?o("p",{className:"small",children:e}):o("ul",{children:t.map(n=>o("li",{children:[o("strong",{children:n.displayName}),o("span",{className:"small",children:[" ","— ",n.statusLabel,". ",n.statusCopy]})]},n.canonicalProjectIdentity))})}function Ra(e){if(!(e instanceof zc))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 Gs(e,t){return{targetIdentityId:e.state==="setup_required"&&e.suggestedIdentityId&&t.has(e.suggestedIdentityId)?e.suggestedIdentityId:"",selected:!1,explicit:!1,itemSignature:Pa(e)}}function Pa(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 Hs(e,t,n,r){if(e.status!=="ready"||e.outcomes.length!==t.bindings.length)return!1;const i=new Set;return t.bindings.every(a=>{const s=n.find(l=>l.deviceId===a.deviceId),c=e.outcomes.findIndex((l,d)=>!i.has(d)&&s?.evidenceDeviceIds.includes(l.deviceId)===!0&&l.targetIdentityId===a.targetIdentityId&&l.action===r);return c<0?!1:(i.add(c),!0)})}var Gy="devices-commit-status";function _n(e){const t=document.getElementById(Gy);t&&(t.textContent=e)}function wx({intent:e,inventory:t,items:n,options:r}){const i=e.identities.filter(A=>A.status==="active"&&A.mergedIntoIdentityId===null),a=new Map(i.map(A=>[A.identityId,A.displayName])),s=new Set(a.keys()),[c,l]=D(()=>Object.fromEntries(n.map(A=>[A.deviceId,Gs(A,s)]))),[d,u]=D(null),[p,m]=D(!1),[f,y]=D(!1),[g,h]=D(""),b=q(null),w=q(0),_=r.previewBindings??km,I=r.commitBindings??Tm,N=ru(r),T=d!==null&&Hs(d.preview,d.request,n,"bind"),x=Se(()=>n.filter(A=>A.state==="setup_required"&&c[A.deviceId]?.selected),[c,n]),j=JSON.stringify({items:t.items.map(Pa),coordinatorEvidence:t.coordinatorEvidence,truncated:t.truncated}),B=i.map(A=>`${A.identityId}:${A.displayName}`).sort().join("|");W(()=>{d&&b.current?.focus()},[d]),W(()=>{w.current+=1,y(!1),l(A=>Object.fromEntries(n.map(E=>{const C=A[E.deviceId];if(!C)return[E.deviceId,Gs(E,s)];if(E.state!=="setup_required")return[E.deviceId,Gs(E,s)];const L=C.targetIdentityId!==""&&s.has(C.targetIdentityId);return C.itemSignature===Pa(E)&&L?[E.deviceId,C]:C.explicit&&L?[E.deviceId,{...C,selected:!1,itemSignature:Pa(E)}]:[E.deviceId,Gs(E,s)]}))),u(null),m(!1)},[j,B]);const P=(A,E)=>{w.current+=1,y(!1),l(C=>({...C,[A]:{...C[A],...E}})),u(null),m(!1),h(""),_n("")},F=A=>({bindings:A.map(E=>{const C=c[E.deviceId];return{deviceId:E.deviceId,targetIdentityId:C?.targetIdentityId??"",confirmed:!0}})}),O=async A=>{if(N){h("Refresh Devices before reviewing Identity setup.");return}if(A.some(L=>L.state!=="setup_required")){h("Only devices that require Identity setup can be reviewed here.");return}const E=A.find(L=>Xo(t,L).blocked);if(E){h(Xo(t,E).recovery??"Identity setup is unavailable.");return}if(A.length===0||A.some(L=>!c[L.deviceId]?.targetIdentityId)){h("Choose an Identity for every selected device before review.");return}y(!0),h(""),_n("");const C=w.current;try{const L=F(A),U=await _(L);C===w.current&&(Hs(U,L,A,"bind")?u({preview:U,request:L}):h("Identity setup preview was incomplete. Refresh and try again."))}catch(L){C===w.current&&h(Ra(L))}C===w.current&&y(!1)},G=async()=>{if(!(!d||!p||N||!T)){y(!0),h("");try{await I({...d.request,reviewedInventoryDigest:d.preview.reviewedInventoryDigest}),u(null),m(!1),_n("Identity setup completed.");const A=await r.onCommitted?.();_n(A===!1?"Identity setup completed, but refreshing Devices and Sharing failed. Refresh to see current state.":A===!0?"Identity setup completed. Devices and Sharing were refreshed.":"Identity setup completed."),document.getElementById("devices-heading")?.focus()}catch(A){h(Ra(A))}y(!1)}},$=n.filter(A=>A.state==="setup_required");return n.length===0?null:o(z,{children:[g?o("p",{role:"alert",children:g}):null,$.length>1?o("div",{className:"device-identity-setup-summary",children:[o("strong",{children:[$.length.toLocaleString()," devices need Identity setup"]}),o("button",{className:"settings-button",disabled:f||N||x.length===0,onClick:()=>{O(x)},type:"button",children:["Review ",x.length.toLocaleString()," selected"]})]}):null,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:n.map((A,E)=>{const C=c[A.deviceId],L=Xo(t,A),U=L.blocked||N,V=`device-inventory-title-${E}`;return o("li",{children:o("article",{"aria-labelledby":V,className:"peer-card peer-card--padded recipient-policy-sharing-card device-identity-setup-card",id:`device-identity-card-${A.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:V,children:[A.displayName,A.isLocal?" (this device)":""]}),o("span",{className:"badge actor-badge",children:A.state==="setup_required"?"Setup required":A.state==="pairing_required"?"Pairing required":A.state==="conflicted"?"Review required":"Configured"})]}),A.state==="setup_required"?o(z,{children:[o("fieldset",{children:[o("legend",{children:"Assign an existing Identity"}),i.length===0?o("p",{children:"No active Identity is available. Create or restore an Identity before setup."}):null,$.length>1?o("label",{children:[o("input",{"aria-label":`Select for setup: ${A.displayName}`,checked:C?.selected??!1,disabled:U,onInput:de=>P(A.deviceId,{selected:de.currentTarget.checked}),type:"checkbox"})," ","Select for setup"]}):null,o("label",{htmlFor:`${V}-identity`,children:"Identity"}),o("select",{"aria-label":`Choose an Identity for ${A.displayName}`,disabled:U,id:`${V}-identity`,onInput:de=>P(A.deviceId,{targetIdentityId:de.currentTarget.value,explicit:!0}),value:C?.targetIdentityId??"",children:[o("option",{value:"",children:"Choose Identity…"}),i.map(de=>o("option",{value:de.identityId,children:de.displayName},de.identityId))]}),A.suggestedIdentityId&&a.has(A.suggestedIdentityId)?o("p",{className:"small",children:"Suggested from historical device information. Review it before applying setup."}):null,L.recovery?o("p",{className:"small",children:L.recovery}):null]}),o("div",{className:"device-identity-card-actions",children:[i.length===0?o("button",{"aria-label":`Open Identity administration for ${A.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Identity administration"}):null,o("button",{"aria-label":`Review this device: ${A.displayName}`,className:"settings-button",disabled:f||U||!C?.targetIdentityId,onClick:()=>{O([A])},type:"button",children:"Review this device"})]})]}):A.state==="pairing_required"?o(z,{children:[o("p",{children:"Pair this device first. Pairing establishes trust but does not choose its Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Go to pairing for ${A.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Go to pairing"})})]}):A.state==="conflicted"?o(z,{children:[o("p",{children:"Device evidence conflicts. Review and repair it before assigning an Identity."}),o("div",{className:"device-identity-card-actions",children:o("button",{"aria-label":`Open Advanced review for ${A.displayName}`,className:"settings-button",onClick:()=>r.onNavigate?.("advanced_sync"),type:"button",children:"Open Advanced review"})})]}):null]})},A.deviceId)})}),d?o("section",{"aria-labelledby":"device-identity-review-heading",className:"peer-card peer-card--padded device-identity-review-panel",children:[o("h3",{id:"device-identity-review-heading",ref:b,tabIndex:-1,children:"Review Identity setup"}),o("ul",{children:d.preview.outcomes.map(A=>o("li",{children:[o("strong",{children:[A.displayName,":"]})," ",A.previousIdentityId?a.get(A.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→ ",a.get(A.targetIdentityId)??"Unavailable Identity"]},A.deviceId))}),o("p",{children:"Identity setup records device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:p,disabled:N,onInput:A=>m(A.currentTarget.checked),type:"checkbox"})," ","I reviewed every device and target Identity"]}),o("div",{className:"peer-actions",children:[o("button",{className:"settings-button",disabled:f,onClick:()=>{u(null),m(!1)},type:"button",children:"Back"}),o("button",{className:"settings-button sync-dialog-confirm",disabled:f||N||!p||!T,onClick:()=>{G()},type:"button",children:["Apply setup to ",d.request.bindings.length.toLocaleString()," ",d.request.bindings.length===1?"device":"devices"]})]})]}):null]})}function Hy({intent:e,inventory:t,item:n,options:r,previousIdentityName:i}){const a=e.identities.filter(A=>A.status==="active"&&A.mergedIntoIdentityId===null&&A.identityId!==n.identityId),[s,c]=D(!1),[l,d]=D(""),[u,p]=D(!1),[m,f]=D(null),[y,g]=D(!1),[h,b]=D(!1),[w,_]=D(""),I=q(0),N=i,T=new Map(e.identities.map(A=>[A.identityId,A.displayName])),x=m?.preview.status==="ready"&&m.preview.outcomes.length===1?m.preview.outcomes[0]:null,j=m!==null&&Hs(m.preview,m.request,[n],"rebind"),B=Xo(t,n),P=B.blocked||ru(r),F=`configured-rebind-trigger-${n.deviceId}`,O=a.find(A=>A.identityId===l)?.displayName??"";W(()=>{I.current+=1,b(!1),l&&!a.some(A=>A.identityId===l)&&(d(""),p(!1)),f(null),g(!1)},[a.map(A=>A.identityId).sort().join("|"),Pa(n)]);const G=async()=>{if(P){_(B.recovery??"Identity reassignment is unavailable.");return}if(!l||!u){_("Choose a target Identity and confirm the reassignment before review.");return}b(!0),_(""),_n("");const A=I.current;try{const E={bindings:[{deviceId:n.deviceId,targetIdentityId:l,confirmed:u,allowRebind:!0}]},C=await(r.previewBindings??km)(E);A===I.current&&(C.status!=="ready"?_(Ra(new zc(409,C.errorCode??"binding_preview_unavailable",C))):Hs(C,E,[n],"rebind")?f({preview:C,request:E}):_("Identity reassignment preview was incomplete. Refresh and try again."))}catch(E){A===I.current&&_(Ra(E))}A===I.current&&b(!1)},$=async()=>{if(!(!m||!y||P||!j)){b(!0),_("");try{await(r.commitBindings??Tm)({...m.request,reviewedInventoryDigest:m.preview.reviewedInventoryDigest}),c(!1),d(""),p(!1),f(null),g(!1),_n("Identity reassignment completed.");const A=await r.onCommitted?.();_n(A===!1?"Identity reassignment completed, but refreshing Devices and Sharing failed. Refresh to see current state.":A===!0?"Identity reassignment completed. Devices and Sharing were refreshed.":"Identity reassignment completed."),(document.getElementById(F)??document.getElementById("devices-heading"))?.focus()}catch(A){_(Ra(A))}b(!1)}};return o("div",{className:"device-identity-rebind",children:[o("button",{"aria-expanded":s,className:"settings-button",disabled:P,id:F,onClick:()=>{I.current+=1,b(!1),c(!s),f(null),g(!1),_(""),_n("")},type:"button",children:"Change Identity…"}),B.recovery?o("p",{className:"small",children:B.recovery}):null,s?o("fieldset",{children:[o("legend",{children:"Reassign this configured device"}),o("p",{children:[o("strong",{children:"Suggested current Identity (unconfirmed):"})," ",N]}),o("label",{htmlFor:`configured-rebind-${n.deviceId}`,children:"Target Identity"}),o("select",{disabled:P,id:`configured-rebind-${n.deviceId}`,onInput:A=>{I.current+=1,b(!1),d(A.currentTarget.value),p(!1),f(null),g(!1)},value:l,children:[o("option",{value:"",children:"Choose a different Identity…"}),a.map(A=>o("option",{value:A.identityId,children:A.displayName},A.identityId))]}),o("label",{children:[o("input",{checked:u,disabled:P||!l,onInput:A=>{I.current+=1,b(!1),p(A.currentTarget.checked),f(null),g(!1)},type:"checkbox"})," ","Confirm reassigning ",n.displayName," to ",O||"the selected Identity"]}),o("button",{className:"settings-button",disabled:h||P,onClick:()=>{G()},type:"button",children:"Review reassignment"}),m?o("div",{className:"device-identity-rebind-review",children:[o("h4",{children:"Review reassignment"}),o("p",{children:[x?.displayName,":"," ",x?.previousIdentityId?T.get(x.previousIdentityId)??"Unavailable Identity":"No Identity"," ","→"," ",T.get(x?.targetIdentityId??"")??"Unavailable Identity"]}),o("p",{className:"small",children:"This changes device ownership only. It does not grant Projects, Team membership, or sync access."}),o("label",{children:[o("input",{checked:y,disabled:P,onInput:A=>g(A.currentTarget.checked),type:"checkbox"})," ","I reviewed the previous and target Identities"]}),o("button",{className:"settings-button sync-dialog-confirm",disabled:h||P||!y||!j,onClick:()=>{$()},type:"button",children:"Reassign Identity"})]}):null,w?o("p",{"aria-live":"assertive",role:"alert",children:w}):null]}):null]})}function Sx({intent:e,options:t,projection:n}){if(t.loading)return o(Rh,{label:"Loading Devices"});if(t.loadError)return o("p",{"aria-live":"assertive",role:"alert",children:"Devices are unavailable. Refresh and try again."});const r=t.refreshError?o("p",{"aria-live":"assertive",role:"alert",children:"Refresh failed; showing previous device information. Identity setup is disabled until a refresh succeeds."}):null,i=n.devices.filter(m=>!t.inventory?.items.some(f=>f.state!=="configured"&&f.evidenceDeviceIds.includes(m.deviceId))),a=new Set(i.map(m=>m.deviceId)),s=t.inventoryUnavailable?o("p",{"aria-live":"polite",className:"small",role:"status",children:"Device ownership information is temporarily unavailable. Existing device details remain visible, but Identity setup is disabled until a refresh succeeds."}):null,c=Ph(t.inventory),l=t.inventory?.items.filter(m=>m.state==="configured"&&!m.evidenceDeviceIds.some(f=>a.has(f)))??[],d=t.inventory?o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:l.map((m,f)=>{const y=`configured-inventory-title-${f}`,g=e.identities.find(h=>h.identityId===m.identityId)?.displayName??"Unavailable Identity";return o("li",{children:o("article",{"aria-labelledby":y,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:y,children:m.displayName}),o("span",{className:"badge actor-badge",children:"Configured · Availability unknown"})]}),o("p",{children:[o("strong",{children:"Owning Identity:"})," ",g]}),o(Hy,{intent:e,inventory:t.inventory,item:m,options:t,previousIdentityName:g})]})},m.deviceId)})}):null,u=(t.coordinatorEnrollmentIssueCount??0)>0?o("aside",{"aria-labelledby":"devices-coordinator-reconciliation-heading",className:"peer-card peer-card--padded recipient-policy-sharing-attention",children:[o("h3",{id:"devices-coordinator-reconciliation-heading",children:"Coordinator setup needs attention"}),o("p",{children:[t.coordinatorEnrollmentIssueCount?.toLocaleString()," coordinator enrollment",t.coordinatorEnrollmentIssueCount===1?" could":"s could"," not be safely reconciled with device Identity setup."]}),o("p",{className:"small",children:["No ownership was inferred."," ",c.length>0?"Review the affected device setup or pairing state here, then retry after coordinator data is corrected.":"No device on this page can be corrected from here. Retry after coordinator data is corrected."]})]}):null,p=t.inventory?o(z,{children:[t.inventory.truncated?o("p",{"aria-live":"assertive",role:"alert",children:"The device inventory is incomplete. Identity setup is unavailable until a complete refresh succeeds."}):null,t.inventory.coordinatorEvidence.availability==="unavailable"?o("p",{className:"small",role:"status",children:"Coordinator device information is temporarily unavailable. Local devices remain visible, but some setup actions may require a refresh."}):null,o(wx,{intent:e,inventory:t.inventory,items:c,options:t})]}):null;return i.length===0?o(z,{children:[r,s,u,p,d,o("p",{className:"small",role:"status",children:[l.length>0?"No additional active devices are registered.":c.length>0?"No configured devices are registered.":"No active devices are registered.",n.revokedDeviceCount>0?` ${n.revokedDeviceCount.toLocaleString()} revoked ${n.revokedDeviceCount===1?"device is":"devices are"} not shown.`:""]})]}):o(z,{children:[r,s,u,p,d,o("ul",{className:"recipient-policy-sharing-grid recipient-policy-sharing-responsive-grid",children:i.map((m,f)=>{const y=`devices-card-title-${f}`,g=m.action,h=t.inventory?.items.find(b=>b.state==="configured"&&b.evidenceDeviceIds.includes(m.deviceId));return o("li",{children:o("article",{"aria-labelledby":y,className:"peer-card peer-card--padded recipient-policy-sharing-card",id:`device-identity-card-${m.deviceId}`,tabIndex:-1,children:[o("div",{className:"peer-title recipient-policy-sharing-card-title",children:[o("h3",{id:y,children:m.displayName}),o("span",{className:"badge actor-badge",children:[ru(t)?"Device":"Configured"," ·"," ",m.availabilityLabel]})]}),o("dl",{className:"recipient-policy-sharing-details",children:[o("div",{children:[o("dt",{children:"Owning Identity"}),o("dd",{children:m.identityName})]}),o("div",{children:[o("dt",{children:"Availability"}),o("dd",{children:m.availabilityLabel})]}),m.isPairedPeer?o("div",{children:[o("dt",{children:"Codemem version"}),o("dd",{children:m.reportedRuntimeVersion??"Not reported"})]}):null,o("div",{children:[o("dt",{children:"Sharing status"}),o("dd",{children:[o("strong",{children:m.statusLabel})," — ",m.statusCopy]})]})]}),o("section",{"aria-labelledby":`${y}-direct`,children:[o("h4",{id:`${y}-direct`,children:"Direct Projects"}),o(qy,{empty:"No Projects are shared directly.",projects:m.directProjects})]}),o("section",{"aria-labelledby":`${y}-teams`,children:[o("h4",{id:`${y}-teams`,children:"Projects through Teams"}),o(qy,{empty:"Per-device Team access is not shown because Team membership alone does not prove this device receives the Team’s Projects.",projects:m.inheritedProjects})]}),m.unavailableProjectCount>0?o("p",{className:"small",role:"status",children:"Some Project names are unavailable and are not shown."}):null,m.deliveredCopiesMayRemain?o("p",{className:"small",children:[o("strong",{children:"Delivered copies:"})," Changing access stops future delivery, but copies already delivered may remain on this device or in backups."]}):null,g&&t.onNavigate?o("button",{"aria-label":`${g.label} for ${m.displayName}`,className:"settings-button recipient-policy-sharing-target-24",onClick:()=>t.onNavigate?.(g.target),ref:b=>{b&&iu.set(b,{deviceId:m.deviceId,target:g.target})},type:"button",children:g.label}):null,h&&t.inventory?o(Hy,{intent:e,inventory:t.inventory,item:h,options:t,previousIdentityName:m.identityName}):null]})},m.deviceId)})}),n.revokedDeviceCount>0?o("p",{className:"small",role:"status",children:[n.revokedDeviceCount.toLocaleString()," revoked"," ",n.revokedDeviceCount===1?"device is":"devices are"," not included in the active list."]}):null]})}function Ks(e,t,n,r,i,a={}){const s=document.activeElement,c=s instanceof HTMLElement&&e.contains(s),l=c?iu.get(s):void 0,d=_x(t,n,r,i,a.peerRuntimeMetadata);if(He(o("section",{"aria-labelledby":"devices-heading",className:"recipient-policy-sharing recipient-policy-sharing-responsive-surface",children:[o("div",{className:"recipient-policy-sharing-header",children:[o("h2",{id:"devices-heading",tabIndex:-1,children:"Devices"}),o("p",{className:"small",children:"See where Codemem runs and which Projects each active device receives."})]}),o(Sx,{intent:t,options:a,projection:d}),o("p",{"aria-live":"polite",id:Gy,role:"status"})]}),e),_n(""),!a.loading&&S.pendingDeviceIdentityFocus!==void 0){const u=S.pendingDeviceIdentityFocus,p=a.inventory?.items.find(f=>f.deviceId===u||f.evidenceDeviceIds.includes(u??"")),m=[...u?[u]:[],...p?[p.deviceId,...p.evidenceDeviceIds]:[]].map(f=>document.getElementById(`device-identity-card-${f}`)).find(f=>f instanceof HTMLElement)??document.getElementById("device-identity-review-heading");if(c)S.pendingDeviceIdentityFocus=void 0;else if(m){S.pendingDeviceIdentityFocus=void 0,m.focus();return}else if(!a.inventoryUnavailable&&!a.refreshError){S.pendingDeviceIdentityFocus=void 0,(document.getElementById("devices-heading")??document.getElementById("tabBtn-devices"))?.focus();return}}l&&([...e.querySelectorAll("button")].find(u=>{const p=iu.get(u);return p?.deviceId===l.deviceId&&p.target===l.target})??document.getElementById("tabBtn-devices"))?.focus()}function Cx(e){if(!e)return"n/a";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Ar(e){if(!e)return"never";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function Nx(e){if(!e)return"n/a";const t=new Date(e),n=t.getTime();if(Number.isNaN(n))return String(e);const r=Date.now()-n,i=Math.round(r/1e3);if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.round(i/60);if(a<60)return`${a}m ago`;const s=Math.round(a/60);if(s<24)return`${s}h ago`;const c=Math.round(s/24);return c<14?`${c}d ago`:t.toLocaleDateString()}function Ci(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 Kn(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 Ky(e){const t=Number(e);return Number.isFinite(t)?`${Math.round(t*100)}%`:"n/a"}function Ix(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 au(e,t){const n=Number(e||0),r=Number(t||0);if(!Number.isFinite(n)||!Number.isFinite(r))return"n/a";const i=n+r;if(i<=0)return"n/a";const a=n/i;return Number.isFinite(a)?`${Math.round(a*100)}%`:"n/a"}function Aa(e){const t=Number(e||0);if(!Number.isFinite(t))return"n/a";const n=[{threshold:1e9,suffix:"B"},{threshold:1e6,suffix:"M"},{threshold:1e3,suffix:"K"}];let r=n.findIndex(({threshold:i})=>Math.abs(t)>=i);if(r===-1)return`${t.toLocaleString()} tokens`;for(;r>=0;){const{suffix:i,threshold:a}=n[r],s=t/a,c=Number(s.toFixed(s>=10?0:1));if(Math.abs(c)<1e3||r===0)return`${c.toString().replace(/\.0$/,"")}${i} tokens`;r-=1}return`${t.toLocaleString()} tokens`}function kx(e){const t=String(e||"").trim();if(!t.endsWith("%"))return null;const n=Number(t.replace("%",""));return Number.isFinite(n)?n:null}function Ea(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function Vs(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 Vy(e){const t=String(e||"").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function Tx(e){return e.replace(/_/g," ").split(" ").map(t=>t&&t[0].toUpperCase()+t.slice(1)).join(" ").trim()}function Rx(e,t=2){if(!e.length)return"";const n=e.map(a=>String(a).trim()).filter(Boolean),r=n.slice(0,t),i=n.length>t?` +${n.length-t}`:"";return`${r.join(", ")}${i}`.trim()}function Wy(e){if(!e)return"";const t=String(e).trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n).trim()}function Px(e){const t=String(e||"");return t?t.replace(/^\/Users\/[^/]+(?=\/|$)/,"~").replace(/^\/home\/[^/]+(?=\/|$)/,"~").replace(/^[A-Z]:\\Users\\[^\\]+(?=\\|$)/,"~"):""}function Ax(e){const t=Number(e||0);if(!Number.isFinite(t)||t<0)return"n/a";if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB","PB"],r=s=>s>=10?Math.round(s):Number(s.toFixed(1));let i=t/1024,a=0;for(;a<n.length-1&&r(i)>=1024;)i/=1024,a+=1;return`${String(r(i)).replace(/\.0$/,"")} ${n[a]}`}function zy(e){if(e.owned_by_self===!0)return!0;const t=String(e.actor_id||"").trim();return!!(t&&t===S.lastStatsPayload?.identity?.actor_id)}function Ws(e){if(!e||typeof e!="object")return{};const t=e,n=t.import_metadata;return n&&typeof n=="object"?{...n,...t}:t}function Ex(e){if(!e)return[];const t=String(e).split(`
|
|
46
|
+
`).map(n=>n.trim()).filter(Boolean).filter(n=>/^[-*\u2022]\s+/.test(n)||/^\d+\./.test(n));return t.length?t.map(n=>n.replace(/^[-*\u2022]\s+/,"").replace(/^\d+\.\s+/,"")):[]}function xx(e,t=6){const n=String(e||"").trim();if(!n)return[];const r=n.replace(/\s+/g," ").trim().split(/(?<=[.!?])\s+/).map(a=>a.trim()).filter(Boolean),i=[];for(const a of r)if(!(a.length<18)&&(i.push(a),i.length>=t))break;return i}function Jy(e){const t=Ea(e.title),n=Ea(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 Yy(e){return String(e.id??e.memory_id??e.observation_id??e.session_id??e.created_at_utc??e.created_at??"")}function vt(e){return`${String(e.kind||"").toLowerCase()}:${Yy(e)}`}function Dx(e){if(e.tags!=null)return Vs(e.tags);const t=Vs(e.tags_text);return t.length>0?t:typeof e.tags_text!="string"?[]:e.tags_text.trim().split(/\s+/).filter(Boolean)}function Lx(e){return e==="mine"?" · my memories":e==="theirs"?" · other people":""}function $x(e){return e==="legacy_unknown"?"legacy provenance":e==="unreviewed"?"unreviewed":e.replace(/_/g," ")}function Mx(e){if(zy(e))return"You";const t=String(e.actor_id||"").trim(),n=ai(e.resolved_actor_display_name);return n||(t||e.actor_display_name?"Teammate":"Unknown author")}function jx(e,t={}){if(zy(e)||!String(e.origin_device_id||t.origin_device_id||"").trim())return"";const n=ai(e.resolved_device_display_name);return n?`Device ${n}`:"Shared device"}function Xy(e,t){const n=new Map;return e.forEach(r=>{n.set(vt(r),r)}),t.forEach(r=>{n.set(vt(r),r)}),Array.from(n.values()).sort((r,i)=>new Date(i.created_at||0).getTime()-new Date(r.created_at||0).getTime())}function Ox(e,t){const n=new Set(t.map(vt));return Xy(e.filter(r=>!n.has(vt(r))),t)}var dU=560;function Fx(){const e=document.documentElement,t=Math.max(e.scrollHeight,document.body.scrollHeight);return window.innerHeight+window.scrollY>=t-560}function zs(e,t,n){const r=e.pagination?.has_more;return typeof r=="boolean"?r:t>=n}function Js(e,t){const n=e.pagination?.next_offset;return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:t}function Bx(e,t){const n=new Set(t.map(vt));return e.filter(r=>!n.has(vt(r))).length}var[Ys,uU]=dt("Tooltip",[On]),Xs=On(),Qy="TooltipProvider",Ux=700,ou="tooltip.open",[qx,su]=Ys(Qy),Zy=e=>{const{__scopeTooltip:t,delayDuration:n=Ux,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:a}=e,s=q(!0),c=q(!1),l=q(0);return W(()=>{const d=l.current;return()=>window.clearTimeout(d)},[]),o(qx,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:oe(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:oe(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:oe(d=>{c.current=d},[]),disableHoverableContent:i,children:a})};Zy.displayName=Qy;var xa="Tooltip",[Gx,Da]=Ys(xa),eb=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:a,disableHoverableContent:s,delayDuration:c}=e,l=su(xa,e.__scopeTooltip),d=Xs(t),[u,p]=D(null),m=ut(),f=q(0),y=s??l.disableHoverableContent,g=c??l.delayDuration,h=q(!1),[b,w]=kt({prop:r,defaultProp:i??!1,onChange:x=>{x?(l.onOpen(),document.dispatchEvent(new CustomEvent(ou))):l.onClose(),a?.(x)},caller:xa}),_=Se(()=>b?h.current?"delayed-open":"instant-open":"closed",[b]),I=oe(()=>{window.clearTimeout(f.current),f.current=0,h.current=!1,w(!0)},[w]),N=oe(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),T=oe(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{h.current=!0,w(!0),f.current=0},g)},[g,w]);return W(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),o(Ca,{...d,children:o(Gx,{scope:t,contentId:m,open:b,stateAttribute:_,trigger:u,onTriggerChange:p,onTriggerEnter:oe(()=>{l.isOpenDelayedRef.current?T():I()},[l.isOpenDelayedRef,T,I]),onTriggerLeave:oe(()=>{y?N():(window.clearTimeout(f.current),f.current=0)},[N,y]),onOpen:I,onClose:N,disableHoverableContent:y,children:n})})};eb.displayName=xa;var cu="TooltipTrigger",tb=K((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Da(cu,n),a=su(cu,n),s=Xs(n),c=be(t,q(null),i.onTriggerChange),l=q(!1),d=q(!1),u=oe(()=>l.current=!1,[]);return W(()=>()=>document.removeEventListener("pointerup",u),[u]),o(Na,{asChild:!0,...s,children:o(le.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:c,onPointerMove:X(e.onPointerMove,p=>{p.pointerType!=="touch"&&!d.current&&!a.isPointerInTransitRef.current&&(i.onTriggerEnter(),d.current=!0)}),onPointerLeave:X(e.onPointerLeave,()=>{i.onTriggerLeave(),d.current=!1}),onPointerDown:X(e.onPointerDown,()=>{i.open&&i.onClose(),l.current=!0,document.addEventListener("pointerup",u,{once:!0})}),onFocus:X(e.onFocus,()=>{l.current||i.onOpen()}),onBlur:X(e.onBlur,i.onClose),onClick:X(e.onClick,i.onClose)})})});tb.displayName=cu;var lu="TooltipPortal",[Hx,Kx]=Ys(lu,{forceMount:void 0}),nb=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,a=Da(lu,t);return o(Hx,{scope:t,forceMount:n,children:o(ot,{present:n||a.open,children:o(fr,{asChild:!0,container:i,children:r})})})};nb.displayName=lu;var Ni="TooltipContent",rb=K((e,t)=>{const n=Kx(Ni,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...a}=e,s=Da(Ni,e.__scopeTooltip);return o(ot,{present:r||s.open,children:s.disableHoverableContent?o(ib,{side:i,...a,ref:t}):o(Vx,{side:i,...a,ref:t})})}),Vx=K((e,t)=>{const n=Da(Ni,e.__scopeTooltip),r=su(Ni,e.__scopeTooltip),i=q(null),a=be(t,i),[s,c]=D(null),{trigger:l,onClose:d}=n,u=i.current,{onPointerInTransitChange:p}=r,m=oe(()=>{c(null),p(!1)},[p]),f=oe((y,g)=>{const h=y.currentTarget,b={x:y.clientX,y:y.clientY},w=Xx(b,Yx(b,h.getBoundingClientRect())),_=Qx(g.getBoundingClientRect());c(e0([...w,..._])),p(!0)},[p]);return W(()=>()=>m(),[m]),W(()=>{if(l&&u){const y=h=>f(h,u),g=h=>f(h,l);return l.addEventListener("pointerleave",y),u.addEventListener("pointerleave",g),()=>{l.removeEventListener("pointerleave",y),u.removeEventListener("pointerleave",g)}}},[l,u,f,m]),W(()=>{if(s){const y=g=>{const h=g.target,b={x:g.clientX,y:g.clientY},w=l?.contains(h)||u?.contains(h),_=!Zx(b,s);w?m():_&&(m(),d())};return document.addEventListener("pointermove",y),()=>document.removeEventListener("pointermove",y)}},[l,u,s,d,m]),o(ib,{...e,ref:a})}),[Wx,zx]=Ys(xa,{isInside:!1}),Jx=UN("TooltipContent"),ib=K((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:s,...c}=e,l=Da(Ni,n),d=Xs(n),{onClose:u}=l;return W(()=>(document.addEventListener(ou,u),()=>document.removeEventListener(ou,u)),[u]),W(()=>{if(l.trigger){const p=m=>{m.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,u]),o(mr,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:u,children:o(Ts,{"data-state":l.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[o(Jx,{children:r}),o(Wx,{scope:n,isInside:!0,children:o(_T,{id:l.contentId,role:"tooltip",children:i||r})})]})})});rb.displayName=Ni;var ab="TooltipArrow",ob=K((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Xs(n);return zx(ab,n).isInside?null:o(Rs,{...i,...r,ref:t})});ob.displayName=ab;function Yx(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),a=Math.abs(t.left-e.x);switch(Math.min(n,r,i,a)){case a:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Xx(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Qx(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function Zx(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function e0(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),t0(t)}function t0(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const a=t[t.length-1],s=t[t.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const a=n[n.length-1],s=n[n.length-2];if((a.x-s.x)*(i.y-s.y)>=(a.y-s.y)*(i.x-s.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var n0=Zy,r0=eb,i0=tb,a0=nb,o0=rb,s0=ob;function du({children:e,delayDuration:t=400,skipDelayDuration:n=300}){return o(n0,{delayDuration:t,skipDelayDuration:n,children:e})}function Qs({children:e,label:t,side:n="top",align:r="center",sideOffset:i=6,asChild:a=!0,disabled:s=!1}){return s?o(z,{children:e}):o(r0,{children:[o(i0,{asChild:a,children:e}),o(a0,{children:o(o0,{align:r,className:"tooltip-content",side:n,sideOffset:i,children:[t,o(s0,{className:"tooltip-arrow"})]})})]})}function c0(e){e.dataset.feedRenderRoot="preact"}function l0(){const e=document.getElementById("tab-feed");e&&(e.dataset.feedRenderBoundary="preact-hybrid")}function d0(e,t){c0(e),He(v(du,null,t),e)}function u0(e){return e.hasInspectorOverride?e.inspectorQuery:e.feedQuery}function p0(e){return e.split(/\n|,/).map(t=>t.trim()).filter(Boolean)}function uu(e){return JSON.stringify([e.project,e.query.trim(),e.workingSetFiles])}function m0(e){const t=Ws(e?.metadata_json),n=String(e?.subtitle||t?.subtitle||"").trim(),r=String(e?.narrative||t?.narrative||e?.body_text||"").trim(),i=Ea(n),a=Ea(r),s=!!r&&a!==i,c=Vs(e?.facts||t?.facts||[]),l=c.length?c:Ex(r||n),d=l.length?l:xx(r||n);return{summary:n,narrative:r,facts:d,hasSummary:!!n,hasFacts:d.length>0,hasNarrative:s}}function f0(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 h0(e){return e.hasSummary?"summary":e.hasFacts?"facts":"narrative"}function g0(e,t){return e==="facts"?!1:e==="summary"?t.summary.length>260:t.narrative.length>320}function v0(e){return e==="summary"?["clamp","clamp-3"]:["clamp","clamp-5"]}function y0(e,t){const n=S.feedTypeFilter==="observations"?" · observations":S.feedTypeFilter==="summaries"?" · session summaries":"",r=Lx(S.feedScopeFilter),i=!S.feedQuery.trim()&&S.lastFeedFilteredCount?` · ${S.lastFeedFilteredCount} observations filtered`:"";return`${e} items${n}${r}${S.feedQuery.trim()?` · matching "${S.feedQuery.trim()}"`:""}${i}${t?" · scroll for more":""}`}function Zs({label:e,candidates:t}){return t.length===0?null:v("div",{className:"trace-group"},v("div",{className:"section-meta"},e),v("div",{className:"feed-list"},t.map(n=>v("div",{className:"feed-card",key:`${e}:${n.id}`},v("div",{className:"feed-card-header"},[v("div",{className:"feed-card-title"},`${n.rank}. ${n.title}`),v("div",{className:"feed-card-meta"},`#${n.id} · ${n.kind}${n.section?` · ${n.section}`:""}`)]),v("div",{className:"feed-card-body"},[v("div",null,n.preview||"No preview available."),n.reasons.length?v("div",{className:"section-meta"},`Reasons: ${n.reasons.join(", ")}`):null])))))}function b0({open:e}){const[t,n]=D(()=>String(S.feedQuery||"")),[r,i]=D(!1),[a,s]=D(!1),[c,l]=D(""),[d,u]=D(!1),[p,m]=D(""),[f,y]=D(""),[g,h]=D(null),b=q(0),w=String(S.feedQuery||""),_=String(t||"").trim(),I=S.currentProject||null,N=p0(c),T=uu({project:I,query:_,workingSetFiles:N}),x=g&&uu({project:g.inputs.project,query:g.inputs.query,workingSetFiles:g.inputs.working_set_files})===T?g:null,j=p&&f===T?p:"";W(()=>{b.current+=1,u(!1),m(""),y(""),h($=>!$||$.inputs.query!==_||$.inputs.project!==I?null:$)},[T]),W(()=>{e&&!r&&(n(u0({feedQuery:w,hasInspectorOverride:a,inspectorQuery:t})),i(!0))},[w,a,r,t,e]);const B=async()=>{const $=_,A=I,E=N,C=uu({project:A,query:$,workingSetFiles:E}),L=b.current+1;if(b.current=L,!$){m("Enter a query to inspect."),y(C),h(null);return}u(!0),m(""),y("");try{const U=await lC({context:$,project:A,working_set_files:E});if(L!==b.current)return;h(U)}catch(U){if(L!==b.current)return;m(U instanceof Error?U.message:String(U)),y(C),h(null)}finally{L===b.current&&u(!1)}},P=x?.retrieval.candidates.filter($=>$.disposition==="selected")||[],F=x?.retrieval.candidates.filter($=>$.disposition==="dropped")||[],O=x?.retrieval.candidates.filter($=>$.disposition==="deduped")||[],G=x?.retrieval.candidates.filter($=>$.disposition==="trimmed")||[];return e?v("div",{className:"feed-inspector"},v("div",{className:"feed-card",id:"contextInspectorPanel",style:"margin-top:12px;"},[v("div",{className:"feed-card-header"},[v("div",{className:"feed-card-title"},"Context Inspector"),v("div",{className:"feed-card-meta"},a?"Tracing an inspector-specific query":"Seeded from the feed search on first open")]),v("div",{className:"feed-card-body"},[v("input",{className:"feed-search",onInput:$=>{n(String($.currentTarget.value||"")),s(!0),h(null),m(""),y("")},placeholder:"Trace a pack query…",value:t}),v("div",{className:"section-meta",style:"margin-top:8px;"},a?"Inspector query is independent from the live feed search.":"Inspector query was seeded from the feed search and will stay independent until you change it."),v("textarea",{className:"feed-inspector-files",onInput:$=>l(String($.currentTarget.value||"")),placeholder:"Optional working-set files, one per line",rows:3,value:c}),v("div",{style:"display:flex; gap:8px; margin-top:8px; align-items:center;"},v("button",{className:"toggle-button active",disabled:d,onClick:()=>{B()},type:"button"},d?"Tracing…":"Run trace"),x?v("span",{className:"section-meta"},`mode=${x.mode.selected} · candidates=${x.retrieval.candidate_count} · tokens=${x.output.estimated_tokens}`):null),g&&!x?v("div",{className:"section-meta",style:"margin-top:8px;"},"Trace inputs changed. Run trace again for the current query, project, and working set."):null,j?v("div",{className:"section-meta",style:"margin-top:8px; color:#d96c6c;"},j):null]),x?v(z,null,[v(Zs,{label:"Selected",candidates:P}),v(Zs,{label:"Dropped",candidates:F}),v(Zs,{label:"Deduped",candidates:O}),v(Zs,{label:"Trimmed",candidates:G}),v("div",{className:"feed-card-body"},[x.assembly.collapsed_groups.length?v("div",{className:"section-meta"},`Collapsed duplicates: ${x.assembly.collapsed_groups.map($=>`kept #${$.kept} from [${$.dropped.join(", ")}]`).join(" · ")}`):null,x.assembly.trim_reasons.length?v("div",{className:"section-meta"},`Trim reasons: ${x.assembly.trim_reasons.join(", ")}`):null,v("div",{className:"section-meta"},"Final pack"),v("pre",{style:"white-space:pre-wrap; overflow:auto;"},x.output.pack_text)])]):null])):null}var _0={kind:"kind-chip",provenance:"provenance-chip",tag:"tag-chip",badge:"badge",scope:"peer-scope-chip"};function pu({variant:e,tone:t,title:n,children:r}){const i=_0[e];return o("span",{className:t?`${i} ${t}`:i,title:n,children:r})}function sb(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 w0(e){if(Array.isArray(e))return e}function S0(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,s,c=[],l=!0,d=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(l=(r=a.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw i}}return c}}function C0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
47
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function N0(e,t){return w0(e)||S0(e,t)||I0(e,t)||C0()}function I0(e,t){if(e){if(typeof e=="string")return sb(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)?sb(e,t):void 0}}var cb=Object.entries,lb=Object.setPrototypeOf,k0=Object.isFrozen,T0=Object.getPrototypeOf,R0=Object.getOwnPropertyDescriptor,tt=Object.freeze,nt=Object.seal,Ii=Object.create,db=typeof Reflect<"u"&&Reflect,mu=db.apply,fu=db.construct;tt||(tt=function(t){return t}),nt||(nt=function(t){return t}),mu||(mu=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a];return t.apply(n,i)}),fu||(fu=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 La=We(Array.prototype.forEach),P0=We(Array.prototype.lastIndexOf),ub=We(Array.prototype.pop),ki=We(Array.prototype.push),A0=We(Array.prototype.splice),Vn=Array.isArray,$a=We(String.prototype.toLowerCase),hu=We(String.prototype.toString),pb=We(String.prototype.match),Ma=We(String.prototype.replace),mb=We(String.prototype.indexOf),E0=We(String.prototype.trim),x0=We(Number.prototype.toString),D0=We(Boolean.prototype.toString),fb=typeof BigInt>"u"?null:We(BigInt.prototype.toString),hb=typeof Symbol>"u"?null:We(Symbol.prototype.toString),Ye=We(Object.prototype.hasOwnProperty),ja=We(Object.prototype.toString),rt=We(RegExp.prototype.test),Er=L0(TypeError);function We(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 mu(e,t,r)}}function L0(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return fu(e,n)}}function Ne(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:$a;if(lb&&lb(e,null),!Vn(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i=="string"){const a=n(i);a!==i&&(k0(t)||(t[r]=a),i=a)}e[i]=!0}return e}function $0(e){for(let t=0;t<e.length;t++)Ye(e,t)||(e[t]=null);return e}function mt(e){const t=Ii(null);for(const r of cb(e)){var n=N0(r,2);const i=n[0],a=n[1];Ye(e,i)&&(Vn(a)?t[i]=$0(a):a&&typeof a=="object"&&a.constructor===Object?t[i]=mt(a):t[i]=a)}return t}function M0(e){switch(typeof e){case"string":return e;case"number":return x0(e);case"boolean":return D0(e);case"bigint":return fb?fb(e):"0";case"symbol":return hb?hb(e):"Symbol()";case"undefined":return ja(e);case"function":case"object":{if(e===null)return ja(e);const t=e,n=Qt(t,"toString");if(typeof n=="function"){const r=n(t);return typeof r=="string"?r:ja(r)}return ja(e)}default:return ja(e)}}function Qt(e,t){for(;e!==null;){const r=R0(e,t);if(r){if(r.get)return We(r.get);if(typeof r.value=="function")return We(r.value)}e=T0(e)}function n(){return null}return n}function j0(e){try{return rt(e,""),!0}catch{return!1}}var gb=tt(["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"]),gu=tt(["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"]),vu=tt(["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"]),O0=tt(["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"]),yu=tt(["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"]),F0=tt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),vb=tt(["#text"]),yb=tt(["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"]),bu=tt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),bb=tt(["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"]),ec=tt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),B0=nt(/{{[\w\W]*|^[\w\W]*}}/g),U0=nt(/<%[\w\W]*|^[\w\W]*%>/g),q0=nt(/\${[\w\W]*/g),G0=nt(/^data-[\-\w.\u00B7-\uFFFF]+$/),H0=nt(/^aria-[\-\w]+$/),_b=nt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),K0=nt(/^(?:\w+script|data):/i),V0=nt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),W0=nt(/^html$/i),z0=nt(/^[a-z][.\w]*(-[.\w]+)+$/i),wb=nt(/<[/\w!]/g),J0=nt(/<[/\w]/g),Y0=nt(/<\/no(script|embed|frames)/i),X0=nt(/\/>/i),Zt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Q0=function(){return typeof window>"u"?null:window},Z0=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const a="dompurify"+(r?"#"+r:"");try{return t.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},Sb=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Wn=function(t,n,r,i){return Ye(t,n)&&Vn(t[n])?Ne(i.base?mt(i.base):{},t[n],i.transform):r};function Cb(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Q0();const t=ee=>Cb(ee);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==Zt.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,i=r.currentScript;e.DocumentFragment;const a=e.HTMLTemplateElement,s=e.Node,c=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,u=e.trustedTypes,p=c.prototype,m=Qt(p,"cloneNode"),f=Qt(p,"remove"),y=Qt(p,"nextSibling"),g=Qt(p,"childNodes"),h=Qt(p,"parentNode"),b=Qt(p,"shadowRoot"),w=Qt(p,"attributes"),_=s&&s.prototype?Qt(s.prototype,"nodeType"):null,I=s&&s.prototype?Qt(s.prototype,"nodeName"):null;if(typeof a=="function"){const ee=n.createElement("template");ee.content&&ee.content.ownerDocument&&(n=ee.content.ownerDocument)}let N,T="",x,j=!1,B=0;const P=function(){if(B>0)throw Er('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.')},F=function(k){P(),B++;try{return N.createHTML(k)}finally{B--}},O=function(k){P(),B++;try{return N.createScriptURL(k)}finally{B--}},G=function(){return j||(x=Z0(u,i),j=!0),x},$=n,A=$.implementation,E=$.createNodeIterator,C=$.createDocumentFragment,L=$.getElementsByTagName,U=r.importNode;let V=Sb();t.isSupported=typeof cb=="function"&&typeof h=="function"&&A&&A.createHTMLDocument!==void 0;const de=B0,ie=U0,ne=q0,Re=G0,ye=H0,Ce=K0,re=V0,Pe=z0;let ue=_b,H=null;const fe=Ne({},[...gb,...gu,...vu,...yu,...vb]);let ae=null;const Te=Ne({},[...yb,...bu,...bb,...ec]);let ce=Object.seal(Ii(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}})),Be=null,Z=null;const te=Object.seal(Ii(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Qe=!0,$e=!0,an=!1,Nn=!0,yt=!1,In=!0,he=!1,bt=!1,Nt=null,qi=null,yo=!1,kn=!1,Wr=!1,ir=!1,_t=!0,ar=!1;const kS="user-content-";let Wp=!0,zp=!1,Gi={},on=null;const Jp=Ne({},["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 TS=null;const RS=Ne({},["audio","video","img","source","image","track"]);let Yp=null;const PS=Ne({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Uc="http://www.w3.org/1998/Math/MathML",qc="http://www.w3.org/2000/svg",sn="http://www.w3.org/1999/xhtml";let Hi=sn,Xp=!1,Qp=null;const DB=Ne({},[Uc,qc,sn],hu),AS=tt(["mi","mo","mn","ms","mtext"]);let Zp=Ne({},AS);const ES=tt(["annotation-xml"]);let em=Ne({},ES);const LB=Ne({},["title","style","font","a","script"]);let bo=null;const $B=["application/xhtml+xml","text/html"],MB="text/html";let Ve=null,Ki=null;const jB=n.createElement("form"),xS=function(k){return k instanceof RegExp||k instanceof Function},tm=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ki&&Ki===k)return;(!k||typeof k!="object")&&(k={}),k=mt(k),bo=$B.indexOf(k.PARSER_MEDIA_TYPE)===-1?MB:k.PARSER_MEDIA_TYPE,Ve=bo==="application/xhtml+xml"?hu:$a,H=Wn(k,"ALLOWED_TAGS",fe,{transform:Ve}),ae=Wn(k,"ALLOWED_ATTR",Te,{transform:Ve}),Qp=Wn(k,"ALLOWED_NAMESPACES",DB,{transform:hu}),Yp=Wn(k,"ADD_URI_SAFE_ATTR",PS,{transform:Ve,base:PS}),TS=Wn(k,"ADD_DATA_URI_TAGS",RS,{transform:Ve,base:RS}),on=Wn(k,"FORBID_CONTENTS",Jp,{transform:Ve}),Be=Wn(k,"FORBID_TAGS",mt({}),{transform:Ve}),Z=Wn(k,"FORBID_ATTR",mt({}),{transform:Ve}),Gi=Ye(k,"USE_PROFILES")?k.USE_PROFILES&&typeof k.USE_PROFILES=="object"?mt(k.USE_PROFILES):k.USE_PROFILES:!1,Qe=k.ALLOW_ARIA_ATTR!==!1,$e=k.ALLOW_DATA_ATTR!==!1,an=k.ALLOW_UNKNOWN_PROTOCOLS||!1,Nn=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,yt=k.SAFE_FOR_TEMPLATES||!1,In=k.SAFE_FOR_XML!==!1,he=k.WHOLE_DOCUMENT||!1,kn=k.RETURN_DOM||!1,Wr=k.RETURN_DOM_FRAGMENT||!1,ir=k.RETURN_TRUSTED_TYPE||!1,yo=k.FORCE_BODY||!1,_t=k.SANITIZE_DOM!==!1,ar=k.SANITIZE_NAMED_PROPS||!1,Wp=k.KEEP_CONTENT!==!1,zp=k.IN_PLACE||!1,ue=j0(k.ALLOWED_URI_REGEXP)?k.ALLOWED_URI_REGEXP:_b,Hi=typeof k.NAMESPACE=="string"?k.NAMESPACE:sn,Zp=Ye(k,"MATHML_TEXT_INTEGRATION_POINTS")&&k.MATHML_TEXT_INTEGRATION_POINTS&&typeof k.MATHML_TEXT_INTEGRATION_POINTS=="object"?mt(k.MATHML_TEXT_INTEGRATION_POINTS):Ne({},AS),em=Ye(k,"HTML_INTEGRATION_POINTS")&&k.HTML_INTEGRATION_POINTS&&typeof k.HTML_INTEGRATION_POINTS=="object"?mt(k.HTML_INTEGRATION_POINTS):Ne({},ES);const M=Ye(k,"CUSTOM_ELEMENT_HANDLING")&&k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING=="object"?mt(k.CUSTOM_ELEMENT_HANDLING):Ii(null);if(ce=Ii(null),Ye(M,"tagNameCheck")&&xS(M.tagNameCheck)&&(ce.tagNameCheck=M.tagNameCheck),Ye(M,"attributeNameCheck")&&xS(M.attributeNameCheck)&&(ce.attributeNameCheck=M.attributeNameCheck),Ye(M,"allowCustomizedBuiltInElements")&&typeof M.allowCustomizedBuiltInElements=="boolean"&&(ce.allowCustomizedBuiltInElements=M.allowCustomizedBuiltInElements),nt(ce),yt&&($e=!1),Wr&&(kn=!0),Gi&&(H=Ne({},vb),ae=Ii(null),Gi.html===!0&&(Ne(H,gb),Ne(ae,yb)),Gi.svg===!0&&(Ne(H,gu),Ne(ae,bu),Ne(ae,ec)),Gi.svgFilters===!0&&(Ne(H,vu),Ne(ae,bu),Ne(ae,ec)),Gi.mathMl===!0&&(Ne(H,yu),Ne(ae,bb),Ne(ae,ec))),te.tagCheck=null,te.attributeCheck=null,Ye(k,"ADD_TAGS")&&(typeof k.ADD_TAGS=="function"?te.tagCheck=k.ADD_TAGS:Vn(k.ADD_TAGS)&&(H===fe&&(H=mt(H)),Ne(H,k.ADD_TAGS,Ve))),Ye(k,"ADD_ATTR")&&(typeof k.ADD_ATTR=="function"?te.attributeCheck=k.ADD_ATTR:Vn(k.ADD_ATTR)&&(ae===Te&&(ae=mt(ae)),Ne(ae,k.ADD_ATTR,Ve))),Ye(k,"ADD_URI_SAFE_ATTR")&&Vn(k.ADD_URI_SAFE_ATTR)&&Ne(Yp,k.ADD_URI_SAFE_ATTR,Ve),Ye(k,"FORBID_CONTENTS")&&Vn(k.FORBID_CONTENTS)&&(on===Jp&&(on=mt(on)),Ne(on,k.FORBID_CONTENTS,Ve)),Ye(k,"ADD_FORBID_CONTENTS")&&Vn(k.ADD_FORBID_CONTENTS)&&(on===Jp&&(on=mt(on)),Ne(on,k.ADD_FORBID_CONTENTS,Ve)),Wp&&(H["#text"]=!0),he&&Ne(H,["html","head","body"]),H.table&&(Ne(H,["tbody"]),delete Be.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw Er('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Er('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Q=N;N=k.TRUSTED_TYPES_POLICY;try{T=F("")}catch(se){throw N=Q,se}}else k.TRUSTED_TYPES_POLICY===null?(N=void 0,T=""):(N===void 0&&(N=G()),N&&typeof T=="string"&&(T=F("")));tt&&tt(k),Ki=k},DS=Ne({},[...gu,...vu,...O0]),LS=Ne({},[...yu,...F0]),OB=function(k,M,Q){return M.namespaceURI===sn?k==="svg":M.namespaceURI===Uc?k==="svg"&&(Q==="annotation-xml"||Zp[Q]):!!DS[k]},FB=function(k,M,Q){return M.namespaceURI===sn?k==="math":M.namespaceURI===qc?k==="math"&&em[Q]:!!LS[k]},BB=function(k,M,Q){return M.namespaceURI===qc&&!em[Q]||M.namespaceURI===Uc&&!Zp[Q]?!1:!LS[k]&&(LB[k]||!DS[k])},UB=function(k){let M=h(k);(!M||!M.tagName)&&(M={namespaceURI:Hi,tagName:"template"});const Q=$a(k.tagName),se=$a(M.tagName);return Qp[k.namespaceURI]?k.namespaceURI===qc?OB(Q,M,se):k.namespaceURI===Uc?FB(Q,M,se):k.namespaceURI===sn?BB(Q,M,se):!!(bo==="application/xhtml+xml"&&Qp[k.namespaceURI]):!1},or=function(k){ki(t.removed,{element:k});try{h(k).removeChild(k)}catch{if(f(k),!h(k))throw Er("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},$S=function(k){const M=g(k);if(M){const se=[];La(M,we=>{ki(se,we)}),La(se,we=>{try{f(we)}catch{}})}const Q=w(k);if(Q)for(let se=Q.length-1;se>=0;--se){const we=Q[se],De=we&&we.name;if(typeof De=="string")try{k.removeAttribute(De)}catch{}}},zr=function(k,M){try{ki(t.removed,{attribute:M.getAttributeNode(k),from:M})}catch{ki(t.removed,{attribute:null,from:M})}if(M.removeAttribute(k),k==="is")if(kn||Wr)try{or(M)}catch{}else try{M.setAttribute(k,"")}catch{}},qB=function(k){const M=w(k);if(M)for(let Q=M.length-1;Q>=0;--Q){const se=M[Q],we=se&&se.name;if(!(typeof we!="string"||ae[Ve(we)]))try{k.removeAttribute(we)}catch{}}},GB=function(k){const M=[k];for(;M.length>0;){const Q=M.pop();(_?_(Q):Q.nodeType)===Zt.element&&qB(Q);const se=g(Q);if(se)for(let we=se.length-1;we>=0;--we)M.push(se[we])}},MS=function(k){let M=null,Q=null;if(yo)k="<remove></remove>"+k;else{const De=pb(k,/^[\r\n\t ]+/);Q=De&&De[0]}bo==="application/xhtml+xml"&&Hi===sn&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const se=N?F(k):k;if(Hi===sn)try{M=new d().parseFromString(se,bo)}catch{}if(!M||!M.documentElement){M=A.createDocument(Hi,"template",null);try{M.documentElement.innerHTML=Xp?T:se}catch{}}const we=M.body||M.documentElement;return k&&Q&&we.insertBefore(n.createTextNode(Q),we.childNodes[0]||null),Hi===sn?L.call(M,he?"html":"body")[0]:he?M.documentElement:we},jS=function(k){return E.call(k.ownerDocument||k,k,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Gc=function(k){return k=Ma(k,de," "),k=Ma(k,ie," "),k=Ma(k,ne," "),k},nm=function(k){var M;k.normalize();const Q=E.call(k.ownerDocument||k,k,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let se=Q.nextNode();for(;se;)se.data=Gc(se.data),se=Q.nextNode();const we=(M=k.querySelectorAll)===null||M===void 0?void 0:M.call(k,"template");we&&La(we,De=>{Vi(De.content)&&nm(De.content)})},Hc=function(k){const M=I?I(k):null;return typeof M!="string"||Ve(M)!=="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)},Vi=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return _(k)===Zt.documentFragment}catch{return!1}},_o=function(k){if(!_||typeof k!="object"||k===null)return!1;try{return typeof _(k)=="number"}catch{return!1}};function Tn(ee,k,M){ee.length!==0&&La(ee,Q=>{Q.call(t,k,M,Ki)})}const HB=function(k,M){return!!(In&&k.hasChildNodes()&&!_o(k.firstElementChild)&&rt(wb,k.textContent)&&rt(wb,k.innerHTML)||In&&k.namespaceURI===sn&&M==="style"&&_o(k.firstElementChild)||k.nodeType===Zt.processingInstruction||In&&k.nodeType===Zt.comment&&rt(J0,k.data))},KB=function(k,M){if(!Be[M]&&BS(M)&&(ce.tagNameCheck instanceof RegExp&&rt(ce.tagNameCheck,M)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(M)))return!1;if(Wp&&!on[M]){const Q=h(k),se=g(k);if(se&&Q){const we=se.length;for(let De=we-1;De>=0;--De){const Ue=zp?se[De]:m(se[De],!0);Q.insertBefore(Ue,y(k))}}}return or(k),!0},OS=function(k){if(Tn(V.beforeSanitizeElements,k,null),Hc(k))return or(k),!0;const M=Ve(I?I(k):k.nodeName);if(Tn(V.uponSanitizeElement,k,{tagName:M,allowedTags:H}),HB(k,M))return or(k),!0;if(Be[M]||!(te.tagCheck instanceof Function&&te.tagCheck(M))&&!H[M])return KB(k,M);if((_?_(k):k.nodeType)===Zt.element&&!UB(k)||(M==="noscript"||M==="noembed"||M==="noframes")&&rt(Y0,k.innerHTML))return or(k),!0;if(yt&&k.nodeType===Zt.text){const Q=Gc(k.textContent);k.textContent!==Q&&(ki(t.removed,{element:k.cloneNode()}),k.textContent=Q)}return Tn(V.afterSanitizeElements,k,null),!1},FS=function(k,M,Q){if(Z[M]||_t&&(M==="id"||M==="name")&&(Q in n||Q in jB))return!1;const se=ae[M]||te.attributeCheck instanceof Function&&te.attributeCheck(M,k);if(!($e&&rt(Re,M))){if(!(Qe&&rt(ye,M))){if(se){if(!Yp[M]){if(!rt(ue,Ma(Q,re,""))){if(!((M==="src"||M==="xlink:href"||M==="href")&&k!=="script"&&mb(Q,"data:")===0&&TS[k])){if(!(an&&!rt(Ce,Ma(Q,re,"")))){if(Q)return!1}}}}}else if(!(BS(k)&&(ce.tagNameCheck instanceof RegExp&&rt(ce.tagNameCheck,k)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(k))&&(ce.attributeNameCheck instanceof RegExp&&rt(ce.attributeNameCheck,M)||ce.attributeNameCheck instanceof Function&&ce.attributeNameCheck(M,k))||M==="is"&&ce.allowCustomizedBuiltInElements&&(ce.tagNameCheck instanceof RegExp&&rt(ce.tagNameCheck,Q)||ce.tagNameCheck instanceof Function&&ce.tagNameCheck(Q))))return!1}}return!0},VB=Ne({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),BS=function(k){return!VB[$a(k)]&&rt(Pe,k)},WB=function(k,M,Q,se){if(N&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!Q)switch(u.getAttributeType(k,M)){case"TrustedHTML":return F(se);case"TrustedScriptURL":return O(se)}return se},zB=function(k,M,Q,se){try{Q?k.setAttributeNS(Q,M,se):k.setAttribute(M,se),Hc(k)?or(k):ub(t.removed)}catch{zr(M,k)}},US=function(k){Tn(V.beforeSanitizeAttributes,k,null);const M=k.attributes;if(!M||Hc(k))return;const Q={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ae,forceKeepAttr:void 0};let se=M.length;const we=Ve(k.nodeName);for(;se--;){const De=M[se],Ue=De.name,Dt=De.namespaceURI,Rn=De.value,qt=Ve(Ue),im=Rn;let ht=Ue==="value"?im:E0(im);if(Q.attrName=qt,Q.attrValue=ht,Q.keepAttr=!0,Q.forceKeepAttr=void 0,Tn(V.uponSanitizeAttribute,k,Q),ht=Q.attrValue,ar&&(qt==="id"||qt==="name")&&mb(ht,kS)!==0&&(zr(Ue,k),ht=kS+ht),In&&rt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,ht)){zr(Ue,k);continue}if(qt==="attributename"&&pb(ht,"href")){zr(Ue,k);continue}if(!Q.forceKeepAttr){if(!Q.keepAttr){zr(Ue,k);continue}if(!Nn&&rt(X0,ht)){zr(Ue,k);continue}if(yt&&(ht=Gc(ht)),!FS(we,qt,ht)){zr(Ue,k);continue}ht=WB(we,qt,Dt,ht),ht!==im&&zB(k,Ue,Dt,ht)}}Tn(V.afterSanitizeAttributes,k,null)},Kc=function(k){let M=null;const Q=jS(k);for(Tn(V.beforeSanitizeShadowDOM,k,null);M=Q.nextNode();)if(Tn(V.uponSanitizeShadowNode,M,null),OS(M),US(M),Vi(M.content)&&Kc(M.content),(_?_(M):M.nodeType)===Zt.element){const se=b(M);Vi(se)&&(rm(se),Kc(se))}Tn(V.afterSanitizeShadowDOM,k,null)},rm=function(k){const M=[{node:k,shadow:null}];for(;M.length>0;){const Q=M.pop();if(Q.shadow){Kc(Q.shadow);continue}const se=Q.node,we=(_?_(se):se.nodeType)===Zt.element,De=g(se);if(De)for(let Ue=De.length-1;Ue>=0;--Ue)M.push({node:De[Ue],shadow:null});if(we){const Ue=I?I(se):null;if(typeof Ue=="string"&&Ve(Ue)==="template"){const Dt=se.content;Vi(Dt)&&M.push({node:Dt,shadow:null})}}if(we){const Ue=b(se);Vi(Ue)&&M.push({node:null,shadow:Ue},{node:Ue,shadow:null})}}};return t.sanitize=function(ee){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,Q=null,se=null,we=null;if(Xp=!ee,Xp&&(ee="<!-->"),typeof ee!="string"&&!_o(ee)&&(ee=M0(ee),typeof ee!="string"))throw Er("dirty is not a string, aborting");if(!t.isSupported)return ee;bt?(H=Nt,ae=qi):tm(k),(V.uponSanitizeElement.length>0||V.uponSanitizeAttribute.length>0)&&(H=mt(H)),V.uponSanitizeAttribute.length>0&&(ae=mt(ae)),t.removed=[];const De=zp&&typeof ee!="string"&&_o(ee);if(De){const Rn=I?I(ee):ee.nodeName;if(typeof Rn=="string"){const qt=Ve(Rn);if(!H[qt]||Be[qt])throw Er("root node is forbidden and cannot be sanitized in-place")}if(Hc(ee))throw Er("root node is clobbered and cannot be sanitized in-place");try{rm(ee)}catch(qt){throw $S(ee),qt}}else if(_o(ee))M=MS("<!---->"),Q=M.ownerDocument.importNode(ee,!0),Q.nodeType===Zt.element&&Q.nodeName==="BODY"||Q.nodeName==="HTML"?M=Q:M.appendChild(Q),rm(Q);else{if(!kn&&!yt&&!he&&ee.indexOf("<")===-1)return N&&ir?F(ee):ee;if(M=MS(ee),!M)return kn?null:ir?T:""}M&&yo&&or(M.firstChild);const Ue=jS(De?ee:M);try{for(;se=Ue.nextNode();)OS(se),US(se),Vi(se.content)&&Kc(se.content)}catch(Rn){throw De&&$S(ee),Rn}if(De)return La(t.removed,Rn=>{Rn.element&&GB(Rn.element)}),yt&&nm(ee),ee;if(kn){if(yt&&nm(M),Wr)for(we=C.call(M.ownerDocument);M.firstChild;)we.appendChild(M.firstChild);else we=M;return(ae.shadowroot||ae.shadowrootmode)&&(we=U.call(r,we,!0)),we}let Dt=he?M.outerHTML:M.innerHTML;return he&&H["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&rt(W0,M.ownerDocument.doctype.name)&&(Dt="<!DOCTYPE "+M.ownerDocument.doctype.name+`>
|
|
48
|
+
`+Dt),yt&&(Dt=Gc(Dt)),N&&ir?F(Dt):Dt},t.setConfig=function(){tm(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),bt=!0,Nt=H,qi=ae},t.clearConfig=function(){Ki=null,bt=!1,Nt=null,qi=null,N=x,T=""},t.isValidAttribute=function(ee,k,M){return Ki||tm({}),FS(Ve(ee),Ve(k),M)},t.addHook=function(ee,k){typeof k=="function"&&Ye(V,ee)&&ki(V[ee],k)},t.removeHook=function(ee,k){if(Ye(V,ee)){if(k!==void 0){const M=P0(V[ee],k);return M===-1?void 0:A0(V[ee],M,1)[0]}return ub(V[ee])}},t.removeHooks=function(ee){Ye(V,ee)&&(V[ee]=[])},t.removeAllHooks=function(){V=Sb()},t}var Nb=Cb();function _u(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var xr=_u();function Ib(e){xr=e}var Dr={exec:()=>null};function Ti(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 Ie(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(i,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(st.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,t)};return r}var eD=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),st={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:Ti(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Ti(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Ti(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Ti(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Ti(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Ti(e=>new RegExp(`^ {0,${e}}>`))},tD=/^(?:[ \t]*(?:\n|$))+/,nD=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,rD=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Oa=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,iD=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,wu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Tb=Ie(kb).replace(/bull/g,wu).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),aD=Ie(kb).replace(/bull/g,wu).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Su=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,oD=/^[^\n]+/,Cu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,sD=Ie(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Cu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),cD=Ie(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,wu).getRegex(),tc="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",Nu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,lD=Ie("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\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",Nu).replace("tag",tc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Rb=Ie(Su).replace("hr",Oa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",tc).getRegex(),Iu={blockquote:Ie(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Rb).getRegex(),code:nD,def:sD,fences:rD,heading:iD,hr:Oa,html:lD,lheading:Tb,list:cD,newline:tD,paragraph:Rb,table:Dr,text:oD},Pb=Ie("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Oa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",tc).getRegex(),dD={...Iu,lheading:aD,table:Pb,paragraph:Ie(Su).replace("hr",Oa).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pb).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",tc).getRegex()},uD={...Iu,html:Ie(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Nu).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:Dr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ie(Su).replace("hr",Oa).replace("heading",` *#{1,6} *[^
|
|
49
|
+
]`).replace("lheading",Tb).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},pD=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,mD=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ab=/^( {2,}|\\)\n(?!\s*$)/,fD=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ri=/[\p{P}\p{S}]/u,nc=/[\s\p{P}\p{S}]/u,ku=/[^\s\p{P}\p{S}]/u,hD=Ie(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,nc).getRegex(),Eb=/(?!~)[\p{P}\p{S}]/u,gD=/(?!~)[\s\p{P}\p{S}]/u,vD=/(?:[^\s\p{P}\p{S}]|~)/u,yD=Ie(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",eD?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),xb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,bD=Ie(xb,"u").replace(/punct/g,Ri).getRegex(),_D=Ie(xb,"u").replace(/punct/g,Eb).getRegex(),Db="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",wD=Ie(Db,"gu").replace(/notPunctSpace/g,ku).replace(/punctSpace/g,nc).replace(/punct/g,Ri).getRegex(),SD=Ie(Db,"gu").replace(/notPunctSpace/g,vD).replace(/punctSpace/g,gD).replace(/punct/g,Eb).getRegex(),CD=Ie("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ku).replace(/punctSpace/g,nc).replace(/punct/g,Ri).getRegex(),ND=Ie(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ri).getRegex(),ID=Ie("^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)","gu").replace(/notPunctSpace/g,ku).replace(/punctSpace/g,nc).replace(/punct/g,Ri).getRegex(),kD=Ie(/\\(punct)/,"gu").replace(/punct/g,Ri).getRegex(),TD=Ie(/^<(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(),RD=Ie(Nu).replace("(?:-->|$)","-->").getRegex(),PD=Ie("^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",RD).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),rc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,AD=Ie(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",rc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Lb=Ie(/^!?\[(label)\]\[(ref)\]/).replace("label",rc).replace("ref",Cu).getRegex(),$b=Ie(/^!?\[(ref)\](?:\[\])?/).replace("ref",Cu).getRegex(),ED=Ie("reflink|nolink(?!\\()","g").replace("reflink",Lb).replace("nolink",$b).getRegex(),Mb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Tu={_backpedal:Dr,anyPunctuation:kD,autolink:TD,blockSkip:yD,br:Ab,code:mD,del:Dr,delLDelim:Dr,delRDelim:Dr,emStrongLDelim:bD,emStrongRDelimAst:wD,emStrongRDelimUnd:CD,escape:pD,link:AD,nolink:$b,punctuation:hD,reflink:Lb,reflinkSearch:ED,tag:PD,text:fD,url:Dr},xD={...Tu,link:Ie(/^!?\[(label)\]\((.*?)\)/).replace("label",rc).getRegex(),reflink:Ie(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",rc).getRegex()},Ru={...Tu,emStrongRDelimAst:SD,emStrongLDelim:_D,delLDelim:ND,delRDelim:ID,url:Ie(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Mb).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:Ie(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Mb).getRegex()},DD={...Ru,br:Ie(Ab).replace("{2,}","*").getRegex(),text:Ie(Ru.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ic={normal:Iu,gfm:dD,pedantic:uD},Fa={normal:Tu,gfm:Ru,breaks:DD,pedantic:xD},LD={"&":"&","<":"<",">":">",'"':""","'":"'"},jb=e=>LD[e];function en(e,t){if(t){if(st.escapeTest.test(e))return e.replace(st.escapeReplace,jb)}else if(st.escapeTestNoEncode.test(e))return e.replace(st.escapeReplaceNoEncode,jb);return e}function Ob(e){try{e=encodeURI(e).replace(st.percentDecode,"%")}catch{return null}return e}function Fb(e,t){let n=e.replace(st.findPipe,(i,a,s)=>{let c=!1,l=a;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}).split(st.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(st.slashPipe,"|");return n}function zn(e,t,n){let r=e.length;if(r===0)return"";let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Bb(e){let t=e.split(`
|
|
50
|
+
`),n=t.length-1;for(;n>=0&&st.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
51
|
+
`)}function $D(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 MD(e,t=0){let n=t,r="";for(let i of e)if(i===" "){let a=4-n%4;r+=" ".repeat(a),n+=a}else r+=i,n++;return r}function Ub(e,t,n,r,i){let a=t.href,s=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:s,text:c,tokens:r.inlineTokens(c)};return r.state.inLink=!1,l}function jD(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
52
52
|
`).map(a=>{let s=a.match(n.other.beginningSpace);if(s===null)return a;let[c]=s;return c.length>=i.length?a.slice(i.length):a}).join(`
|
|
53
|
-
`)}var
|
|
54
|
-
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:
|
|
55
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=
|
|
53
|
+
`)}var ac=class{options;rules;lexer;constructor(e){this.options=e||xr}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]:Bb(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=jD(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=zn(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:zn(t[0],`
|
|
54
|
+
`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:zn(t[0],`
|
|
55
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=zn(t[0],`
|
|
56
56
|
`).split(`
|
|
57
57
|
`),r="",i="",a=[];for(;n.length>0;){let s=!1,c=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))c.push(n[l]),s=!0;else if(!s)c.push(n[l]);else break;n=n.slice(l);let d=c.join(`
|
|
58
58
|
`),u=d.replace(this.rules.other.blockquoteSetextReplace,`
|
|
59
59
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
60
60
|
${d}`:d,i=i?`${i}
|
|
61
|
-
${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=p,n.length===0)break;let m=a.at(-1);if(m?.type==="code")break;if(m?.type==="blockquote"){let f=m,
|
|
61
|
+
${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=p,n.length===0)break;let m=a.at(-1);if(m?.type==="code")break;if(m?.type==="blockquote"){let f=m,y=f.raw+`
|
|
62
62
|
`+n.join(`
|
|
63
|
-
`),
|
|
63
|
+
`),g=this.blockquote(y);a[a.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,i=i.substring(0,i.length-f.text.length)+g.text;break}else if(m?.type==="list"){let f=m,y=f.raw+`
|
|
64
64
|
`+n.join(`
|
|
65
|
-
`),
|
|
66
|
-
`);continue}}return{type:"blockquote",raw:r,tokens:a,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 a=this.rules.other.listItemRegex(n),s=!1;for(;e;){let l=!1,d="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=
|
|
65
|
+
`),g=this.list(y);a[a.length-1]=g,r=r.substring(0,r.length-m.raw.length)+g.raw,i=i.substring(0,i.length-f.raw.length)+g.raw,n=y.substring(a.at(-1).raw.length).split(`
|
|
66
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:a,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 a=this.rules.other.listItemRegex(n),s=!1;for(;e;){let l=!1,d="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let p=MD(t[2].split(`
|
|
67
67
|
`,1)[0],t[1].length),m=e.split(`
|
|
68
|
-
`,1)[0],f=!p.trim(),
|
|
69
|
-
`,e=e.substring(m.length+1),l=!0),!l){let
|
|
70
|
-
`,1)[0],
|
|
71
|
-
`+
|
|
68
|
+
`,1)[0],f=!p.trim(),y=0;if(this.options.pedantic?(y=2,u=p.trimStart()):f?y=t[1].length+1:(y=p.search(this.rules.other.nonSpaceChar),y=y>4?1:y,u=p.slice(y),y+=t[1].length),f&&this.rules.other.blankLine.test(m)&&(d+=m+`
|
|
69
|
+
`,e=e.substring(m.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(y),h=this.rules.other.hrRegex(y),b=this.rules.other.fencesBeginRegex(y),w=this.rules.other.headingBeginRegex(y),_=this.rules.other.htmlBeginRegex(y),I=this.rules.other.blockquoteBeginRegex(y);for(;e;){let N=e.split(`
|
|
70
|
+
`,1)[0],T;if(m=N,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),T=m):T=m.replace(this.rules.other.tabCharGlobal," "),b.test(m)||w.test(m)||_.test(m)||I.test(m)||g.test(m)||h.test(m))break;if(T.search(this.rules.other.nonSpaceChar)>=y||!m.trim())u+=`
|
|
71
|
+
`+T.slice(y);else{if(f||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(p)||w.test(p)||h.test(p))break;u+=`
|
|
72
72
|
`+m}f=!m.trim(),d+=N+`
|
|
73
|
-
`,e=e.substring(N.length+1),p=
|
|
74
|
-
`),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=
|
|
75
|
-
`):[],a={type:"table",raw:
|
|
76
|
-
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?a.align.push("right"):this.rules.other.tableAlignCenter.test(s)?a.align.push("center"):this.rules.other.tableAlignLeft.test(s)?a.align.push("left"):a.align.push(null);for(let s=0;s<n.length;s++)a.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:a.align[s]});for(let s of i)a.rows.push(
|
|
73
|
+
`,e=e.substring(N.length+1),p=T.slice(y)}}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){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);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){let u=l.tokens.filter(p=>p.type==="space");i.loose=u.length>0&&u.some(p=>this.rules.other.anyLine.test(p.raw))}}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=Bb(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:zn(t[0],`
|
|
74
|
+
`),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=Fb(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
75
|
+
`):[],a={type:"table",raw:zn(t[0],`
|
|
76
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?a.align.push("right"):this.rules.other.tableAlignCenter.test(s)?a.align.push("center"):this.rules.other.tableAlignLeft.test(s)?a.align.push("left"):a.align.push(null);for(let s=0;s<n.length;s++)a.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:a.align[s]});for(let s of i)a.rows.push(Fb(s,a.header.length).map((c,l)=>({text:c,tokens:this.lexer.inline(c),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:zn(t[0],`
|
|
77
77
|
`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
|
|
78
|
-
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=
|
|
79
|
-
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(
|
|
78
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=zn(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=$D(t[2],"()");if(a===-2)return;if(a>-1){let s=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,s).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(r);a&&(r=a[1],i=a[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)),Ub(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 Ub(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,a,s,c=i,l=0,d=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(s=[...a].length,r[3]||r[4]){c+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+s)%3)){l+=s;continue}if(c-=s,c>0)continue;s=Math.min(s,s+c+l);let u=[...r[0]][0].length,p=e.slice(0,i+r.index+u+s);if(Math.min(i,s)%2){let f=p.slice(1,-1);return{type:"em",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}let m=p.slice(2,-2);return{type:"strong",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}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,a,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(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a||(s=[...a].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}}}},Bt=class am{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||xr,this.options.tokenizer=this.options.tokenizer||new ac,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:st,block:ic.normal,inline:Fa.normal};this.options.pedantic?(n.block=ic.pedantic,n.inline=Fa.pedantic):this.options.gfm&&(n.block=ic.gfm,this.options.breaks?n.inline=Fa.breaks:n.inline=Fa.gfm),this.tokenizer.rules=n}static get rules(){return{block:ic,inline:Fa}}static lex(t,n){return new am(n).lex(t)}static lexInline(t,n){return new am(n).inlineTokens(t)}lex(t){t=t.replace(st.carriageReturn,`
|
|
79
|
+
`),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(st.tabCharGlobal," ").replace(st.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(c=>(a=c.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let c=n.at(-1);a.raw.length===1&&c!==void 0?c.raw+=`
|
|
80
80
|
`:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let c=n.at(-1);c?.type==="paragraph"||c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
81
81
|
`)?"":`
|
|
82
82
|
`)+a.raw,c.text+=`
|
|
@@ -89,9 +89,9 @@ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
89
89
|
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a),r=s.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let c=n.at(-1);c?.type==="text"?(c.raw+=(c.raw.endsWith(`
|
|
90
90
|
`)?"":`
|
|
91
91
|
`)+a.raw,c.text+=`
|
|
92
|
-
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);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}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,i=null;if(this.tokens.links){let d=Object.keys(this.tokens.links);if(d.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)d.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)a=i[2]?i[2].length:0,r=r.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,c="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}s||(c=""),s=!1;let d;if(this.options.extensions?.inline?.some(p=>(d=p.call({lexer:this},t,n))?(t=t.substring(d.raw.length),n.push(d),!0):!1))continue;if(d=this.tokenizer.escape(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.tag(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.link(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(d.raw.length);let p=n.at(-1);d.type==="text"&&p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(d=this.tokenizer.emStrong(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.codespan(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.br(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.del(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.autolink(t)){t=t.substring(d.raw.length),n.push(d);continue}if(!this.state.inLink&&(d=this.tokenizer.url(t))){t=t.substring(d.raw.length),n.push(d);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,m=t.slice(1),f;this.options.extensions.startInline.forEach(
|
|
93
|
-
`;return r?'<pre><code class="language-'+
|
|
94
|
-
`:"<pre><code>"+(n?i:
|
|
92
|
+
`+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):n.push(a);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}inlineTokens(t,n=[]){this.tokenizer.lexer=this;let r=t,i=null;if(this.tokens.links){let d=Object.keys(this.tokens.links);if(d.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)d.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)a=i[2]?i[2].length:0,r=r.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,c="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}s||(c=""),s=!1;let d;if(this.options.extensions?.inline?.some(p=>(d=p.call({lexer:this},t,n))?(t=t.substring(d.raw.length),n.push(d),!0):!1))continue;if(d=this.tokenizer.escape(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.tag(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.link(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(d.raw.length);let p=n.at(-1);d.type==="text"&&p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(d=this.tokenizer.emStrong(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.codespan(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.br(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.del(t,r,c)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.autolink(t)){t=t.substring(d.raw.length),n.push(d);continue}if(!this.state.inLink&&(d=this.tokenizer.url(t))){t=t.substring(d.raw.length),n.push(d);continue}let u=t;if(this.options.extensions?.startInline){let p=1/0,m=t.slice(1),f;this.options.extensions.startInline.forEach(y=>{f=y.call({lexer:this},m),typeof f=="number"&&f>=0&&(p=Math.min(p,f))}),p<1/0&&p>=0&&(u=t.substring(0,p+1))}if(d=this.tokenizer.inlineText(u)){t=t.substring(d.raw.length),d.raw.slice(-1)!=="_"&&(c=d.raw.slice(-1)),s=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);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)}},oc=class{options;parser;constructor(e){this.options=e||xr}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(st.notSpaceStart)?.[0],i=e.replace(st.endingNewline,"")+`
|
|
93
|
+
`;return r?'<pre><code class="language-'+en(r)+'">'+(n?i:en(i,!0))+`</code></pre>
|
|
94
|
+
`:"<pre><code>"+(n?i:en(i,!0))+`</code></pre>
|
|
95
95
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
96
96
|
${this.parser.parse(e)}</blockquote>
|
|
97
97
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -107,8 +107,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
107
107
|
`}tablerow({text:e}){return`<tr>
|
|
108
108
|
${e}</tr>
|
|
109
109
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
110
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${
|
|
111
|
-
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+Yt(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},hr=new e0;function Re(e,t){return hr.parse(e,t)}Re.options=Re.setOptions=function(e){return hr.setOptions(e),Re.defaults=hr.defaults,Cy(Re.defaults),Re},Re.getDefaults=Dd,Re.defaults=mr,Re.use=function(...e){return hr.use(...e),Re.defaults=hr.defaults,Cy(Re.defaults),Re},Re.walkTokens=function(e,t){return hr.walkTokens(e,t)},Re.parseInline=hr.parseInline,Re.Parser=Ot,Re.parser=Ot.parse,Re.Renderer=$s,Re.TextRenderer=Gd,Re.Lexer=Mt,Re.lexer=Mt.lex,Re.Tokenizer=Ls,Re.Hooks=ba,Re.parse=Re;var nF=Re.options,rF=Re.setOptions,iF=Re.use,aF=Re.walkTokens,oF=Re.parseInline,sF=Re,cF=Ot.parse,lF=Mt.lex,t0={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 n0(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:")}Sy.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(n0(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function qd(e){const t=Re.parse(String(e||""),{async:!1});return Sy.sanitize(t,t0)}function r0(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"},qA(r)),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:qd(i)}})):null}).filter(Boolean)}function i0(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const a=r.indexOf(":"),s=r.slice(0,a).trim(),c=r.slice(a+1).trim();return!s||!c?null:y("div",{className:"summary-section",key:`${s}-${i}`},y("div",{className:"summary-section-label"},s),y("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:qd(c)}}))}).filter(Boolean);if(n.length)return y("div",{className:"feed-body facts"},n)}return y("div",{className:"feed-body"},y("ul",null,t.map((n,r)=>y("li",{key:`${n}-${r}`},n))))}function By(e,t="feed-body"){const n=String(e||"").trim();return n?y("div",{className:t,dangerouslySetInnerHTML:{__html:qd(n)}}):null}function a0(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const a=String(e?.body_text||"").trim();if(a.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(a);d;d=l.exec(a)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function Ms(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function o0(e,t){const n=String(e?.kind||"").trim().toLowerCase();return Ms(e,t)?"session_summary":n||"change"}var Hd=["Enter"," "],s0=["ArrowDown","PageUp","Home"],Uy=["ArrowUp","PageDown","End"],c0=[...s0,...Uy],l0={ltr:[...Hd,"ArrowRight"],rtl:[...Hd,"ArrowLeft"]},d0={ltr:["ArrowLeft"],rtl:["ArrowRight"]},_a="Menu",[wa,u0,p0]=Bo(_a),[gr,Gy]=st(_a,[p0,kn,Wr]),Sa=kn(),qy=Wr(),[Hy,On]=gr(_a),[m0,Ca]=gr(_a),Ky=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:s=!0}=e,c=Sa(t),[l,d]=x(null),u=G(!1),p=lt(a),m=Zi(i);return z(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),o(ra,{...c,children:o(Hy,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:o(m0,{scope:t,onClose:ce(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Ky.displayName=_a;var f0="MenuAnchor",Kd=V((e,t)=>{const{__scopeMenu:n,...r}=e,i=Sa(n);return o(ia,{...i,...r,ref:t})});Kd.displayName=f0;var Vd="MenuPortal",[h0,Vy]=gr(Vd,{forceMount:void 0}),Wy=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=On(Vd,t);return o(h0,{scope:t,forceMount:n,children:o(nt,{present:n||a.open,children:o(Xn,{asChild:!0,container:i,children:r})})})};Wy.displayName=Vd;var Nt="MenuContent",[g0,Wd]=gr(Nt),zy=V((e,t)=>{const n=Vy(Nt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=On(Nt,e.__scopeMenu),s=Ca(Nt,e.__scopeMenu);return o(wa.Provider,{scope:e.__scopeMenu,children:o(nt,{present:r||a.open,children:o(wa.Slot,{scope:e.__scopeMenu,children:s.modal?o(v0,{...i,ref:t}):o(y0,{...i,ref:t})})})})}),v0=V((e,t)=>{const n=On(Nt,e.__scopeMenu),r=G(null),i=we(t,r);return z(()=>{const a=r.current;if(a)return No(a)},[]),o(zd,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Q(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),y0=V((e,t)=>{const n=On(Nt,e.__scopeMenu);return o(zd,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),b0=Jn("MenuContent.ScrollLock"),zd=V((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,disableOutsideScroll:g,...h}=e,v=On(Nt,n),b=Ca(Nt,n),_=Sa(n),S=qy(n),C=u0(n),[N,E]=x(null),A=G(null),M=we(t,A,v.onContentChange),U=G(0),k=G(""),F=G(0),j=G(null),H=G("right"),L=G(0),R=g?Bi:Z,P=g?{as:b0,allowPinchZoom:!0}:void 0,I=O=>{const W=k.current+O,ue=C().filter(fe=>!fe.disabled),re=document.activeElement,ie=ue.find(fe=>fe.ref.current===re)?.textValue,be=R0(ue.map(fe=>fe.textValue),W,ie),Y=ue.find(fe=>fe.textValue===be)?.ref.current;(function fe(ne){k.current=ne,window.clearTimeout(U.current),ne!==""&&(U.current=window.setTimeout(()=>fe(""),1e3))})(W),Y&&setTimeout(()=>Y.focus())};z(()=>()=>window.clearTimeout(U.current),[]),vo();const D=ce(O=>H.current===j.current?.side&&L0(O,j.current?.area),[]);return o(g0,{scope:n,searchRef:k,onItemEnter:ce(O=>{D(O)&&O.preventDefault()},[D]),onItemLeave:ce(O=>{D(O)||(A.current?.focus(),E(null))},[D]),onTriggerLeave:ce(O=>{D(O)&&O.preventDefault()},[D]),pointerGraceTimerRef:F,onPointerGraceIntentChange:ce(O=>{j.current=O},[]),children:o(R,{...P,children:o(ji,{asChild:!0,trapped:i,onMountAutoFocus:Q(a,O=>{O.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:o(Yn,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:o(El,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:N,onCurrentTabStopIdChange:E,onEntryFocus:Q(l,O=>{b.isUsingKeyboardRef.current||O.preventDefault()}),preventScrollOnEntryFocus:!0,children:o(as,{role:"menu","aria-orientation":"vertical","data-state":ub(v.open),"data-radix-menu-content":"",dir:b.dir,..._,...h,ref:M,style:{outline:"none",...h.style},onKeyDown:Q(h.onKeyDown,O=>{const W=O.target.closest("[data-radix-menu-content]")===O.currentTarget,ue=O.ctrlKey||O.altKey||O.metaKey,re=O.key.length===1;W&&(O.key==="Tab"&&O.preventDefault(),!ue&&re&&I(O.key));const ie=A.current;if(O.target!==ie||!c0.includes(O.key))return;O.preventDefault();const be=C().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);Uy.includes(O.key)&&be.reverse(),A0(be)}),onBlur:Q(e.onBlur,O=>{O.currentTarget.contains(O.target)||(window.clearTimeout(U.current),k.current="")}),onPointerMove:Q(e.onPointerMove,Na(O=>{const W=O.target,ue=L.current!==O.clientX;O.currentTarget.contains(W)&&ue&&(H.current=O.clientX>L.current?"right":"left",L.current=O.clientX)}))})})})})})})});zy.displayName=Nt;var _0="MenuGroup",Jd=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{role:"group",...r,ref:t})});Jd.displayName=_0;var w0="MenuLabel",Jy=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{...r,ref:t})});Jy.displayName=w0;var Os="MenuItem",Yy="menu.itemSelect",js=V((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,a=G(null),s=Ca(Os,e.__scopeMenu),c=Wd(Os,e.__scopeMenu),l=we(t,a),d=G(!1),u=()=>{const p=a.current;if(!n&&p){const m=new CustomEvent(Yy,{bubbles:!0,cancelable:!0});p.addEventListener(Yy,f=>r?.(f),{once:!0}),Hc(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return o(Xy,{...i,ref:l,disabled:n,onClick:Q(e.onClick,u),onPointerDown:p=>{e.onPointerDown?.(p),d.current=!0},onPointerUp:Q(e.onPointerUp,p=>{d.current||p.currentTarget?.click()}),onKeyDown:Q(e.onKeyDown,p=>{const m=c.searchRef.current!=="";n||m&&p.key===" "||Hd.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});js.displayName=Os;var Xy=V((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,s=Wd(Os,n),c=qy(n),l=G(null),d=we(t,l),[u,p]=x(!1),[m,f]=x("");return z(()=>{const g=l.current;g&&f((g.textContent??"").trim())},[a.children]),o(wa.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:o(Pl,{asChild:!0,...c,focusable:!r,children:o(pe.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...a,ref:d,onPointerMove:Q(e.onPointerMove,Na(g=>{r?s.onItemLeave(g):(s.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Q(e.onPointerLeave,Na(g=>s.onItemLeave(g))),onFocus:Q(e.onFocus,()=>p(!0)),onBlur:Q(e.onBlur,()=>p(!1))})})})}),S0="MenuCheckboxItem",Qy=V((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o(rb,{scope:e.__scopeMenu,checked:n,children:o(js,{role:"menuitemcheckbox","aria-checked":Fs(n)?"mixed":n,...i,ref:t,"data-state":Qd(n),onSelect:Q(i.onSelect,()=>r?.(Fs(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Qy.displayName=S0;var Zy="MenuRadioGroup",[C0,T0]=gr(Zy,{value:void 0,onValueChange:()=>{}}),eb=V((e,t)=>{const{value:n,onValueChange:r,...i}=e,a=lt(r);return o(C0,{scope:e.__scopeMenu,value:n,onValueChange:a,children:o(Jd,{...i,ref:t})})});eb.displayName=Zy;var tb="MenuRadioItem",nb=V((e,t)=>{const{value:n,...r}=e,i=T0(tb,e.__scopeMenu),a=n===i.value;return o(rb,{scope:e.__scopeMenu,checked:a,children:o(js,{role:"menuitemradio","aria-checked":a,...r,ref:t,"data-state":Qd(a),onSelect:Q(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});nb.displayName=tb;var Yd="MenuItemIndicator",[rb,N0]=gr(Yd,{checked:!1}),ib=V((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,a=N0(Yd,n);return o(nt,{present:r||Fs(a.checked)||a.checked===!0,children:o(pe.span,{...i,ref:t,"data-state":Qd(a.checked)})})});ib.displayName=Yd;var I0="MenuSeparator",ab=V((e,t)=>{const{__scopeMenu:n,...r}=e;return o(pe.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});ab.displayName=I0;var k0="MenuArrow",ob=V((e,t)=>{const{__scopeMenu:n,...r}=e,i=Sa(n);return o(os,{...i,...r,ref:t})});ob.displayName=k0;var Xd="MenuSub",[E0,sb]=gr(Xd),P0=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=On(Xd,t),s=Sa(t),[c,l]=x(null),[d,u]=x(null),p=lt(i);return z(()=>(a.open===!1&&p(!1),()=>p(!1)),[a.open,p]),o(ra,{...s,children:o(Hy,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:o(E0,{scope:t,contentId:ct(),triggerId:ct(),trigger:c,onTriggerChange:l,children:n})})})};P0.displayName=Xd;var Ta="MenuSubTrigger",cb=V((e,t)=>{const n=On(Ta,e.__scopeMenu),r=Ca(Ta,e.__scopeMenu),i=sb(Ta,e.__scopeMenu),a=Wd(Ta,e.__scopeMenu),s=G(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=a,d={__scopeMenu:e.__scopeMenu},u=ce(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return z(()=>u,[u]),z(()=>{const p=c.current;return()=>{window.clearTimeout(p),l(null)}},[c,l]),o(Kd,{asChild:!0,...d,children:o(Xy,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":ub(n.open),...e,ref:ho(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Q(e.onPointerMove,Na(p=>{a.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(a.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:Q(e.onPointerLeave,Na(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,g=f==="right",h=g?-5:5,v=m[g?"left":"right"],b=m[g?"right":"left"];a.onPointerGraceIntentChange({area:[{x:p.clientX+h,y:p.clientY},{x:v,y:m.top},{x:b,y:m.top},{x:b,y:m.bottom},{x:v,y:m.bottom}],side:f}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(p),p.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:Q(e.onKeyDown,p=>{const m=a.searchRef.current!=="";e.disabled||m&&p.key===" "||l0[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});cb.displayName=Ta;var lb="MenuSubContent",db=V((e,t)=>{const n=Vy(Nt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=On(Nt,e.__scopeMenu),s=Ca(Nt,e.__scopeMenu),c=sb(lb,e.__scopeMenu),l=G(null),d=we(t,l);return o(wa.Provider,{scope:e.__scopeMenu,children:o(nt,{present:r||a.open,children:o(wa.Slot,{scope:e.__scopeMenu,children:o(zd,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:Q(e.onFocusOutside,u=>{u.target!==c.trigger&&a.onOpenChange(!1)}),onEscapeKeyDown:Q(e.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:Q(e.onKeyDown,u=>{const p=u.currentTarget.contains(u.target),m=d0[s.dir].includes(u.key);p&&m&&(a.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});db.displayName=lb;function ub(e){return e?"open":"closed"}function Fs(e){return e==="indeterminate"}function Qd(e){return Fs(e)?"indeterminate":e?"checked":"unchecked"}function A0(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function x0(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function R0(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=x0(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function D0(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function L0(e,t){return t?D0({x:e.clientX,y:e.clientY},t):!1}function Na(e){return t=>t.pointerType==="mouse"?e(t):void 0}var $0=Ky,M0=Kd,O0=Wy,j0=zy,F0=Jd,B0=Jy,U0=js,G0=Qy,q0=eb,H0=nb,K0=ib,V0=ab,W0=ob,z0=cb,J0=db,Bs="DropdownMenu",[Y0,dF]=st(Bs,[Gy]),pt=Gy(),[X0,pb]=Y0(Bs),mb=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:s,modal:c=!0}=e,l=pt(t),d=G(null),[u,p]=Tt({prop:i,defaultProp:a??!1,onChange:s,caller:Bs});return o(X0,{scope:t,triggerId:ct(),triggerRef:d,contentId:ct(),open:u,onOpenChange:p,onOpenToggle:ce(()=>p(m=>!m),[p]),modal:c,children:o($0,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};mb.displayName=Bs;var fb="DropdownMenuTrigger",hb=V((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=pb(fb,n),s=pt(n);return o(M0,{asChild:!0,...s,children:o(pe.button,{type:"button",id:a.triggerId,"aria-haspopup":"menu","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:ho(t,a.triggerRef),onPointerDown:Q(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(a.onOpenToggle(),a.open||c.preventDefault())}),onKeyDown:Q(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&a.onOpenToggle(),c.key==="ArrowDown"&&a.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});hb.displayName=fb;var Q0="DropdownMenuPortal",gb=e=>{const{__scopeDropdownMenu:t,...n}=e,r=pt(t);return o(O0,{...r,...n})};gb.displayName=Q0;var vb="DropdownMenuContent",yb=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pb(vb,n),a=pt(n),s=G(!1);return o(j0,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:Q(e.onCloseAutoFocus,c=>{s.current||i.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Q(e.onInteractOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;(!i.modal||u)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});yb.displayName=vb;var Z0="DropdownMenuGroup",eD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(F0,{...i,...r,ref:t})});eD.displayName=Z0;var tD="DropdownMenuLabel",nD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(B0,{...i,...r,ref:t})});nD.displayName=tD;var rD="DropdownMenuItem",bb=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(U0,{...i,...r,ref:t})});bb.displayName=rD;var iD="DropdownMenuCheckboxItem",aD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(G0,{...i,...r,ref:t})});aD.displayName=iD;var oD="DropdownMenuRadioGroup",sD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(q0,{...i,...r,ref:t})});sD.displayName=oD;var cD="DropdownMenuRadioItem",lD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(H0,{...i,...r,ref:t})});lD.displayName=cD;var dD="DropdownMenuItemIndicator",uD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(K0,{...i,...r,ref:t})});uD.displayName=dD;var pD="DropdownMenuSeparator",mD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(V0,{...i,...r,ref:t})});mD.displayName=pD;var fD="DropdownMenuArrow",hD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(W0,{...i,...r,ref:t})});hD.displayName=fD;var gD="DropdownMenuSubTrigger",vD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(z0,{...i,...r,ref:t})});vD.displayName=gD;var yD="DropdownMenuSubContent",bD=V((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=pt(n);return o(J0,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});bD.displayName=yD;var _D=mb,wD=hb,SD=gb,CD=yb,_b=bb;function TD({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return y(_D,null,y(wD,{asChild:!0},y("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),y(SD,null,y(CD,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},y(_b,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),y(_b,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function ND({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 Zd({label:e,variant:t=""}){return y(Nd,{variant:"provenance",tone:t||void 0},e)}function ID({tag:e}){const t=Kv(e);return t?y(Nd,{variant:"tag",title:String(e)},t):null}function kD({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const a=Ss(e?.metadata_json),s=Ms(e,a),c=o0(e,a),l=ft(e),d=e.title||"(untitled)",u=s&&a?.request?a.request:d,p=e.created_at||e.created_at_utc,m=BA(p),f=JA(e),g=ws(e.files||[]),h=e.project||"",v=QA(e),b=ZA(e,a),_=String(e.visibility||a?.visibility||"private").trim(),S=String(e.workspace_kind||a?.workspace_kind||"").trim(),C=String(e.origin_source||a?.origin_source||"").trim(),N=String(e.trust_state||a?.trust_state||"").trim(),E=f.length?` · ${f.map(ve=>Kv(ve)).join(", ")}`:"",A=g.length?` · ${HA(g)}`:"",M=Number(e.id||0),U=M>0?`ID ${M}`:"",[k,F]=x(w.newItemKeys.has(l)),j=s?a0({...e,metadata_json:a}):null,H=s?null:Px({...e,metadata_json:a}),L=H?Ax(H):[],R=H?xx(H):"summary",P=w.itemViewState.get(l),[I,D]=x(H&&P&&L.some(ve=>ve.id===P)?P:R),O=`${l}:${I}`,[W,ue]=x(w.itemExpandState.get(O)===!0),[re,ie]=x(_==="shared"?"shared":"private"),[be,Y]=x(!1),[fe,ne]=x(!1),[Pe,ge]=x(!1),ae=j?r0(j):[];z(()=>{H&&(L.some(ve=>ve.id===I)||D(R))},[I,R,L,H]),z(()=>{w.itemViewState.set(l,I)},[I,l]),z(()=>{const ve=`${l}:${I}`;ue(w.itemExpandState.get(ve)===!0)},[I,l]),z(()=>{ie(_==="shared"?"shared":"private")},[_]),z(()=>{if(!k)return;const ve=window.setTimeout(()=>{w.newItemKeys.delete(l),F(!1)},700);return()=>window.clearTimeout(ve)},[k,l]);const Ee=re,le=Ee==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",Te=[h?`Project ${h}`:"No project",m].filter(Boolean).join(" · "),B=[S&&S!==_?`Workspace ${S}`:"",C?`From ${C}`:"",b,N&&N!=="trusted"?XA(N):""].filter(Boolean).join(" · "),oe=[`${E}${A}`.trim(),B].filter(Boolean).join(" · "),K=!!H&&Rx(I,H),J=[I==="facts"?"feed-body facts":"feed-body",K&&!W?Dx(I).join(" "):""].filter(Boolean).join(" "),Oe=s?ae.length?y("div",{className:"feed-body facts"},ae):By(String(e.body_text||""))||y("div",{className:"feed-body"}):H?I==="facts"?i0(H.facts)||y("div",{className:J}):By(I==="narrative"?H.narrative:H.summary,J)||y("div",{className:J}):y("div",{className:"feed-body"});async function Ae(ve){const gt=Ee;ie(ve),Y(!0);try{const St=await zw(M,ve);St?.item&&(t(St.item),r()),se(ve==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(St){ie(gt),se(St instanceof Error?St.message:"Failed to save visibility.","warning")}finally{Y(!1)}}async function At(){const ve=String(e.project||"").trim(),gt=ve,St=String(u||"this memory").trim(),Ni=St.length>80?`${St.slice(0,79).trimEnd()}…`:St,Ja=ve?`Move "${Ni}" from "${ve}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${Ni}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let vn=[];try{vn=(await Za()).filter(vt=>vt&&vt!==ve)}catch{}const Er=await ud({title:"Assign to project",description:Ja,initialValue:gt,placeholder:"Pick one or type a new project name",suggestions:vn,confirmLabel:"Move",cancelLabel:"Cancel",validate:vt=>{const Kn=vt.trim();return Kn?Kn===ve?"Already assigned to this project.":null:"Enter a project name."}});if(Er==null)return;const Hn=Er.trim();if(!(!Hn||Hn===ve)){ge(!0);try{const vt=await Jw(M,Hn),Kn=Number(vt.moved_memory_count||1);se(Kn>1?`Moved ${Kn} memories from this session to "${vt.project}".`:`Moved to "${vt.project}".`),await i(),r()}catch(vt){se(vt instanceof Error?vt.message:"Failed to move memory.","warning")}finally{ge(!1)}}}async function hn(){const ve=String(u||"this memory").trim();if(await Wt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${ve.length>80?`${ve.slice(0,79).trimEnd()}…`:ve}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){ne(!0);try{await Yw(M),n(M),r(),await i(),se("Memory forgotten and removed from the active feed.")}catch(gt){se(gt instanceof Error?gt.message:"Failed to forget memory.","warning")}finally{ne(!1)}}}const ht=c.replace(/_/g," "),gn=g.length?y("div",{className:"feed-files"},g.map((ve,gt)=>y("span",{className:"feed-file",key:`${String(ve)}-${gt}`},String(ve)))):null;return y("article",{className:`feed-item ${c}${k?" new-item":""}`.trim(),"data-key":l},y("div",{className:"feed-kind-banner"},y(Nd,{variant:"kind",tone:c},ht)),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:CI(u,w.feedQuery)}}),y("div",{className:"feed-card-subtitle small"},Te)),y("div",{className:"feed-actions"},H?y(ND,{active:I,modes:L,onSelect:ve=>D(ve)}):null,y(ks,{label:FA(p),side:"left"},y("div",{className:"small feed-age"},m)),e.owned_by_self&&M>0?y(TD,{assignProjectDisabled:Pe,disabled:fe,onAssignProject:()=>{At()},onForget:()=>{hn()},title:String(u||"memory")}):null)),y("div",{className:"feed-provenance"},y(Zd,{label:v,variant:v==="You"?"mine":"author"}),y(Zd,{label:_||"private",variant:_||"private"}),U?y(ks,{label:`Memory database id ${M}`,side:"top"},y(Zd,{label:U,variant:"memory-id"})):null),y("div",{className:"feed-meta"},oe||"No tags, files, or provenance details attached."),Oe,y("div",{className:"feed-footer"},y("div",{className:"feed-footer-left"},f.length?y("div",{className:"feed-tags"},f.map((ve,gt)=>y(ID,{key:`${String(ve)}-${gt}`,tag:ve}))):null,e.owned_by_self&&M>0?y("div",{className:"feed-visibility-controls"},y("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:be,onChange:ve=>{Ae(String(ve.currentTarget.value)==="shared"?"shared":"private")},value:Ee},y("option",{value:"private"},"Only me"),y("option",{value:"shared"},"Share with peers")),y("div",{className:"feed-visibility-note"},le)):null),y("div",{className:"feed-footer-right"},K?y("button",{className:"feed-expand",onClick:()=>{const ve=!W;w.itemExpandState.set(O,ve),ue(ve)},type:"button"},W?"Collapse":"Expand"):null)),gn))}function ED({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 PD({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(ED,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!w.feedQuery.trim()||w.feedTypeFilter!=="all"||w.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(kD,{item:r,key:ft(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function wb({id:e,active:t,options:n,onSelect:r}){return y("div",{className:"feed-toggle",id:e},n.map(({value:i,label:a})=>{const s=i===t;return y("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},a)}))}function AD({text:e}){return y("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function xD({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 RD({errorText:e,items:t,loadingText:n,ops:r}){const[i,a]=x(!1);return y(Z,null,y("div",{className:"feed-controls"},y(AD,{text:n||Lx(t.length,r.hasMorePages())}),y("div",{className:"feed-controls-right"},y(xD,{query:w.feedQuery,onQuery:r.updateFeedQuery}),y(wb,{active:w.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==w.feedScopeFilter&&(Ih(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),y(wb,{active:w.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==w.feedTypeFilter&&(MI(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),y("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>a(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),y($x,{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(PD,{items:t,loadingText:n,ops:r}):null)))}function DD(e){return w.feedTypeFilter==="observations"?e.filter(t=>!Ms(t,Ss(t?.metadata_json))):w.feedTypeFilter==="summaries"?e.filter(t=>Ms(t,Ss(t?.metadata_json))):e}function LD(e){const t=e.map(n=>`${zv(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${w.feedTypeFilter}|${w.feedScopeFilter}|${w.currentProject}|${da(w.feedQuery)}|${t.join("|")}`}var Sb="",Ia=0,ka=0,di=!0,ui=!0,Us=null,$D=0,It=null,Cb=!1,pi=0,eu="all",Tb="",Ea=null,mi="",uF=250;function Nb(e){Sb=e,eu=w.feedScopeFilter,Tb=w.feedQuery.trim(),mi="",pi+=1,Ia=0,ka=0,di=!0,ui=!0,w.lastFeedItems=[],w.pendingFeedItems=null,w.lastFeedFilteredCount=0,w.lastFeedSignature="",w.newItemKeys.clear(),w.itemViewState.clear(),w.itemExpandState.clear()}function tu(){return di||ui}function MD(e){const t=ft(e);w.lastFeedItems=w.lastFeedItems.map(n=>ft(n)===t?e:n)}function OD(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(ft(r)),i};w.lastFeedItems=w.lastFeedItems.filter(n),Array.isArray(w.pendingFeedItems)&&(w.pendingFeedItems=w.pendingFeedItems.filter(n));for(const r of t){w.newItemKeys.delete(r),w.itemViewState.delete(r);for(const i of Array.from(w.itemExpandState.keys()))i.startsWith(`${r}:`)&&w.itemExpandState.delete(i)}}async function jD(){if(!tu())return;const e=pi;if(Us===e)return;const t=w.currentProject||"",n=w.feedQuery.trim(),r=Ia,i=ka;Us=e;try{const[a,s]=await Promise.all([di?Sp(t,{limit:20,offset:r,scope:w.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),ui?Cp(t,{limit:50,offset:i,scope:w.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==pi||t!==(w.currentProject||"")||n!==w.feedQuery.trim())return;const c=s.items||[],l=a.items||[],d=n?l:l.filter(p=>!Wv(p));w.lastFeedFilteredCount+=l.length-d.length,ui=Cs(s,c.length,50),di=Cs(a,l.length,20),ka=Ts(s,i+c.length),Ia=Ts(a,r+l.length);const u=[...c,...d];w.lastFeedItems=Jv(w.lastFeedItems,u),vr()}finally{Us===e&&(Us=null)}}function Ib(){w.activeTab==="feed"&&(Ea||It||tu()&&tx()&&jD())}var FD={replaceFeedItem:MD,removeFeedItem:OD,updateFeedView:e=>vr(e),loadFeedData:()=>iu(),updateFeedQuery:e=>UD(e),hasMorePages:tu};function nu(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;Ix(n,y(RD,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:FD}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function ru(e="Loading selected project..."){nu([],{loadingText:e})}function BD(){Nx(),nu(w.lastFeedItems,w.lastFeedItems.length||w.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),Cb||(window.addEventListener("scroll",()=>{Ib()},{passive:!0}),Cb=!0)}function UD(e){if(e===w.feedQuery)return;const t=w.feedQuery.trim();w.feedQuery=e,e.trim()!==t&&(Nb(w.currentProject||""),ru("Searching memories…"),Ea&&clearTimeout(Ea),Ea=setTimeout(()=>{Ea=null,iu().catch(()=>{})},250))}function vr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=DD(w.lastFeedItems),r=LD(n),i=e||r!==w.lastFeedSignature;w.lastFeedSignature=r,i&&nu(n,{errorText:mi||void 0}),window.scrollTo({top:t}),Ib()}async function iu(){const e=w.currentProject||"",t=w.feedScopeFilter!==eu,n=w.feedQuery.trim(),r=n!==Tb;(e!==Sb||t||r)&&(Nb(e),ru(r?"Searching memories…":void 0));const i=pi,a=++$D;It={generation:i,requestId:a};const s=!!mi;s&&(mi="",w.lastFeedItems.length>0?vr(!0):ru(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([Sp(e,{limit:20,offset:0,scope:w.feedScopeFilter,q:n||void 0}),Cp(e,{limit:50,offset:0,scope:w.feedScopeFilter,q:n||void 0})]);if(It?.generation!==i||It.requestId!==a||i!==pi||e!==(w.currentProject||"")||n!==w.feedQuery.trim())return;const p=u.items||[],m=d.items||[],f=n?m:m.filter(_=>!Wv(_)),g=m.length-f.length,h=[...p,...f].sort((_,S)=>new Date(S.created_at||0).getTime()-new Date(_.created_at||0).getTime()),v=ex(w.lastFeedItems,h),b=w.lastFeedItems;if(nx(v,b)&&b.length>0){const _=new Set(b.map(ft));v.forEach(S=>{_.has(ft(S))||w.newItemKeys.add(ft(S))})}w.pendingFeedItems=null,w.lastFeedItems=v,mi="",w.lastFeedFilteredCount=Math.max(w.lastFeedFilteredCount,g),ui=Cs(u,p.length,50),di=Cs(d,m.length,20),ka=Math.max(ka,Ts(u,p.length)),Ia=Math.max(Ia,Ts(d,m.length)),eu=w.feedScopeFilter,It?.generation===i&&It.requestId===a&&(It=null),vr(s)}catch(c){throw It?.generation===i&&It.requestId===a&&i===pi&&e===(w.currentProject||"")&&n===w.feedQuery.trim()&&(di=!1,ui=!1,mi="Feed unavailable. Refresh and try again.",vr(!0)),c}finally{It?.generation===i&&It.requestId===a&&(It=null)}}var GD=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function kb(e){return!!GD.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function pF(e){return e}function qD(e){return e.latest_version?e.stale?{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:kb(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function HD({status:e}){const t=qD(e),n=e.update_available||e.stale||!e.latest_version||!kb(e.current_version);return y("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},y("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),y("div",{class:"health-update-copy"},y("h2",null,t.title),y("p",null,t.detail),n&&e.recommended_action?y("p",{class:"health-update-guidance"},y("span",{class:"health-update-guidance-label"},"Recommended action"),y("code",null,e.recommended_action)):null))}function KD(e,t){e&&(e.hidden=!t,Ge(t?y(HD,{status:t}):null,e))}function VD({label:e,value:t,detail:n,icon:r,className:i,title:a}){const s=y("div",{class:`stat${i?` ${i}`:""}`,style:a?"cursor: help;":void 0},r?y("i",{"data-lucide":r,class:"stat-icon"}):null,y("div",{class:"stat-content"},y("div",{class:"value"},t),y("div",{class:"label"},e),n?y("div",{class:"small"},n):null));return a?y(ks,{label:a},s):s}function WD({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action()}catch{}t.disabled=!1,t.textContent=r}}function a(){!e.command||!n||Yi(e.command,n)}return y("div",{class:"health-action"},y("div",{class:"health-action-text"},e.label,e.command?y("span",{class:"health-action-command"},e.command):null),y("div",{class:"health-action-buttons"},e.action?y("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?y("button",{class:"settings-button health-action-copy",onClick:a,ref:s=>{n=s}},"Copy"):null))}function zD(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function JD({label:e,value:t,icon:n,tooltip:r}){const i=y("div",{class:"stat",style:r?"cursor: help;":void 0},y("i",{"data-lucide":n,class:"stat-icon"}),y("div",{class:"stat-content"},y("div",{class:"value"},zD(t)),y("div",{class:"label"},e)));return r?y(ks,{label:r},i):i}function Eb(e,t){e&&Ge(y(Cd,null,t.map(n=>y(JD,{...n,key:`${n.label}-${n.icon}`}))),e)}function Pb(e,t){e&&Ge(y(Z,null,t),e)}function au(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function YD(e,t){e&&Ge(y(Cd,null,t.map(n=>y(VD,{...n,key:n.key??n.label}))),e)}function XD(e,t){if(e){if(!t.length){e.hidden=!0,Ge(null,e);return}e.hidden=!1,Ge(y(Z,null,t.slice(0,3).map((n,r)=>y(WD,{item:n,key:`${n.label}-${r}`}))),e)}}var Ab="scope_id_backfill";function xb(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;KD(document.getElementById("healthUpdateBanner"),w.lastUpdateStatus);const i=w.lastStatsPayload||{},a=w.lastUsagePayload||{},s=w.lastRawEventsPayload&&typeof w.lastRawEventsPayload=="object"?w.lastRawEventsPayload:{},c=w.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(B=>B.kind===Ab),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},g=a.totals_filtered||a.totals||a.totals_global||i.usage?.totals||{},h=Array.isArray(a.recent_packs)?a.recent_packs:[],v=h.length?h[0]?.created_at:null,b=h.length?h[0]?.metadata_json||{}:{},_=Number(b?.exact_duplicates_collapsed||0),S=Number(s.pending||0),C=Number(p.errored_batches||0),N=Number(m.flush_success_rate??1),E=Number(m.dropped_event_rate||0),A=yd(g.tokens_saved,g.tokens_read),M=GA(A),U=Number(f.tags_coverage||0),k=String(c.daemon_state||"unknown"),F=k==="offline-peers"?"Offline peers":k==="needs_attention"?"Needs attention":k==="rebootstrapping"?"Rebootstrapping":Hv(k),j=Array.isArray(w.lastSyncPeers)?w.lastSyncPeers.length:0,H=k==="disabled"||c.enabled===!1,L=k==="offline-peers",R=!H&&j===0;let P=H?"Disabled":R?"No peers":F;const I=ii(c.last_sync_at||c.last_sync_at_utc||null),D=ii(v),O=I!==null&&I>7200,W=I!==null&&I<=300,ue=S>=200;let re=0;const ie=[];S>=1e3?(re+=40,ie.push("high raw-event backlog")):S>=200&&(re+=24,ie.push("growing raw-event backlog")),C>0&&S>=200&&(re+=C>=5?10:6,ie.push("batch errors during backlog pressure")),N<.95&&(re+=20,ie.push("lower flush success")),E>.02?(re+=24,ie.push("high dropped-event rate")):E>.005&&(re+=10,ie.push("non-trivial dropped-event rate")),!H&&!R&&(k==="error"?(re+=36,ie.push("sync daemon reports errors")):k==="needs_attention"?(re+=40,ie.push("sync needs manual attention")):k==="stopped"?(re+=22,ie.push("sync daemon stopped")):k==="degraded"&&!W&&(re+=20,ie.push("sync daemon degraded")),L?(re+=4,ie.push("all peers currently offline"),O&&(re+=4,ie.push("offline peers and sync not recent"))):O?(re+=26,ie.push("sync looks stale")):I!==null&&I>1800&&(re+=12,ie.push("sync not recent"))),M!==null&&M<10&&(re+=8,ie.push("low retrieval reduction")),D!==null&&D>86400&&(re+=12,ie.push("memory pack activity is old"));let be="Healthy",Y="status-healthy";re>=60?(be="Attention",Y="status-attention"):re>=25&&(be="Degraded",Y="status-degraded");const fe=Y==="status-healthy";r&&(r.className=`health-dot ${Y}`,r.title=be);const ne=`${Number(g.tokens_saved||0).toLocaleString()} saved tokens · ${_.toLocaleString()} deduped in latest pack`,Pe=S>0?"Queue is actively draining":"Queue is clear",ge=H?"Sync disabled":R?"No peers configured":L?`${j} peers offline · last sync ${Dn(I)} ago`:`${j} peers · last sync ${Dn(I)} ago`;fe&&!H&&!R&&(L?P="Peers offline":k==="degraded"&&W&&(P="Syncing"));const ae=`last pack ${Dn(D)} ago`,Ee=l.map(B=>{const oe=Number(B.progress?.current||0),K=typeof B.progress?.total=="number"?B.progress.total:null,J=String(B.progress?.unit||"items"),Oe=K&&K>0?` (${Math.round(100*oe/K)}%)`:"",Ae=K&&K>0?`${oe.toLocaleString()}/${K.toLocaleString()} ${J}${Oe}`:`${oe.toLocaleString()} ${J}`,At=B.status==="failed",hn=B.status==="completed",ht=B.kind===Ab,gn=At?"Failed":hn?"Complete":Ae,ve=At?String(B.error||"unknown error").trim():hn?ht?`${Ae} · one-time Sharing-domain upgrade finished`:Ae:ht?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(B.kind||B.title||"background-maintenance"),label:String(B.title||B.kind||"Background maintenance"),value:gn,detail:ve,icon:At?"alert-triangle":hn?"check-circle":"loader",className:At?"status-attention":void 0,title:At?`Error: ${B.error||"unknown"}`:hn?`${String(B.title||"Maintenance")} finished`:ht?`${String(B.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(B.title||"Maintenance")} in progress`}});YD(e,[{key:"overall-health",label:"Overall health",value:be,detail:`Weighted score ${re}`,icon:"heart-pulse",className:`health-primary ${Y}`,title:ie.length?`Main signals: ${ie.join(", ")}`:"No major risk signals detected"},...Ee,{key:"pipeline-health",label:"Pipeline health",value:`${S.toLocaleString()} pending`,detail:Pe,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:A,detail:ne,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:P,detail:ge,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:Dn(D),detail:ae,icon:"clock-3",title:"Recency of last memory pack activity"}]);const le=async()=>{await Sc()},Te=[];ue?(Te.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),Te.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):k==="stopped"?Te.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!H&&!R&&!fe&&(k==="error"||k==="degraded")?(Te.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:le,actionLabel:"Sync now"}),Te.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!H&&!R&&O&&Te.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:le,actionLabel:"Sync now"}),U>0&&U<.7&&Te.length<2&&Te.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&Te.length<3&&Te.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),XD(n,Te),t.textContent=ie.length?`Why this status: ${ie.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",au()}function QD(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=w.lastUsagePayload||{},r=w.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,a=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(N=>N.event==="pack")||null,c=Array.isArray(n?.recent_packs)?n.recent_packs:[],l=c.length?c[0]:null,d=l?.metadata_json||{},u=l?.created_at||"",p=Number(s?.count||0),m=Number(l?.tokens_read||0),f=Number(l?.tokens_saved||0),g=Number(d?.exact_duplicates_collapsed||0),h=!!d?.exact_dedupe_enabled,v=yd(f,m),b=p?`${p} packs`:"No packs yet",_=u?`Last pack: ${ur(u)}`:"",S=a?"Project":"All projects",C=[{label:"Last pack savings",value:l?`${la(f)} (${v})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?la(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?g.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:l?h?"On":"Off":"n/a",icon:"shield-check"},{label:"Packs",value:p||0,icon:"archive"}];Pb(t,[S,b,_].filter(Boolean).join(" · ")),Eb(e,C),au()}function ZD(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=w.lastStatsPayload||{},r=w.lastUsagePayload||{},i=w.lastRawEventsPayload&&typeof w.lastRawEventsPayload=="object"?w.lastRawEventsPayload:{},a=n.database||{},s=w.currentProject,c=r?.totals_global||r?.totals||n.usage?.totals||{},l=r?.totals_filtered||null,d=!!(s&&l),u=d?l:c,p=Number(i.sessions||0),m=Number(i.pending||0),f=d?`
|
|
112
|
-
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",
|
|
113
|
-
Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",
|
|
114
|
-
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",v=[{label:d?"Savings (project)":"Savings",value:la(u.tokens_saved||0),tooltip:`Tokens saved by reusing compressed memories. Exact: ${Number(u.tokens_saved||0).toLocaleString()} saved${h}`,icon:"trending-up"},{label:d?"Injected (project)":"Injected",value:la(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${g}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:yd(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${UA(u.tokens_saved,u.tokens_read)}.`+g+h,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:la(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${f}`,icon:"pencil"},{label:"Active memories",value:a.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:qv(a.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:qv(a.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?v.push({label:"Raw events pending",value:m,tooltip:"Pending raw events waiting to be flushed",icon:"activity"}):p>0&&v.push({label:"Raw sessions",value:p,tooltip:"Sessions with pending raw events",icon:"inbox"}),Eb(e,v),t){const b=s?` · project: ${s}`:"";Pb(t,`DB: ${KA(a.path||"unknown")} · ${VA(a.size_bytes||0)}${b}`)}au()}async function eL(){const e=w.lastStatsPayload?.identity?.actor_id||null,t=w.activeTab==="health"&&!w.lastUpdateStatus?KS().catch(VS):Promise.resolve(w.lastUpdateStatus),[n,r,i,a,s]=await Promise.all([eS(),tS(w.currentProject),nS(w.currentProject),rS(w.currentProject),t]);w.lastStatsPayload=n||{},w.lastUsagePayload=r||{},w.lastRawEventsPayload=a||{},w.lastUpdateStatus=s;const c=w.lastStatsPayload?.identity?.actor_id||null;ZD(),QD(),xb(),w.activeTab==="feed"&&e!==c&&vr(!0)}var tL={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function Rb(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function nL(e){return e.targetIdentityRef??e.existingIdentityRef??""}function rL({blocked:e,blockedDescriptionId:t,busy:n,detail:r,device:i,index:a,onAssign:s,onClear:c,onDecision:l}){const d=`legacy-team-device-identity-${a}`,u=`legacy-team-device-evidence-${a}`,p=`legacy-team-device-assignment-help-${a}`,m=nL(i),f=i.targetIdentityRef??"",[g,h]=x(m);z(()=>h(m),[m]);const v=r.identityChoices.some(L=>L.identityRef===g),b=Rb(r,i.existingIdentityRef),_=Rb(r,i.suggestedIdentityRef),S=e||n,C=S||!i.enabled,N=i.expectation.kind==="existing"&&i.verifiedEvidenceKind!=="active_assignment",E=!!g&&!v,A=N||E||!f||g!==f,M=S||A,U=C||!g||N||E||g===f,k=!i.enabled||A,F=e?t:void 0,j=[u,k?p:void 0,F].filter(Boolean).join(" "),H=[u,F].filter(Boolean).join(" ");return o("fieldset",{"aria-busy":n?"true":"false",className:"legacy-team-device-row",id:`legacy-team-device-row-${a}`,tabIndex:i.decision==="unresolved"?-1:void 0,children:[o("legend",{children:i.displayName}),o("div",{className:"small legacy-team-device-evidence",id:u,children:[o("span",{children:i.enabled?"Current Team device":"Device no longer active on this Team"}),b?o("span",{children:["Current assignment: ",b,i.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!b&&_?o("span",{children:["Suggested person: ",_]}):null,o("span",{children:["Decision: ",tL[i.decision]]})]}),o("label",{htmlFor:d,children:"Person using this device"}),o("select",{"aria-describedby":j,className:"feed-search legacy-team-device-select",disabled:C,id:d,onChange:L=>h(L.currentTarget.value),value:g,children:[o("option",{value:"",children:"Choose a person"}),g&&!v?o("option",{value:g,children:"Current server assignment"}):null,r.identityChoices.map(L=>o("option",{value:L.identityRef,children:L.displayName},L.identityRef))]}),i.enabled?E?o("p",{className:"small",id:p,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):N?o("p",{className:"small",id:p,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!g||!f||g!==f?o("p",{className:"small",id:p,children:g?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:o("p",{className:"small",id:p,children:"Inactive devices can only be removed from this Team."}),o("div",{className:"legacy-team-device-actions",children:[o("button",{"aria-describedby":j,"aria-disabled":U?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{U||s(i,g)},type:"button",children:"Save assignment"}),i.enabled?o(Z,{children:[o("button",{"aria-describedby":j,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{M||l(i,"included",f)},type:"button",children:"Include"}),o("button",{"aria-describedby":H,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||l(i,"excluded")},type:"button",children:"Exclude"})]}):o("button",{"aria-describedby":H,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||l(i,"removed")},type:"button",children:"Remove"}),i.decision!=="unresolved"?o("button",{"aria-describedby":H,"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{S||c(i)},type:"button",children:"Clear decision"}):null]})]})}function iL(e){return o("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[o("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),o("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),o("div",{className:"legacy-team-device-list",children:e.detail.devices.map((t,n)=>y(rL,{...e,busy:e.busyDeviceRef===t.deviceRef,device:t,index:n,key:t.deviceRef}))})]})}function aL(e){return e.resolvedProjectRef?e.mappingChoices.find(t=>t.resolvedProjectRef===e.resolvedProjectRef)?.displayName??"Unavailable Project":null}function oL({blocked:e,blockedDescriptionId:t,busy:n,index:r,onMap:i,project:a}){const s=Dr(),c=`${s}-mapping`,l=`${s}-help`,d=a.resolvedProjectRef??"",u=a.mappingChoices.some(_=>_.resolvedProjectRef===d)?d:"",p=JSON.stringify(a.mappingChoices.map(_=>_.resolvedProjectRef)),[m,f]=x(u);z(()=>f(u),[u,p]);const g=e||n,h=g||!m||m===d,v=aL(a),b=[m?void 0:l,e?t:void 0].filter(Boolean).join(" ");return o("fieldset",{"aria-busy":n?"true":"false",className:"legacy-team-project-row",id:`legacy-team-project-row-${r}`,tabIndex:a.resolution==="unresolved"?-1:void 0,children:[o("legend",{children:a.displayName}),a.resolution==="deterministic"?o("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):o(Z,{children:[o("p",{className:"small",children:v?`Saved mapping: ${v}`:"This Project still needs a mapping."}),o("label",{htmlFor:c,children:"Canonical Project"}),o("select",{"aria-describedby":b||void 0,className:"feed-search legacy-team-project-select",disabled:g,id:c,onChange:_=>f(_.currentTarget.value),value:m,children:[o("option",{value:"",children:"Choose a Project"}),a.mappingChoices.map(_=>o("option",{value:_.resolvedProjectRef,children:_.displayName},_.resolvedProjectRef))]}),m?null:o("p",{className:"small",id:l,children:"Choose and save one of the server-provided Project mappings."}),o("button",{"aria-describedby":b||void 0,"aria-disabled":h?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{h||i(a,m)},type:"button",children:"Save mapping"})]})]})}function sL(e){return o("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[o("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),o("p",{children:[e.detail.unresolvedProjectCount.toLocaleString()," of"," ",e.detail.candidate.projectCount.toLocaleString()," Team Projects still need a mapping."]}),o("div",{className:"legacy-team-project-list",children:e.detail.projects.map((t,n)=>o(oL,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,busy:e.busyProjectRef===t.projectRef,index:n,onMap:e.onMap,project:t},t.projectRef))})]})}var Pa={add:"Add",update:"Update",remove:"Remove"};function Aa({empty:e,items:t,title:n}){return o("section",{children:[o("h4",{children:n}),t.length>0?o("ul",{children:t.map((r,i)=>o("li",{children:r},`${n}-${i}`))}):o("p",{className:"small",children:e})]})}function cL({blocked:e,blockedDescriptionId:t,detail:n,onFinish:r}){const i=n.accessDelta,a=`${n.attemptId}:${n.finishDigest}:${n.accessDeltaDigest}:${n.viewerAccessDeltaDigest}`,[s,c]=x(null),l=s===a,d=e||!l,u=[l?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),p=i.teamChanges.map(b=>{const _=b.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":b.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Pa[b.change]} ${b.teamDisplayName}: change device access from ${_} to the reviewed device list.`}),m=i.membershipChanges.map(b=>`${Pa[b.change]} ${b.identityDisplayName} ${b.change==="remove"?"from":"to"} ${b.teamDisplayName}.`),f=i.projectChanges.map(b=>`${Pa[b.change]} ${b.projectDisplayName}: ${b.fromResolvedProjectDisplayName??"no Project"} to ${b.toResolvedProjectDisplayName??"no Project"}.`),g=i.recipientChanges.map(b=>`${Pa[b.change]} ${b.recipientDisplayName} ${b.change==="remove"?"from":"as"} a recipient for ${b.canonicalProjectDisplayName}.`),h=i.deviceAccessChanges.map(b=>`${Pa[b.change]} ${b.deviceDisplayName} access ${b.change==="remove"?"from":"to"} ${b.canonicalProjectDisplayName}.`),v=p.length+m.length+f.length+g.length+h.length;return o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:"Review every server-confirmed access change before activating this Team."}),o("p",{className:"small",children:[v," access ",v===1?"change":"changes"," to review."]}),o("div",{className:"legacy-team-setup-delta",children:[o(Aa,{empty:"No Team policy changes.",items:p,title:"Team policy"}),o(Aa,{empty:"No membership changes.",items:m,title:"Memberships"}),o(Aa,{empty:"No Project mapping changes.",items:f,title:"Projects"}),o(Aa,{empty:"No recipient changes.",items:g,title:"Recipients"}),o(Aa,{empty:"No device access changes.",items:h,title:"Device access"})]}),o("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[o("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:l,onChange:b=>{e||c(b.currentTarget.checked?a:null)},type:"checkbox"}),o("span",{children:"I reviewed every access change above and approve activating this Team."})]}),o("button",{"aria-describedby":u||void 0,"aria-disabled":d?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{d||r(n)},type:"button",children:"Finish Team setup"})]})}var yr="Team setup changed since it was last reviewed. Reload the latest details to continue.",lL="The change was saved, but the latest Team setup details could not be loaded. Reload before continuing.",fi=new Set(["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"]),dL={clearDecision:yS,finish:wS,loadDetail:hS,onCompleted:()=>{},refreshCandidate:_S,saveAssignment:gS,saveDecision:vS,saveProjectMapping:bS},Gs=null,xa=null,qs=null;function Db(e){return e?(qs=document.activeElement instanceof HTMLElement?document.activeElement:null,xa?xa(e):Gs=e,!0):!1}function uL(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 Lb(e){return e.draftState==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":e.unresolvedProjectCount>0?"projects":"review"}function Ra(e){return e.draftState==="completed"?!1:e.draftState==="stale"||!e.canFinish&&e.conflictState!==null&&fi.has(e.conflictState)}function pL(e){return ou(e)?yr:"Team setup details are temporarily unavailable. Retry to load the latest details."}function ou(e){return e instanceof Bt&&fi.has(e.errorCode)}function Hs(e){return ou(e)?yr:e instanceof Bt&&e.errorCode==="team_setup_roster_unavailable"?"Team device details are temporarily unavailable. Reload the latest details before trying again.":"This device change could not be saved. Reload the latest details before trying again."}function mL(e){return e instanceof Bt&&fi.has(e.errorCode)?yr:"This Project mapping could not be saved. Reload the latest details before trying again."}function fL(e){return e instanceof Bt&&fi.has(e.errorCode)?yr:"Team setup could not be refreshed. Retry to load the latest server details."}function hL(e){return e instanceof Bt&&fi.has(e.errorCode)?yr:"Team setup could not be finished. Reload the latest details before trying again."}function gL({detail:e,step:t}){return t==="completed"?o("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[o("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),o("p",{children:"This Team is ready for Project sharing."})]}):t==="devices"||t==="projects"?null:o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for current server confirmation evidence."}),o("p",{className:"small",children:"Next setup action: confirm the server-provided access review before finishing."})]})}function vL({dependencies:e}){const[t,n]=x(null),[r,i]=x(null),[a,s]=x("devices"),[c,l]=x(!1),[d,u]=x(null),[p,m]=x(0),[f,g]=x(null),[h,v]=x(null),[b,_]=x(""),[S,C]=x(!1),N=G(!1),E=G(null),A=G(!1),M=G(!1),U=G(!1),k=G(!1),F=G(0),j=G(null),H=B=>{const oe=j.current;if(oe?.attemptId===B&&oe.candidateRef===t)return oe.promise;const K=Promise.resolve().then(()=>e.onCompleted()),J=()=>{j.current?.promise===Oe&&(j.current=null)},Oe=K.then(J,Ae=>{throw J(),Ae});return j.current={attemptId:B,candidateRef:t,promise:Oe},Oe},L=(B,oe)=>{_("Team setup complete. Sharing and Projects are refreshing."),H(B).then(()=>{F.current===oe&&_("Team setup complete. Sharing and Projects are up to date.")},()=>{F.current===oe&&_("Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control.")})};if(z(()=>{if(xa=B=>{if(k.current){_("Wait for the current Team setup change to finish before opening another Team.");return}F.current+=1,M.current=!1,U.current=!1,n(B),i(null),u(null),_(""),m(oe=>oe+1)},Gs){const B=Gs;Gs=null,xa(B)}return()=>{xa=null}},[]),z(()=>{if(!t)return;let B=!0;const oe=M.current;return M.current=!1,l(!0),(oe?e.refreshCandidate(t).then(()=>e.loadDetail(t)):e.loadDetail(t)).then(K=>{B&&(U.current=Ra(K),i(K),s(Lb(K)),u(Ra(K)?yr:null),l(!1),K.draftState==="completed"&&L(K.attemptId,F.current))},K=>{B&&(U.current=oe||ou(K),u(pL(K)),l(!1))}),()=>{B=!1}},[t,e,p]),z(()=>{if(E.current){const B=E.current;E.current=null,A.current=!1,document.getElementById(B)?.focus();return}A.current&&(A.current=!1,document.getElementById(`legacy-team-setup-step-${a}`)?.focus())},[a]),z(()=>{if(!(c||!N.current)){if(N.current=!1,d){(document.getElementById("legacy-team-setup-retry")??document.getElementById("legacy-team-setup-refresh"))?.focus();return}document.getElementById(`legacy-team-setup-step-${a}`)?.focus()}},[d,c,a]),!t)return null;const R=r?`Set up ${r.candidate.displayName}`:"Set up Team",P=()=>{if(k.current){_("Team setup will stay open while this change saves. Close it after saving finishes.");return}N.current=!1,E.current=null,A.current=!1,M.current=!1,U.current=!1,F.current+=1,n(null),i(null),u(null),l(!1),g(null),v(null),_(""),s("devices")},I=B=>{if(B===a){document.getElementById(`legacy-team-setup-step-${B}`)?.focus();return}A.current=!0,s(B)},D=(B,oe)=>{_(oe);const K=B==="devices"?r?.devices.findIndex(Oe=>Oe.decision==="unresolved"):r?.projects.findIndex(Oe=>Oe.resolution==="unresolved"),J=K!==void 0&&K>=0?B==="devices"?`legacy-team-device-row-${K}`:`legacy-team-project-row-${K}`:null;if(J&&B===a){document.getElementById(J)?.focus();return}E.current=J,I(B)},O=r?r.unresolvedDeviceCount>0:!1,W=r?r.unresolvedProjectCount>0:!1,ue=r?Ra(r):!1,re=c||S||!!d,ie=d?"legacy-team-setup-error":c?"legacy-team-setup-refresh-status":S?"legacy-team-setup-operation-status":void 0,be=(B,oe)=>{U.current=Ra(B),i(B),s(K=>{const J=oe&&K==="devices"&&B.draftState!=="completed"&&B.unresolvedDeviceCount>0?"devices":Lb(B);return J!==K&&(A.current=!0),J}),u(Ra(B)?yr:null)},Y=async()=>{const B=await e.loadDetail(t);return be(B,!0),B},fe=async(B,oe=Hs)=>{const K=oe(B);if(_(""),u(K),!(!(B instanceof Bt)||!fi.has(B.errorCode))){try{const J=await e.loadDetail(t);if(be(J,!0),J.draftState==="completed"){u(null),L(J.attemptId,F.current);return}U.current=!0}catch{U.current=!0}u(K)}},ne=async(B,oe,K,J,Oe,Ae)=>{if(!(re||k.current)){k.current=!0,C(!0),J(B),_(oe),u(null);try{try{await Ae()}catch(At){await fe(At,Oe);return}try{await Y(),_(K)}catch{_(""),u(lL)}}finally{k.current=!1,C(!1),J(null)}}},Pe=(B,oe)=>{const K=r;K&&ne(B.deviceRef,`Saving the assignment for ${B.displayName}.`,`${B.displayName} saved.`,g,Hs,()=>e.saveAssignment(t,B.deviceRef,{attemptId:K.attemptId,targetIdentityRef:oe,expectation:B.expectation}))},ge=(B,oe,K)=>{const J=r;if(J){if(oe==="included"&&!K){_(`Save a person assignment before including ${B.displayName}.`);return}ne(B.deviceRef,`Saving the decision for ${B.displayName}.`,`${B.displayName} saved.`,g,Hs,async()=>{oe==="included"&&K?await e.saveDecision(t,B.deviceRef,{attemptId:J.attemptId,decision:"included",expectedTargetIdentityRef:K}):oe!=="included"&&await e.saveDecision(t,B.deviceRef,{attemptId:J.attemptId,decision:oe})})}},ae=B=>{const oe=r;oe&&ne(B.deviceRef,`Clearing the decision for ${B.displayName}.`,`${B.displayName} saved.`,g,Hs,()=>e.clearDecision(t,B.deviceRef,{attemptId:oe.attemptId}))},Ee=(B,oe)=>{const K=r;K&&ne(B.projectRef,`Saving the mapping for ${B.displayName}.`,`${B.displayName} saved.`,v,mL,()=>e.saveProjectMapping(t,B.projectRef,{attemptId:K.attemptId,resolvedProjectRef:oe}))},le=()=>{if(c||S||k.current)return;const B=F.current;k.current=!0,C(!0),_("Refreshing Team setup from the latest server state."),u(null),e.refreshCandidate(t).then(Y).then(oe=>{if(oe.draftState==="completed"){L(oe.attemptId,B);return}_("Team setup refreshed.")}).catch(oe=>fe(oe,fL)).finally(()=>{k.current=!1,C(!1)})},Te=B=>{if(re||k.current)return;const oe=F.current;k.current=!0,C(!0),_("Finishing Team setup."),u(null),e.finish(t,{attemptId:B.attemptId,finishDigest:B.finishDigest,confirmedAccessDeltaDigest:B.accessDeltaDigest,confirmedViewerAccessDeltaDigest:B.viewerAccessDeltaDigest}).then(()=>{A.current=!0,s("completed"),L(B.attemptId,oe)},K=>fe(K,hL)).finally(()=>{k.current=!1,C(!1)})};return o(Fr,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:B=>{B.preventDefault();const oe=document.querySelector('.tab-btn[aria-current="page"]');(uL(qs)?qs:oe)?.focus(),qs=null},onOpenAutoFocus:B=>{const oe=document.getElementById("legacy-team-setup-title");oe&&(B.preventDefault(),oe.focus())},onOpenChange:B=>{B||P()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:o("div",{"aria-busy":c||S?"true":"false",className:"modal-card legacy-team-setup-card",children:[o("div",{className:"modal-header",children:[o("h2",{id:"legacy-team-setup-title",tabIndex:-1,children:R}),o(Mi,{ariaDisabled:S,ariaLabel:`Close ${R}`,onClick:P})]}),o("div",{className:"modal-body legacy-team-setup-body",children:[o("p",{className:"small",id:"legacy-team-setup-description",children:"Review the server-provided device and Project work before this Team can be used for sharing."}),c&&!r?o("p",{role:"status",children:"Loading the latest Team setup details…"}):null,d?o("div",{className:"legacy-team-setup-error",children:[o("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:d}),!r||!ue?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{c||S||(N.current=!0,M.current=U.current,m(B=>B+1))},type:"button",children:c?"Retrying…":"Retry"}):null]}):null,r?o(Z,{children:[a!=="completed"?o(Z,{children:[o("ol",{"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[o("li",{children:o("button",{"aria-current":a==="devices"?"step":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>I("devices"),type:"button",children:"Devices"})}),o("li",{children:o("button",{"aria-current":a==="projects"?"step":void 0,"aria-describedby":O?"legacy-team-setup-block-devices":void 0,"aria-disabled":O?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{O?D("devices","Finish the device decisions before mapping Projects."):I("projects")},type:"button",children:"Projects"})}),o("li",{children:o("button",{"aria-current":a==="review"?"step":void 0,"aria-describedby":O?"legacy-team-setup-block-devices":W?"legacy-team-setup-block-projects":void 0,"aria-disabled":O||W?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{O?D("devices","Finish the device decisions before reviewing access."):W?D("projects","Finish the Project mappings before reviewing access."):I("review")},type:"button",children:"Review"})})]}),O?o("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,W?o("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]}):null,c?o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:b}),ue?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-refresh",onClick:le,type:"button",children:"Refresh Team setup"}):null,a==="devices"?o(iL,{blocked:re,blockedDescriptionId:ie,busyDeviceRef:f,detail:r,onAssign:Pe,onClear:ae,onDecision:ge}):a==="projects"?o(sL,{blocked:re,blockedDescriptionId:ie,busyProjectRef:h,detail:r,onMap:Ee}):a==="review"&&r.canFinish?o(cL,{blocked:re,blockedDescriptionId:ie,detail:r,onFinish:Te}):o(Z,{children:[o(gL,{detail:r,step:a}),a==="review"&&!r.canFinish&&!ue?o("button",{"aria-disabled":c||S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:le,type:"button",children:"Refresh Team setup"}):null]})]}):null]}),o("div",{className:"modal-footer legacy-team-setup-actions",children:o("button",{"aria-disabled":S?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:P,type:"button",children:"Close"})})]})})}function yL(e,t={}){Ge(o(vL,{dependencies:{...dL,...t}}),e)}var Da=new WeakMap;function br(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function bL(e){const t=document.createElement("article");t.className="project-inventory-row recipient-policy-blocked-item";const n=document.createElement("div");n.className="project-inventory-row-header";const r=document.createElement("h3");r.className="project-inventory-title",r.textContent=e.finding;const i=document.createElement("span");return i.className="project-status-badge needs_attention",i.textContent="Blocked",n.append(r,i),t.append(n,br(e.reason,"project-inventory-meta"),br(`Owner: ${e.ownerLabel}`,"settings-note"),br(`Repair: ${e.repairAction}`,"settings-note")),t}function _L(e,t){const n=`review:${JSON.stringify(t)}`;if(Da.get(e)===n)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,Da.set(e,n);return}e.hidden=!1;const r=document.createElement("section");r.className="card recipient-policy-review",r.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const i=document.createElement("h2");if(i.id="recipientPolicyReviewTitle",i.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",r.appendChild(i),t.continuity){const a=t.continuity.findingCount,s=br(`${a.toLocaleString()} older sharing finding${a===1?" was":"s were"} not changed because Codemem could not safely translate ${a===1?"it":"them"} automatically.`,"settings-note");s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),t.blockedItems.length===0&&r.appendChild(br("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),r.appendChild(s)}if(t.blockedItems.length>0){const a=br("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),s=document.createElement("h3");s.className="recipient-policy-blocked-heading",s.textContent="Needs repair";const c=document.createElement("div");c.className="project-inventory-list recipient-policy-review-list";for(const l of t.blockedItems)c.appendChild(bL(l));r.append(a,s,c)}e.replaceChildren(r),Da.set(e,n)}function wL(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(Da.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const a=document.createElement("h2");a.textContent="Recipient migration review";const s=br(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(a,s),e.replaceChildren(i),Da.set(e,r)}var $b=[["","All projects"],["needs_attention","Needs review"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","Received from peers"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],at=null,La=0,su=250,cu=[],lu=new Set,du=new Set,Ks=new Map,Vs=new Map,_r=new Map,$a=new Map,Ws=!1,Ma=!1,jn=!1,hi=0,Oa=null,kt=new Set,Mb=new WeakMap,zs={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},gi=zs,Fn=!1,uu;function Ob(e=!1){if(!e&&Oa)return Oa;const t=Rp().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return Oa=t,t.then(()=>{Oa===t&&(Oa=null)}),t}function He(e){return document.getElementById(e)}function SL(e){return $b.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function CL(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 vi(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function pu(e){return e.identity_source!=="unmapped"&&!vi(e)}function mu(e){return vi(e)?"Received from peers":Js(e.resolved_scope_id)}function TL(e){return vi(e)?"source-owned project":CL(e.resolution_reason)}function NL(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 jb(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Fb(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function wr(){const e=kt.size,t=He("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!jn||!Fn,t.classList.add("project-selection-target"));const n=He("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=Mb.get(r)??[],a=i.filter(s=>kt.has(s)).length;r.checked=i.length>0&&a===i.length,r.indeterminate=a>0&&a<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!jn||!Fn}function IL(e){const t=e.every(n=>kt.has(n));for(const n of e)t?kt.delete(n):kt.add(n);wr()}function Bb(e,t){const n=Fb(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),Mb.set(i,n),i.addEventListener("change",()=>IL(n));const a=document.createElement("span");return a.className="sr-only",a.textContent=t,r.append(i,a),r}function kL(e){if(!Fn)return[];const t=new Set(e),n=new Map(gi.teams.filter(a=>a.status==="active").map(a=>[a.teamId,a.displayName])),r=new Map(gi.identities.filter(a=>a.status==="active"||a.status==="pending").map(a=>[a.identityId,a.displayName])),i=new Map;for(const a of gi.projectRecipients)if(!(a.status!=="active"||!t.has(a.canonicalProjectIdentity)))if(a.recipientKind==="team"){const s=n.get(a.teamId);s&&i.set(`team:${a.teamId}`,{key:`team:${a.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(a.identityId);s&&i.set(`identity:${a.identityId}`,{key:`identity:${a.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((a,s)=>`${a.kind}:${a.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function Ub(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=kL(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Fn?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const a of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${a.kind.toLowerCase()}`,s.textContent=`${a.kind}: ${a.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function Gb(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!jn||!Fn,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{qi({mode:"project-manage",projectId:e[0]})})):(n.textContent="Share selected",n.setAttribute("aria-label",`Share selected identities for ${t}`),n.dataset.projectFocusKey=`share:${e.join("|")}`,n.addEventListener("click",()=>{for(const r of e)kt.add(r);wr(),qi({mode:"project-add",projectIds:[...e].sort()})})),n}function EL(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function fu(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function hu(e){return e.project||e.display_project||"Unnamed Project"}function qb(e){const t=String(e||"").trim();return t?w.lastCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function PL(){return new Set(w.lastCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function AL(e){return!Ma||e.authority_type!=="coordinator"||!e.group_id?!1:!PL().has(String(e.group_id).trim())}function Hb(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function Kb(){Ws&&(Ws=!1,at?.())}async function xL(){try{const e=await Qa();w.lastCoordinatorAdminStatus=e&&typeof e=="object"?e:null}catch{w.lastCoordinatorAdminStatus=null,w.lastCoordinatorAdminGroups=[],Ma=!1;return}if(w.lastCoordinatorAdminStatus?.readiness!=="ready"||!w.lastCoordinatorAdminStatus.has_admin_secret){w.lastCoordinatorAdminGroups=[],Ma=!1;return}try{const e=await bp(!1);w.lastCoordinatorAdminGroups=Array.isArray(e?.items)?e.items:[],Ma=!0}catch{w.lastCoordinatorAdminGroups=[],Ma=!1}}function RL(e){return e.kind==="team_default"}function gu(e){const t=e.label||"Untitled Space";return RL(e)?`${t} (default)`:t}function DL(e,t){const n=gu(e);return t.some(r=>r.scope_id!==e.scope_id&&gu(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function LL(e){const t=qb(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 $L(e){return e?cu.find(t=>t.scope_id===e)??null:null}function Js(e){const t=$L(e);return e?t?`${gu(t)} · ${LL(t)}`:"Unknown Space":"—"}function vu(){return cu.filter(e=>e.scope_id!=="legacy-shared-review"&&!AL(e))}function ML(e){return vu().some(t=>t.scope_id===e)}function Vb(...e){for(const t of e)if(t&&ML(t))return t;return e.find(t=>!!t)??""}function OL(e){const t=qb(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function jL(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function FL(){const e=new Map;for(const t of vu()){const n=jL(t),r=OL(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function Wb(e){for(const t of FL()){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=DL(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function BL(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 yu(e,t,n=[]){try{await DS({...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}),_r.delete(e.workspace_identity),Ks.delete(e.workspace_identity),se("Project Space assignment updated. Device access grants are unchanged."),at?.()}catch(r){if(r instanceof to){_r.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),at?.();return}se(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function UL(e,t){const n=e.filter(pu);if(n.length!==0)try{await LS({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}))}),se(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),Vs.delete(fu(n[0])),at?.()}catch(r){se(r instanceof to?"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 GL(e){if(e.mapping_id!=null)try{await $S(e.mapping_id),_r.delete(e.workspace_identity),Ks.delete(e.workspace_identity),se("Project Space assignment removed. The next fallback now applies."),at?.()}catch(t){se(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function zb(e,t=!1){try{const n=$a.get(e.workspace_identity),r=await OS({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});$a.delete(e.workspace_identity),se(`Forgot ${r.forgotten_memory_count.toLocaleString()} local memor${r.forgotten_memory_count===1?"y":"ies"}. ${r.peer_owned_memory_count.toLocaleString()} peer-owned memor${r.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),at?.()}catch(n){if(n instanceof kp){$a.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),at?.();return}se(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function qL(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Za()).filter(i=>i&&i!==t)}catch{}const r=await ud({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const a=i.trim();return a?a===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await MS({project:r.trim(),workspace_identity:e.workspace_identity});se(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),at?.()}catch(i){se(i instanceof Error?i.message:"Unable to change project.","warning")}}function HL(e){const t=document.createElement("div");if(t.className="project-inventory-actions",pu(e)&&e.memory_count!=null&&e.guardrail_warnings.every(f=>!f.requires_confirmation)){const f=document.createElement("button");f.className="settings-button",f.type="button",f.textContent="Share",f.disabled=!jn,jn||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>Ro([e.workspace_identity])),t.appendChild(f)}if(vi(e)){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(f),t}if(e.identity_source==="unmapped"){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(f),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const a=vu().some(f=>f.scope_id===e.resolved_scope_id);if(!a&&e.resolved_scope_id){const f=document.createElement("option");f.value=e.resolved_scope_id,f.textContent=`${Js(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}Wb(i),i.value=Vb(Ks.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!a,s.addEventListener("click",()=>{yu(e,i.value)}),i.addEventListener("change",()=>{Ks.set(e.workspace_identity,i.value),_r.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,at?.()}),i.addEventListener("blur",Kb);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{yu(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",()=>{GL(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",()=>{qL(e)});const u=document.createElement("button");u.className="settings-button danger",u.type="button",u.textContent="Forget local memories…",u.disabled=(e.memory_count??0)===0,u.addEventListener("click",()=>{zb(e)}),t.append(n,i,s,c,l,d,u);const p=_r.get(e.workspace_identity);if(p){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.textContent="Confirmation required before saving this Space.";const h=document.createElement("p");h.textContent="Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save.";const v=document.createElement("ul");for(const S of p.warnings){const C=document.createElement("li"),N=document.createElement("strong");N.textContent=`${BL(S)}: `;const E=document.createElement("span");E.textContent=S.message,C.append(N,E),v.appendChild(C)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const S=_r.get(e.workspace_identity);!S||S.scopeId!==i.value||yu(e,S.scopeId,S.requiredGuardrailTokens)});const _=document.createElement("button");_.className="settings-button",_.type="button",_.textContent="Cancel",_.addEventListener("click",()=>{_r.delete(e.workspace_identity),at?.()}),f.append(g,h,v,b,_),t.appendChild(f)}const m=$a.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const g=document.createElement("strong");g.textContent="Confirm project memory cleanup.";const h=document.createElement("p");h.textContent=`${m.localOwnedMemoryCount.toLocaleString()} locally owned memor${m.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${m.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${m.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const v=document.createElement("p");v.textContent="Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device.";const b=document.createElement("button");b.className="settings-button danger",b.type="button",b.textContent="I understand, forget local memories",b.addEventListener("click",()=>{zb(e,!0)});const _=document.createElement("button");_.className="settings-button",_.type="button",_.textContent="Cancel",_.addEventListener("click",()=>{$a.delete(e.workspace_identity),at?.()}),f.append(g,h,v,b,_),t.appendChild(f)}return t}function Jb(e){const t=document.createElement("article");t.className="project-inventory-row";const n=`project-title-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;t.setAttribute("aria-labelledby",n);const r=document.createElement("div");r.className="project-inventory-row-header",Po(e)&&r.appendChild(Bb([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),Po(e)&&r.appendChild(Gb([e.workspace_identity],e.display_project)),t.appendChild(r);const a=document.createElement("div");a.className="project-inventory-meta",a.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${jb(e.latest_session_at)}`,t.appendChild(a),t.appendChild(Ub([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=mu(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${TL(e)} · ${e.identity_source} · ${jb(e.latest_session_at)}`,s.appendChild(l),e.sharing&&e.sharing.length>0){const h=document.createElement("div");h.className="settings-note project-sharing-summary";const v=document.createElement("strong");v.textContent="Project sharing";const b=document.createElement("ul");b.setAttribute("aria-label",`People sharing ${e.display_project}`);for(const _ of e.sharing){const S=document.createElement("li"),C=document.createElement("strong");C.textContent=NL(_);const N=document.createElement("span");N.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,S.append(C,N),b.appendChild(S)}h.append(v,b),s.appendChild(h)}if(vi(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=EL(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 ${Js(e.suggested_scope_id)}.`,s.appendChild(h)}const u=(e.guardrail_warnings??[]).filter(h=>h.severity==="warning");if(u.length>0){const h=document.createElement("div");h.className="settings-note project-attention-note",h.textContent=`Needs attention: ${u.map(v=>v.message).join(" ")}`,s.appendChild(h)}if(e.statuses.length>0){const h=document.createElement("div");h.className="project-inventory-badges";for(const v of e.statuses){const b=document.createElement("span");b.className=`project-status-badge ${v}`,b.textContent=SL(v),h.appendChild(b)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details",p.open=lu.has(e.workspace_identity),p.addEventListener("toggle",()=>{p.open?lu.add(e.workspace_identity):lu.delete(e.workspace_identity)});const m=document.createElement("summary");m.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(m),p.appendChild(s);const f=document.createElement("dl");f.className="project-detail-grid";const g=[["Workspace identity",e.workspace_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",mu(e)],["Suggested Space",e.suggested_scope_id?Js(e.suggested_scope_id):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]];for(const[h,v]of g){const b=document.createElement("dt");b.textContent=h;const _=document.createElement("dd");_.textContent=v==null||v===""?"—":String(v),f.append(b,_)}return p.appendChild(f),p.appendChild(HL(e)),t.appendChild(p),t}function KL(e){const t=[...new Set(e.map(n=>mu(n)))];return t.length===1?t[0]:"Mixed Spaces"}function VL(e){if(e.length===1)return Jb(e[0]);const t=fu(e[0]),n=e.filter(Po),r=Fb(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster";const a=hu(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(Bb(n,`Select all identities for ${hu(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=a,c.appendChild(l),r.length>0&&c.appendChild(Gb(r,a)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=KL(e),d.appendChild(u);const p=e.reduce((S,C)=>S+(C.memory_count??0),0),m=e.reduce((S,C)=>S+C.session_count,0),f=document.createElement("div");f.className="project-inventory-meta",f.textContent=`${e.length} identities · ${m.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(f),i.appendChild(Ub(r));const g=document.createElement("div");g.className="project-inventory-actions";const h=e.filter(pu);if(h.length===0){const S=document.createElement("div");S.className="settings-note",S.textContent=e.every(vi)?"These project identities were received from peers. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.",g.appendChild(S),d.appendChild(g)}else{const S=h.map(k=>({project:k,warnings:(k.guardrail_warnings??[]).filter(F=>F.requires_confirmation)})),C=S.some(({warnings:k})=>k.length>0),N=new Set(h.map(k=>k.suggested_scope_id).filter(k=>!!k)),E=new Set(h.map(k=>k.resolved_scope_id)),A=document.createElement("select");A.className="project-domain-select",A.setAttribute("aria-label",`Space for ${hu(e[0])} group`);const M=document.createElement("option");M.value="",M.textContent="Choose Space…",A.appendChild(M),Wb(A),A.value=Vb(Vs.get(t));const U=document.createElement("button");if(U.className="settings-button",U.type="button",U.textContent=`Save Space for ${h.length} identit${h.length===1?"y":"ies"}`,U.disabled=!A.value||C,U.addEventListener("click",()=>{UL(h,A.value)}),A.addEventListener("change",()=>{A.value?Vs.set(t,A.value):Vs.delete(t),U.disabled=!A.value||C}),A.addEventListener("blur",Kb),g.append(A,U),N.size>1||E.size>1||C){const k=document.createElement("div");if(k.className="settings-note project-attention-note",k.textContent=C?"One or more identities in this group need individual review before bulk assignment.":"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment.",C){const F=document.createElement("ul");for(const{project:j,warnings:H}of S){if(H.length===0)continue;const L=document.createElement("li"),R=document.createElement("strong");R.textContent=`Blocked identity: ${j.workspace_identity}`;const P=document.createElement("span");P.textContent=` — ${H.map(I=>I.message).join(" ")}`,L.append(R,P),F.appendChild(L)}k.appendChild(F)}g.appendChild(k)}d.appendChild(g)}const v=document.createElement("details");v.className="project-inventory-details",v.open=du.has(t),v.addEventListener("toggle",()=>{v.open?du.add(t):du.delete(t)});const b=document.createElement("summary"),_=e.reduce((S,C)=>S+(C.guardrail_warnings??[]).filter(N=>N.severity==="warning").length,0);b.textContent=_>0?`Advanced Project administration — ${_.toLocaleString()} item${_===1?"":"s"} need attention`:"Advanced Project administration",v.appendChild(b),v.appendChild(d);for(const S of e)v.appendChild(Jb(S));return i.appendChild(v),i}function WL(e){const t=new Map;for(const n of e){const r=fu(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function Yb(e){const t=He("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function Xb(){document.getElementById("projectsInventorySkeleton")?.remove()}function Qb(e){const t=He("projectsInventoryMeta"),n=He("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;if(Xb(),n.textContent="",e.projects.length===0)Yb("No projects match those filters.");else for(const s of WL(e.projects))n.appendChild(VL(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=He("projectsPrevPage"),a=He("projectsNextPage");i&&(i.disabled=e.offset===0),a&&(a.disabled=!e.has_more),wr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function zL(e,t){xL().then(()=>{t===hi&&(Hb()||Qb(e))})}async function JL(){const e=new Map;let t=0;for(;;){const n=await ro({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 Zb(e,t,n){const r=He("recipientPolicyManagementMount");r&&Df(r,Ao(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&kt.clear(),wr(),at?.()}})}function YL(e,t){const n=t?.candidates.filter(d=>d.status!=="ready")??[],r=e.querySelector(":scope > .project-team-setup-entry");r?.querySelector(".project-team-setup-status")?.remove();const i=r?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement?document.activeElement.dataset.teamSetupCandidateRef:void 0;if(n.length===0){r?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,i&&He("projectsSearch")?.focus();return}const a=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===a){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=a;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),uu){const m=document.createElement("button");m.setAttribute("aria-label",`Finish setting up ${d.displayName}`),m.className="settings-button",m.type="button",m.textContent="Finish setting up this Team",m.dataset.teamSetupCandidateRef=d.candidateRef,m.addEventListener("click",()=>uu?.(d.candidateRef)),u.appendChild(m)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||He("projectsSearch")?.focus()}}function XL(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 QL(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 bu(e={}){const t=He("projectsInventoryMeta"),n=He("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await Ob(!0)).ok:!0;if(Hb())return Ws=!0,!e.requireTeamSetupSummary;Ws=!1;const r=++hi;jn=!1,Fn=!1,wr(),t.textContent="Loading project inventory…";try{const i=Ob(e.requireTeamSetupSummary===!0),[a,s,c,l,d]=await Promise.all([ro({limit:su,offset:La,q:He("projectsSearch")?.value.trim()||void 0,status:He("projectsStatusFilter")?.value||void 0}),ES(),JL().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),kS().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),_c().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==hi)return e.requireTeamSetupSummary&&await i,!1;if(cu=s.scopes,jn=c.ok,Fn=d.ok,gi=d.ok?d.intent:zs,c.ok){const g=new Set(Ao(c.projects).map(h=>h.canonicalProjectIdentity));for(const h of kt)g.has(h)||kt.delete(h)}const u=He("projectShareFlowMount");u&&Ff(u,c.projects,{inventoryError:!c.ok});const p=He("recipientPolicyReviewMount");if(p){const g=QL(p);"review"in l?_L(g,l.review):wL(g,l.error),p.hidden=g.hidden&&!p.querySelector(".project-team-setup-entry")}Zb(c.projects,gi,!c.ok||!d.ok),Qb(a),zL(a,r),i.then(g=>{if(r!==hi)return;const h=He("recipientPolicyReviewMount");if(h){if(!g.ok){XL(h);return}YL(h,g.summary)}});const m=c.ok&&"review"in l&&d.ok;if(!e.requireTeamSetupSummary)return m;const f=await i;return r!==hi?!1:m&&f.ok}catch(i){if(r!==hi)return!1;jn=!1,Fn=!1,gi=zs;const a=He("projectShareFlowMount");return a&&Ff(a,[],{inventoryError:!0}),Zb([],zs,!0),wr(),Xb(),t.textContent="Project inventory failed to load.",Yb(i instanceof Error?i.message:"Unable to load project inventory."),!1}}function ZL(e,t={}){at=e,uu=t.onOpenTeamSetup,kt.clear();const n=He("projectsStatusFilter");if(n&&n.options.length===0)for(const[a,s]of $b){const c=document.createElement("option");c.value=a,c.textContent=s,n.appendChild(c)}const r=()=>{La=0,at?.()};He("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),He("projectsPrevPage")?.addEventListener("click",()=>{La=Math.max(0,La-su),at?.()}),He("projectsNextPage")?.addEventListener("click",()=>{La+=su,at?.()});const i=He("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{kt.size!==0&&qi({mode:"project-add",projectIds:[...kt].sort()})})),wr()}function _u(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(a=>a.trim()):r;if(t.requireNonEmpty&&i.some(a=>a.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function e$(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,a]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof a!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=a}return r}var e_="codemem-settings-advanced",t_="gpt-5.1-codex-mini",n_="claude-4.5-haiku",t$=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],n$={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"},r$=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),i$={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 a$(){try{return globalThis.localStorage?.getItem(e_)==="1"}catch{return!1}}function o$(e){try{globalThis.localStorage?.setItem(e_,e?"1":"0")}catch{}}function fn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function ke(e,t,n){if(fn(t,n))return t[n];if(fn(e,n))return e[n]}function De(e){return e==null?"":String(e)}function Ys(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 s$(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function c$(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Je(e){const t=e.trim();return t===""?"":t}function l$(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:n_,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:t_,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:n_,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:t_,source:"Recommended (direct API)"}}function d$(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return Je(De(n[t]));case"observer_runtime":return Je(De(n.observer_runtime));case"observer_auth_source":return Je(De(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([a,s])=>{typeof a=="string"&&a.trim()&&typeof s=="string"&&(i[a.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!fn(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(!fn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!fn(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 Ys(n[t]);default:return fn(n,t)?n[t]:""}}function u$(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{fn(r,i)&&(r[i]=d$(t,i))}),r}function p$(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let a=[];try{a=_u(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(C){if(!i||n.has("claude_command"))throw C;const N=r.claude_command;a=Array.isArray(N)?N.filter(E=>typeof E=="string").map(E=>E.trim()).filter(E=>E.length>0):[]}let s=[];try{s=_u(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(C){if(!i||n.has("codex_command"))throw C;const N=r.codex_command;s=Array.isArray(N)?N.filter(E=>typeof E=="string").map(E=>E.trim()).filter(E=>E.length>0):[]}let c=[];try{c=_u(t.observerAuthCommand,{label:"observer auth command"})}catch(C){if(!i||n.has("observer_auth_command"))throw C;const N=r.observer_auth_command;c=Array.isArray(N)?N.filter(E=>typeof E=="string"):[]}let l={};try{l=e$(t.observerHeaders)}catch(C){if(!i||n.has("observer_headers"))throw C;const N=r.observer_headers;N&&typeof N=="object"&&!Array.isArray(N)&&Object.entries(N).forEach(([E,A])=>{typeof E=="string"&&E.trim()&&typeof A=="string"&&(l[E]=A)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),h=u===""?"":Number(u),v=p===""?"":Number(p),b=m===""?"":Number(m),_=Number(f),S=f===""?"":_;if(d!==""&&!Number.isFinite(g))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof h!="number"||!Number.isFinite(h)||h<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof v!="number"||!Number.isFinite(v)||v<0))throw new Error("rich tier temperature must be a non-negative number");if(m!==""&&(typeof b!="number"||!Number.isFinite(b)||b<=0||!Number.isInteger(b)))throw new Error("rich tier max output tokens must be a positive integer");if(f!==""&&(!Number.isFinite(_)||_<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:a,codex_command:s,observer_provider:Je(t.observerProvider),observer_model:Je(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Je(t.observerSimpleModel),observer_simple_temperature:h,observer_reasoning_effort:Je(t.observerReasoningEffort),observer_reasoning_summary:Je(t.observerReasoningSummary),observer_rich_model:Je(t.observerRichModel),observer_rich_temperature:v,observer_rich_reasoning_effort:Je(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Je(t.observerRichReasoningSummary),observer_rich_max_output_tokens:b,observer_runtime:Je(t.observerRuntime||"api_http")||"api_http",observer_auth_source:Je(t.observerAuthSource||"auto")||"auto",observer_auth_file:Je(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:g,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:S,sync_enabled:t.syncEnabled,sync_host:Je(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Je(t.syncCoordinatorUrl),sync_coordinator_group:Je(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function m$(e){const t=e.config||{},n=e.effective||{},r=ke(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,m])=>typeof p=="string"&&p.trim()&&typeof m=="string")):{},a=ke(t,n,"claude_command"),s=Array.isArray(a)?a.filter(p=>typeof p=="string"):[],c=ke(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=ke(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:De(ke(t,n,"observer_provider")),observerModel:De(ke(t,n,"observer_model")),observerTierRoutingEnabled:Ys(ke(t,n,"observer_tier_routing_enabled")),observerSimpleModel:De(ke(t,n,"observer_simple_model")),observerSimpleTemperature:De(ke(t,n,"observer_simple_temperature")),observerReasoningEffort:De(ke(t,n,"observer_reasoning_effort")),observerReasoningSummary:De(ke(t,n,"observer_reasoning_summary")),observerRichModel:De(ke(t,n,"observer_rich_model")),observerRichTemperature:De(ke(t,n,"observer_rich_temperature")),observerRichReasoningEffort:De(ke(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:De(ke(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:De(ke(t,n,"observer_rich_max_output_tokens")),observerRuntime:De(ke(t,n,"observer_runtime"))||"api_http",observerAuthSource:De(ke(t,n,"observer_auth_source"))||"auto",observerAuthFile:De(ke(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:De(ke(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:De(ke(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:De(ke(t,n,"observer_max_chars")),packObservationLimit:De(ke(t,n,"pack_observation_limit")),packSessionLimit:De(ke(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:De(ke(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Ys(ke(t,n,"sync_enabled")),syncHost:De(ke(t,n,"sync_host")),syncPort:De(ke(t,n,"sync_port")),syncInterval:De(ke(t,n,"sync_interval_s")),syncMdns:Ys(ke(t,n,"sync_mdns")),syncCoordinatorUrl:De(ke(t,n,"sync_coordinator_url")),syncCoordinatorGroup:De(ke(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:De(ke(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:De(ke(t,n,"sync_coordinator_presence_ttl_s"))}}function f$(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=l$(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Je(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>fn(t,r))?"Env override":n.source}: ${n.model}`}function h$(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 g$(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function v$(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 y$(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 b$(e){return!e}function _$(e,t,n){return t.has(e)||n.has(e)}function w$(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var X={open:!1,previouslyFocused:null,activeTab:"observer",baseline:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,showAdvanced:a$(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...i$}}};function S$(){X.controller?.hideTooltip()}function Sr(e){if(X.controller){X.controller.setRenderState(e);return}X.renderState={...X.renderState,...e}}function C$(e){Sr({values:{...X.renderState.values,...e}})}function T$(e){const t=["observer","queue","sync"].includes(e)?e:"observer";X.activeTab=t,X.controller?.setActiveTab(t)}function Xs(e,t=!0){w.settingsDirty=e,t&&X.controller?.setDirty(e)}function N$(e){X.showAdvanced=e,X.controller?.setShowAdvanced(e)}function r_(){return X.open}function I$(e){return _$(e,X.protectedKeys,r$)}function i_(e={}){return p$({values:X.renderState.values,touchedKeys:X.touchedKeys,baseline:X.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function k$(e){Sr({observerStatus:e&&typeof e=="object"?e:null})}function E$(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},a=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=m$(t);X.envOverrides=i,X.protectedKeys=new Set(a),w.configDefaults=n,w.configPath=t.path||"",Sr({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:w.configPath?`Config path: ${w.configPath}`:"Config path: n/a",providers:s$(t.providers),statusText:"No unsaved changes",values:s}),X.touchedKeys=new Set;try{X.baseline=u$(i_({allowUntouchedParseErrors:!0}),r,i)}catch{X.baseline={}}Xs(!1)}async function P$(){if(!X.open)try{const[e,t]=await Promise.all([xw(),Aw().catch(()=>null)]);E$(e),k$(t)}catch{}}function wu(e){return String(e||"").replace(/_/g," ")}function Su(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 A$(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 x$(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 R$(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function D$({status:e}){if(!e)return o("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,a])=>a&&typeof a=="object");return o("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?o(Z,{children:[o("div",{className:"status-label",children:"Active observer"}),o("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",A$(t.auth?.method||"none")," ",o("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:o("i",{"aria-hidden":"true","data-lucide":t.auth?.token_present===!0?"check":"x"})})]})]}):o(Z,{children:[o("div",{className:"status-label",children:"Observer status"}),o("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),i.length?o(Z,{children:[o("div",{className:"status-label",children:"Available credentials"}),o("div",{children:i.map(([a,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return o("span",{className:"status-cred",children:[c>0?" · ":null,o("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?o("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(a),": ",x$(l)]},a)})})]}):null,r&&typeof r=="object"?o(Z,{children:[o("div",{className:"status-label",children:"Latest processing issue"}),o("div",{className:"status-issue",children:[o("div",{className:"status-issue-message",children:typeof r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),o("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${R$(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?o("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function a_(e,t){const n=t.getBoundingClientRect(),r=8,i=8,a=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-a/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-a-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function ja(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function L$(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 $$(){const e=Me("settingsModal");(L$(e)[0]||e)?.focus()}function M$(){const[e,t]=x({anchor:null,content:"",visible:!1}),n=G(null);return z(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},a=u=>{const p=ja(u.target);p&&r(p)},s=u=>{const p=ja(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=ja(u.target);p&&r(p)},l=u=>{ja(u.target)&&i()},d=u=>{const p=ja(u.target);p&&(u.preventDefault(),t(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const f=p.dataset.tooltip?.trim()||"";return f?{anchor:p,content:f,visible:!0}:m}))};return document.addEventListener("pointerover",a),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",a),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),yt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&a_(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),z(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&a_(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:xe(()=>typeof document>"u"?null:on(o("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function O$({DialogContent:e,onClose:t}){const[n,r]=x(X.open),[i,a]=x(["observer","queue","sync"].includes(X.activeTab)?X.activeTab:"observer"),[s,c]=x(w.settingsDirty),[l,d]=x(X.renderState),[u,p]=x(X.showAdvanced),{tooltipPortal:m,setTooltip:f}=M$();X.open=n,X.activeTab=i,w.settingsDirty=s,X.renderState=l,X.showAdvanced=u,z(()=>(X.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:h=>{const v=["observer","queue","sync"].includes(h)?h:"observer";X.activeTab=v,a(v)},setDirty:h=>{w.settingsDirty=h,c(h)},setOpen:h=>{X.open=h,r(h)},setRenderState:h=>{const v={...X.renderState,...h};X.renderState=v,d(v)},setShowAdvanced:h=>{X.showAdvanced=h,o$(h),p(h)}},()=>{X.controller&&(X.controller=null)}),[]),z(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const g=ce(()=>{X.startPolling&&X.refresh&&t(X.startPolling,X.refresh)},[t]);return o(Z,{children:[o(Fr,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:h=>{h.preventDefault()},onOpenAutoFocus:h=>{h.preventDefault(),$$()},onOpenChange:h=>{if(h){r(!0);return}g()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:o(e,{})}),m]})}function Ue({children:e,className:t="field",hidden:n=!1,id:r}){return o("div",{className:t,hidden:n,id:r,children:e})}function Fa({children:e,hidden:t=!1}){return o("div",{className:"settings-note",hidden:t,children:e})}function Cu({detail:e,title:t}){return o("div",{className:"settings-section-intro",children:[o("div",{className:"settings-section-intro-title",children:t}),o("div",{className:"small settings-section-intro-detail",children:e})]})}function j$({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:a,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:m,observerStatusBannerSlot:f}){return o(Z,{children:[o(Cu,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),f,o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Connection"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerProvider",children:"Model provider"}),o("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),o(Rn,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerModel",children:l()}),o("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),o(Se,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),o("div",{className:"small",children:u()}),o("div",{className:"small",id:"observerModelHint",children:p()})]}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRuntime",children:"Connection mode"}),o("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),o(Rn,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),o(ri,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),o("div",{className:"small",children:m("codex_command")})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),o(ri,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),o("div",{className:"small",children:m("claude_command")})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),o(Se,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),o("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Authentication"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),o("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),o(Rn,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),o(Ue,{hidden:!r,id:"observerAuthFileField",children:[o("label",{htmlFor:"observerAuthFile",children:"Token file path"}),o(Se,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),o("div",{className:"small",children:m("observer_auth_file")})]}),o(Ue,{hidden:!i,id:"observerAuthCommandField",children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthCommand",children:"Token command"}),o("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),o(ri,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),o("div",{className:"small",children:m("observer_auth_command")})]}),o("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),o(Fa,{hidden:a(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),o(Se,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),o(Se,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),o(Ue,{className:"field settings-advanced",hidden:a(),children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),o("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),o(ri,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),o("div",{className:"small",children:m("observer_headers")})]})]})]})}function Qs({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:a,onCheckedChange:s}){const c=`${i}Label`;return o("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[o("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:a}),o(Zr,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function F$({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:a}){return o(Z,{children:[o(Cu,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Processing"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),o("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),o(Se,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),o("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Tiered observer routing"}),o(Qs,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),o("div",{className:"small",children:a()}),o(Fa,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),o("div",{hidden:!t,children:[o("h4",{children:"Simple tier"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerSimpleModel",children:"Model"}),o("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(Se,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),o("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),o(Se,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),o("div",{className:"settings-advanced",hidden:!t||n(),children:[o("h4",{children:"Shared reasoning defaults"}),o("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),o(Ue,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),o(Se,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),o(Ue,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),o(Se,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),o("div",{hidden:!t,children:[o("h4",{children:"Rich tier"}),o(Ue,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRichModel",children:"Model"}),o("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(Se,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),o("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),o(Se,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),o(Se,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),o(Se,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),o(Se,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),o("div",{className:"settings-group settings-advanced",hidden:n(),children:[o("h3",{className:"settings-group-title",children:"Pack limits"}),o(Fa,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),o(Se,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),o("div",{className:"small",children:"Default number of observations to include in a pack."})]}),o(Ue,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),o(Se,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),o("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function B$({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return o(Z,{children:[o(Cu,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Device Sync"}),o(Qs,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),o(Se,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),o("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncHost",children:"Sync host"}),o(Se,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncPort",children:"Sync port"}),o(Se,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),o(Qs,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),o(Se,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),o("div",{className:"small",children:i("sync_coordinator_url")})]}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),o(Se,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),o("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:o(Fa,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),o(Se,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),o(Se,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function U$({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:a,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return o("div",{className:"modal-card",onKeyDown:p=>Vr(p,{onSubmit:s,disabled:u}),children:[o("div",{className:"modal-header",children:[o("h2",{id:"settingsTitle",children:"Settings"}),o(Mi,{ariaLabel:"Close settings",className:"modal-close-button",onClick:a})]}),o("div",{className:"modal-body",children:[o("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),o("div",{className:"settings-advanced-toolbar",children:[o(Qs,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),o("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:o("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),o(Fa,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),o(Kh,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:t$,triggerClassName:"settings-tab",value:t,children:[o(rr,{className:"settings-panel",forceMount:!0,value:"observer",children:o(j$,{...e,observerStatusBannerSlot:d})}),o(rr,{className:"settings-panel",forceMount:!0,value:"queue",children:o(F$,{...e})}),o(rr,{className:"settings-panel",forceMount:!0,value:"sync",children:o(B$,{...e})})]}),o("div",{className:"small mono",id:"settingsPath",children:r.pathText}),o("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),o("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),o("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),o("div",{className:"modal-footer",children:[o("div",{className:"small",id:"settingsStatus",children:r.statusText}),o("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function G$(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:a}=e,s={};return Object.entries(t).forEach(([c,l])=>{a(c)||fn(r,c)&&!i.has(c)||c$(l,n[c])||(s[c]=l)}),s}function q$(e){const t=s=>{const c=n$[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 H$(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=>wu(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>wu(String(p))):[],a=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>wu(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: ${Su(r)}.`),i.length&&d.push(`Live settings updated: ${Su(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),a.length&&d.push(`Restart required for ${Su(a)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=a.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var K$=()=>f$(X.renderState.values,X.envOverrides),V$=()=>h$(X.renderState.values),W$=()=>g$(X.renderState.values),z$=()=>v$(X.renderState.values),J$=()=>y$(X.renderState.values),Y$=()=>b$(X.showAdvanced),{onTextInput:X$,onSelectValueChange:Q$,onSwitchInput:Z$}=q$({getTouchedKeys:()=>X.touchedKeys,getValues:()=>X.renderState.values,updateFormState:C$,setDirty:e=>Xs(e)});function eM(){const e=X.renderState.observerStatus;return o(D$,{status:e})}function tM(){const e=X.renderState.values,t=String(w.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return o(U$,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(X.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((a,s)=>a.localeCompare(s)).map(a=>({label:a,value:a})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:Y$,onTextInput:X$,onSelectValueChange:Q$,onSwitchInput:Z$,getObserverModelLabel:W$,getObserverModelTooltip:z$,getObserverModelDescription:J$,getObserverModelHint:K$,getTieredRoutingHelperText:V$,protectedConfigHelp:w$},activeTab:X.activeTab,showAdvanced:X.showAdvanced,renderState:X.renderState,settingsDirty:w.settingsDirty,onClose:()=>{X.startPolling&&X.refresh&&Zs(X.startPolling,X.refresh)},onSave:()=>{X.startPolling&&X.refresh&&aM(X.startPolling,X.refresh)},onActiveTabChange:T$,onAdvancedToggle:N$,observerStatusBannerSlot:o(eM,{})})}function nM(){return o(O$,{DialogContent:tM,onClose:Zs})}function rM(){const e=Me("settingsDialogMount");e&&Ge(o(nM,{}),e)}function o_(){Me("settingsDialogMount")&&(X.shellMounted||(rM(),X.shellMounted=!0))}function iM(e){X.shellMounted||o_(),X.open=!0,X.previouslyFocused=document.activeElement,e(),X.controller?.setOpen(!0)}function Zs(e,t){if(w.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){X.controller?.setOpen(!0);return}X.open=!1,X.controller?.setOpen(!1),S$(),(X.previouslyFocused&&typeof X.previouslyFocused.focus=="function"?X.previouslyFocused:bl("settingsButton"))?.focus(),X.previouslyFocused=null,X.touchedKeys=new Set,e(),t()}async function aM(e,t){if(!X.renderState.isSaving){Sr({isSaving:!0,statusText:"Saving changes…"});try{const n=G$({current:i_({allowUntouchedParseErrors:!0}),baseline:X.baseline,envOverrides:X.envOverrides,touchedKeys:X.touchedKeys,isProtected:I$});if(Object.keys(n).length===0){Sr({isSaving:!1,statusText:"No unsaved changes"}),Xs(!1),Zs(e,t);return}const r=H$(await Rw(n));Sr({isSaving:!1,statusText:"Saved changes"}),Xs(!1),Zs(e,t),se(r.message,r.type)}catch(n){Sr({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function oM(e,t,n){X.startPolling=t,X.refresh=n,o_(),bl("settingsButton")?.addEventListener("click",()=>iM(e))}function sM(e){e.dataset.syncRenderRoot="preact"}function cM(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function et(e,t){sM(e),Ge(t,e)}function yi(e){e.dataset.syncRenderRoot==="preact"&&Ge(null,e)}function lM(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 dM(e){return typeof e=="object"&&e!==null}function uM(e,t){return w.pairingCommandRaw="",{payloadText:e,hintText:t}}function pM(e){if(!dM(e))return uM("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 w.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function mM(){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 fM(){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 hM(){const e=w.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 gM(){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 vM(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 yM({items:e}){return o(Z,{children:e.map((t,n)=>o("div",{class:"stat",children:o("div",{class:"stat-content",children:[o("div",{class:"value",children:t.value}),o("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function bM({attempts:e,note:t}){return o(Z,{children:[t?o("div",{class:"small",children:t}):null,e.map((n,r)=>o("div",{class:"diag-line",children:[o("div",{class:"left",children:[o("div",{children:[n.peerLabel," — ",n.status]}),n.detail?o("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?o("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null]}),o("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function s_({text:e}){return o(Z,{children:e})}function _M({title:e,detail:t}){return o("div",{class:"sync-empty-state",children:[o("strong",{children:e}),o("span",{children:t})]})}function wM(e,t){if(!t.length){yi(e);return}et(e,o(yM,{items:t}))}function SM(e,t,n){if(!t.length){yi(e);return}et(e,o(bM,{attempts:t,note:n}))}function Cr(e,t){et(e,o(_M,{...t}))}function c_(e,t,n){et(e,o(s_,{text:n.payloadText})),t&&et(t,o(s_,{text:n.hintText}))}function l_({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:a,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=G(null),p=G(null),m=G(!1);yt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),z(()=>{if(!e){m.current=!1;return}m.current||(m.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const f=o(zo,{forceMount:!0,asChild:!0,children:o("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return o(Wo,{open:e,onOpenChange:t,children:[o(Yh,{asChild:!0,children:o("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?a:i})}),l?on(f,l):f]})}function CM({open:e,onOpenChange:t}){return o(l_,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[o("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),o("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),o("div",{className:"actor-create-row",children:[o("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),o(Se,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),o("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),o("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),o("div",{className:"sync-ttl-group",children:[o("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),o(Se,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),o("span",{children:"hours"})]}),o("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),o("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),o(ri,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),o("div",{className:"peer-meta",id:"syncInviteAdminHint"}),o("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function TM({contentHost:e,open:t,onOpenChange:n}){return o(l_,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[o("div",{className:"peer-title",children:[o("strong",{children:"Pairing command"}),o("div",{className:"peer-actions",children:o("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),o("div",{className:"pairing-body",children:o("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),o("div",{className:"peer-meta",id:"pairingHint"})]})}function NM(e,t){et(e,o(CM,{...t}))}function IM(e,t){et(e,o(TM,{...t}))}function me(e){return String(e??"").trim()}function kM(e){return me(e).replace(/\s+/g," ").toLowerCase()}function EM(e){const t=me(e);return t?t.slice(0,8):"Unnamed device"}function d_(e){return me(e?.last_error).toLowerCase()}function u_(e){return e.includes("401")&&e.includes("unauthorized")}function p_(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var PM={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function m_(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 AM(e){const t=m_(e);return!me(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function f_(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),a=LM(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${a}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>h_(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=>h_(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review Space access for this device in Teams, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:me(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function h_(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 xM(n)?"trust":RM(n)?"scope":null}function xM(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function RM(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function DM(e){const t=me(e?.reason);return PM[t]??(t.replaceAll("_"," ")||"sync filters")}function LM(e){const t=new Map;for(const n of e){const r=DM(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 g_(e){const t=me(e.localName);if(t)return t;const n=me(e.coordinatorName);return n||EM(me(e.deviceId))}function $M(e){const t=me(e.localName),n=me(e.coordinatorName);return t||n?!1:!!me(e.deviceId)}function MM(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 Ba(e){const t=me(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=d_(e);return u_(n)?"needs-repair":p_(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function bi(e){const t=e?.status||{},n=me(t.peer_state),r=d_(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}:u_(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}:p_(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 OM={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 jM(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,a]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(a??0));if(s===0)continue;const c=i;r.push({reason:c,label:OM[c]??i,count:s})}return r.sort((i,a)=>a.count-i.count||i.label.localeCompare(a.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function v_(e){return Array.isArray(e)?e.map(t=>me(t)).filter(t=>!!t):[]}function y_(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 ec(e,t){return e?e.replaceAll("_"," "):t}function FM(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=me(r.scope_id),a=me(r.label);if(!i&&!a)return null;const s=a||"Untitled Space",c=[ec(me(r.kind),"user"),ec(me(r.authority_type),"local"),`${ec(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 b_(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=me(n.scope_id),i=me(n.label);if(!r&&!i)return null;const a=i||"Untitled Space",s=me(n.last_applied_cursor),c=me(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=ec(me(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(m=>!!m).join(" · ");return{scopeId:r||a,label:a,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var BM=["personal","private","home","mine","me"],UM=["oss","open source","opensource","community","public"],GM=["work","client"],qM=["local","legacy","review"];function HM(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>me(t)??"").join(" ").toLowerCase()}function KM(e){return[e.scope_id,e.label,e.kind].map(t=>me(t)??"").join(" ").toLowerCase()}function __(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tu(e,t){const n=HM(e);return t.some(r=>{const i=__(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function w_(e){return Tu(e,BM)||Tu(e,UM)}function VM(e){const t=KM(e);return qM.some(n=>{const r=__(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function WM(e){return!w_(e)&&(!VM(e)||Tu(e,GM))}function zM(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(w_),r=t.some(WM);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 JM(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function YM(e){const t=v_(e?.effective_include),n=v_(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${y_(t,"all projects")}`,a=`Exclude filter: ${y_(n,"no exclusions")}`,s=JM(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:a,summary:`${r}. ${i}; ${a}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function XM(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=me(n?.display_name),i=me(n?.actor_id),a=kM(r);if(!r||!i||!a)return;const s=t.get(a)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(a,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function S_(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=me(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const a=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>me(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||a.add(c)})}),{visibleActors:t.filter(s=>!a.has(me(s?.actor_id))),hiddenLocalDuplicateCount:a.size}}var QM=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),ZM=new Set(["pending","verifying","waiting"]);function eO(e){return(Array.isArray(e?.groups)?e.groups.map(t=>me(t)).filter(Boolean):[]).join(", ")||"none"}function C_(e){return me(e?.projects?.[0]?.display_name)||"the shared Project"}function tO(e){const t=e?.items?.find(n=>n.state!=="active");return me(t?.canonicalProjectIdentity)||"the shared Project"}function nO(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=bi(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function rO(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&bi(n).state==="mutual-trust"&&!b_(n).rows.some(r=>r.status==="pending"))}function iO(e){return e.some(t=>me(t.status?.peer_state)==="online"&&bi(t).state==="mutual-trust")}function aO(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=bi(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function oO(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 T_(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],a=eO(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${a}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${a}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s){const p=C_(s);return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. Exact-Project setup has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:`Open Project sharing below and retry setup for ${p}.`}}if(c)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. Recipient access has not converged, so coordinator presence is not a healthy sync signal.`,nextAction:"Open Sharing and use Manage projects for the affected recipient, then run Sync now again."};const l=r.find(p=>{const m=p.lifecycle?.state;return m!==void 0&&QM.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&ZM.has(m)});if(l||d){const p=l?C_(l):tO(e.reconciliation??void 0),m=l?.lifecycle?.primary_action?.kind,f=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:f?"Removal pending":"Setup pending",meta:f?`Team: ${a}. Future access removal for ${p} is still pending.`:`Team: ${a}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:f?`Keep both devices online, then sync again to finish removing future access for ${p}.`:m==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:m==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(oO(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${a}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(nO(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${a}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=me(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${a}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${a}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or configure a coordinator in Advanced settings."}:aO(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${a}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&rO(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${a}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:iO(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function sO(e){return e.discovered?.stale?e.peer?Ba(e.peer)!=="connected":!0:!1}function N_(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 Nu(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 cO(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 lO(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 dO(e,t){const n=new Map,r=i=>{const a=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,a),a};return e.forEach(i=>{const a=me(i?.peer_device_id);if(!a)return;const s=r(a);s.peer=i,s.localName=me(i?.name)}),t.forEach(i=>{const a=me(i?.device_id);if(!a)return;const s=r(a);s.discovered=i,s.coordinatorName=me(i?.display_name)}),[...n.values()]}function uO(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=dO(n,r),a=e.duplicatePersonDecisions??{},s=XM(t).filter(l=>!a[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=g_({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?Ba(l.peer):"waiting",p=l.peer?bi(l.peer):null,m=me(l.discovered?.fingerprint),f=me(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(N_({id:l.deviceId,name:d,title:`${d} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."}));return}if(l.peer&&u==="needs-repair"){const g=p?.description||me(l.peer?.last_error)||"Sync needs review.";c.push(N_({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:g}))}l.peer&&p?.state==="trusted-by-you"&&c.push(Nu({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(Nu({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(Nu({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&&$M({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(cO({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:T_({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Ba(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>sO(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var I_={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 Bn(e){const t=document.getElementById(e);t&&t.remove()}var k_=!1;function pO(e){k_=e}var Iu=!1;function mO(e){Iu=e}var ku=!1;function fO(e){ku=e}var hO=new Set,Eu=new Set,Pu=new Set,E_="codemem-sync-duplicate-person-decisions";function gO(e){const t=String(e||"").trim();t&&(Eu.add(t),Pu.add(t),hO.add(t))}function Au(e){const t=String(e||"").trim();return!!t&&Eu.has(t)}function vO(e){const t=String(e||"").trim();t&&Eu.delete(t)}function yO(e){const t=String(e||"").trim();return!t||!Pu.has(t)?!1:(Pu.delete(t),!0)}function xu(){try{const e=localStorage.getItem(E_);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function P_(e){try{localStorage.setItem(E_,JSON.stringify(e))}catch{}}function A_(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function bO(){return xu()}function _O(e,t){const n=A_(e);if(!n)return;const r=xu();r[n]=t,P_(r)}function wO(e){const t=A_(e);if(!t)return;const n=xu();delete n[t],P_(n)}function x_(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function R_(e){const t=String(e||"");return t?x_(t):""}function SO(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function CO(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function tc(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 Ru(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":tc(e)}function TO(e){return(Array.isArray(w.lastSyncPeers)?w.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function NO(){return S_({actors:w.lastSyncActors,peers:w.lastSyncPeers,duplicatePeople:w.lastSyncViewModel?.duplicatePeople}).visibleActors}function D_(e){return NO().filter(t=>String(t?.actor_id||"")!==e)}function IO(e,t){const n=D_(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Ru(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Du(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=Ho("div","sync-action"),i=Ho("div","sync-action-text");i.textContent=n.label,i.appendChild(Ho("span","sync-action-command",n.command));const a=Ho("button","settings-button sync-action-copy","Copy");a.addEventListener("click",()=>Yi(n.command,a)),r.append(i,a),e.appendChild(r)})}}function L_(e,t){return t&&e.error_redacted===!0}function $_(){const e=document.getElementById("syncAttempts");if(!e)return;const t=w.lastSyncAttempts,n=String(w.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Cr(e,hM());return}const r=vM(n,t.slice(0,5).some(i=>i.status==="error"));SM(e,t.slice(0,5).map(i=>{const a=i.started_at||i.started_at_utc||"",s=String(i.peer_device_id||"").trim(),c=Array.isArray(w.lastSyncPeers)?w.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===s):null,l=String(c?.name||"").trim()||(s?s.slice(0,8):"unknown"),d=i.status==="error",u=[],p=Qi();if(d&&i.error){const m=String(i.error);u.push(p?x_(m):m),L_(i,p)&&u.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!d&&(i.ops_in||i.ops_out)&&u.push(`${i.ops_in??0} in · ${i.ops_out??0} out`),!p&&i.address&&u.push(i.address),{status:i.status||"unknown",peerLabel:l,detail:u.join(" · "),startedAt:a?ur(a):"",...L_(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function kO(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&Cr(e,fM()),t&&Cr(t,gM()),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."),Du(r,[])}function _i(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function EO(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=_i(n.would_remove),a=_i(n.ambiguous),s=_i(r.applied),c=_i(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||a>0?`${a} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function M_(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Bn("syncDiagSkeleton");const r=w.lastSyncStatus;if(!r){Cr(e,mM()),Du(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},a=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=a.last_ping_at||r.last_ping_at||lM(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),m=String(r.daemon_detail||""),f=String(r.daemon_state||"unknown"),g=r.retention||{},h=r.cleanup_diagnostics,v=h?.stale_peer_rows??{},b=_i(v.would_remove),_=_i(v.ambiguous),S=g.enabled===!0,C=Number(g.last_deleted_ops||0),N=g.last_run_at||null,E=String(g.last_error||""),A=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":Hv(f),M=f==="disabled"||r.enabled===!1,U=Object.keys(i).length,k=!M&&U===0;if(t){const H=M?["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:k?["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: ${U}`,c?`Last sync: ${Dn(ii(c))} ago`:"Last sync: never"];f==="offline-peers"&&H.push("All peers are currently offline; sync will resume automatically"),m&&f==="stopped"&&H.push(`Detail: ${m}`),m&&(f==="needs_attention"||f==="rebootstrapping")&&H.push(`Detail: ${m}`),S&&H.push(N?`Retention last ran ${Dn(ii(N))} ago (approx oldest-first)`:"Retention enabled"),b>0?H.push(`${b.toLocaleString()} stale peer rows pending cleanup`):_>0&&H.push(`${_.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=H.join(" · ")}const F=M?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:k?[{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?`${Dn(ii(c))} ago`:"never"},{label:"Last peer ping",value:l?`${Dn(ii(l))} ago`:"never"},{label:"Retention",value:S?N?`${C.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!M&&!k&&(d||u)&&F.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!M&&!k&&s.seconds_since_last&&F.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!M&&!k&&a.seconds_since_last&&F.push({label:"Since last peer ping",value:`${a.seconds_since_last}s`}),!M&&S&&E&&F.push({label:E,value:"Retention"}),!M&&!k&&h&&F.push({label:"Cleanup",value:EO(h)}),wM(e,F);const j=[];k||f==="offline-peers"||(f==="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"})):f==="needs_attention"?j.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?j.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="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"})):!M&&!k&&p>0&&j.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!M&&_>0?j.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!M&&b>0&&j.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Du(n,j)}var PO="syncRedactMount",AO="syncRedactLabel",O_=()=>{};function xO(e){O_=e}var Lu=()=>{};function $u(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;IM(e,{contentHost:t,open:w.syncPairingOpen,onOpenChange:r=>{if(jI(r),$u(),r){const i=document.getElementById("pairingPayload"),a=document.getElementById("pairingHint");i&&c_(i,a,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Lu()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=w.pairingCommandRaw;r&&await Yi(r,n)})}function Mu(){$u();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;c_(e,t,pM(w.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!w.pairingCommandRaw)}function j_(){const e=document.getElementById(PO);e&&et(e,y(Zr,{"aria-labelledby":AO,checked:Qi(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{FI(t),j_(),Lu(),M_(),O_(),$_(),Mu()},thumbClassName:"sync-redact-switch-thumb"}))}function RO(e){Lu=e,$u(),j_()}function DO(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function wi(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),DO(e),e.addEventListener("input",()=>Ua(e),{once:!0}),!1}function Ua(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function ot(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var Tr=new Map,Ou=null,LO={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 $O(e){return LO[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function MO(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 OO(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function ju(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 jO({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[a,s]=x(!1),[c,l]=x(()=>Tr.get(e.operation_id)??null),d=G(null),u=e.lifecycle.primary_action;z(()=>{Ou!==e.operation_id||!d.current||(Ou=null,d.current.focus())},[c?.message,e.operation_id]);async function p(h){s(!0);try{let v=h;if(!v&&n){const _=(await n(e.operation_id)).lifecycle.primary_action;_?.kind==="copy_invite"&&(v=_.invite_link)}if(!v)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(_=>navigator.clipboard.writeText(_)))(v);const b={message:"Invite copied.",tone:"success"};Tr.set(e.operation_id,b),l(b)}catch(v){const b={message:v instanceof Error?v.message:"Invite could not be copied.",tone:"warning"};Tr.set(e.operation_id,b),l(b)}finally{s(!1)}}async function m(){s(!0);try{const h=await t(e.operation_id),v=h.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:h.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${h.lifecycle.label}.`,tone:"success"};Tr.set(e.operation_id,v),Ou=e.operation_id,l(v),await r()}catch(h){const v={message:$O(h),tone:"warning"};Tr.set(e.operation_id,v),l(v),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){const h=e.projects.map(v=>v.project_id?.trim()).filter(v=>!!v);if(h.length!==e.projects.length){const v={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};Tr.set(e.operation_id,v),l(v);return}if(!Ro(h,e.person.display_name)){const v={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};Tr.set(e.operation_id,v),l(v)}}function g(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){m();return}f()}}return o("section",{"aria-label":`${ju(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[o("div",{className:"peer-scope-summary",children:ju(e.lifecycle.state)}),o("ul",{"aria-label":`${ju(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((h,v)=>o("li",{className:"peer-scope-chip",children:h.display_name},`${h.display_name}:${v}`))}),o("div",{className:"peer-scope-summary",children:e.lifecycle.label}),o("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?o("div",{className:"peer-actions",children:o("button",{"aria-busy":a,className:"settings-button",disabled:a,type:"button",onClick:g,children:a?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?o("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function FO({operations:e,...t}){const n=e[0].person,r=OO(e);return o("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[o("h3",{className:"device-row-name",children:n.display_name}),r.length>0?o("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>o("li",{children:i.display_name},i.device_id))}):null,e.map(i=>o(jO,{operation:i,...t},i.operation_id))]})}function BO(e){return e.operations.length===0?null:o("div",{className:"project-share-person-groups",children:MO(e.operations).map(t=>o(FO,{...e,operations:t},t[0].person.actor_id))})}function UO(e,t){et(e,o(BO,{...t}))}function F_({title:e,detail:t}){return o("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[o("strong",{children:e}),o("span",{children:t})]})}function GO(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 qO({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const a=String(e.actor_id||""),s=tc(e),c=TO(a),l=D_(a),d=l.map(j=>String(j.actor_id||"")).join("|"),[u,p]=x(s),[m,f]=x(!1),[g,h]=x("Rename"),[v,b]=x(!1),[_,S]=x("Merge into selected person"),[C,N]=x(""),[E,A]=x(!1);z(()=>{p(s),f(!1),h("Rename"),b(!1),S("Merge into selected person"),N(""),A(!1)},[a,c,t,s,d]);const M=l.length?IO(C,a):"No other people are available yet. Create another person first if you need to merge duplicates.",U=[{label:"Merge into person",value:""},...l.map(j=>{const H=String(j.actor_id||"");return{label:j.is_local?Ru(j):tc(j),value:H}})];async function k(){const j=u.trim();if(!j)return;f(!0),h("Saving…");let H=!1;try{await n(a,j),H=!0}catch{h("Retry rename")}finally{f(!1),H&&h("Rename")}}async function F(){if(!C)return;const j=l.find(L=>String(L.actor_id||"")===C);if(!j||!await Wt({title:`Merge ${s} into ${tc(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;b(!0),S("Merging…");let H=!1;try{await r(C,a),H=!0}catch{S("Retry merge")}finally{b(!1),H&&S("Merge into selected person")}}return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:Ru(e)}),o("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?GO(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:o("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),o("div",{className:"actor-actions",children:e.is_local?o("div",{className:"peer-meta",children:"Rename yourself in config"}):o(Z,{children:[o(Se,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||v,type:"text",value:u,onInput:j=>p(j.currentTarget.value),onKeyDown:j=>Vr(j,{onSubmit:()=>{k()},disabled:m||v||!u.trim()})}),o("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||v,onClick:()=>{k()},children:g}),o("button",{type:"button",className:"settings-button danger",disabled:m||v,onClick:async()=>{await Wt({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(a)},children:"Remove"}),o("button",{type:"button",className:"settings-button",disabled:m||v,onClick:()=>A(j=>!j),children:E?"Hide duplicate cleanup":"Show duplicate cleanup"}),E?o(Z,{children:[o("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),o("div",{className:"actor-merge-controls",children:[o(Rn,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:v||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:N,options:U,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:C,viewportClassName:"sync-radix-select-viewport"}),o("button",{type:"button",className:"settings-button",disabled:v||l.length===0||!C,onClick:()=>{F()},children:_})]}),o("div",{className:"peer-meta actor-merge-note",children:M})]}):null]})})]})}function HO({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?o(Z,{children:e.map(a=>{const s=String(a.actor_id||a.display_name||a.is_local||"");return o(qO,{actor:a,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):o(F_,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function KO(e,t){et(e,o(HO,{...t}))}function VO(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function WO(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${ur(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function zO({devices:e}){return o(Z,{children:WO(e)})}function JO(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 YO(e){const t=VO(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),yi(e.mount),yi(e.meta);return}const n=t.map(JO),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,et(e.mount,o(Rn,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),et(e.meta,o(zO,{devices:t}))}var XO={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function QO({state:e,size:t=8,"aria-label":n}){return o("span",{"aria-label":n??XO[e],className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function Nr({feedback:e}){return e?.message?o("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function ZO(){return o("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[o("title",{children:"Chevron"}),o("path",{d:"m9 18 6-6-6-6"})]})}function ej(e){switch(Ba(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var nc=null,B_=0,Fu=new Set;function U_(e){if(nc!==e){nc=e,B_+=1;for(const t of Fu)t(B_)}}function tj(){const[,e]=x(0);return z(()=>(Fu.add(e),()=>{Fu.delete(e)}),[]),nc}var nj={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 G_(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 rj(e,t,n,r=!1,i=!1,a=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||a&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${G_(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: ${G_(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 ij(e){w.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function aj(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 oj(){window.location.hash="coordinator-admin"}function Bu(e=w.lastCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function sj({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),a=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||a,c=bi(e),l=nj[MM(e)],d=e.status||{},u=FM(e),p=Au(i),m=p&&u.total===0,f=zM(e),g=jM(e),h=b_(e),v=YM(e.project_scope||{}),b=SO(e.addresses),_=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(J=>String(J)))):[],S=Number(e.address_count??0),C=Number.isFinite(S)&&S>0?S:0,N=_.length?_.map(J=>Qi()?R_(J):J).join(" · "):C>0?`${C} ${C===1?"address":"addresses"} hidden`:"No addresses",E=w.lastDeviceIdentityInventory?.items.find(J=>J.deviceId===i||J.evidenceDeviceIds.includes(i)),A=rj(E,String(e.actor_id||"")||null,w.lastSyncActors,w.deviceIdentityInventoryLoadError,w.lastDeviceIdentityInventory?.truncated===!0,w.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),M=String(d.last_sync_at||d.last_sync_at_utc||""),U=String(d.last_ping_at||d.last_ping_at_utc||""),k=e.discovered_via_group_id?`Discovery: seen through Team ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,F=yO(i),j=G(null),[H,L]=x(a),[R,P]=x(()=>w.syncPeerFeedbackById.get(i)??null),[I,D]=x(!1),[O,W]=x("Save name"),[ue,re]=x(!1),[ie,be]=x(!1),[Y,fe]=x("Remove device");z(()=>{p&&u.total>0&&vO(i)},[u.total,i,p]),z(()=>{L(a),P(w.syncPeerFeedbackById.get(i)??null),D(!1),W("Save name"),re(!1),be(!1),fe("Remove device")},[a,e.actor_id,i]),z(()=>{!F||!j.current||queueMicrotask(()=>j.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[F]);async function ne(){if(!i)return;const J=H.trim();if(!J){const Oe={message:"Enter a friendly name for this device.",tone:"warning"};P(Oe),w.syncPeerFeedbackById.set(i,Oe),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}D(!0),W("Saving…");try{const Oe=await n(i,J);P(Oe),w.syncPeerFeedbackById.set(i,Oe),W("Save name")}catch{W("Retry")}finally{D(!1)}}async function Pe(){if(m){const J=Bu();if(!await Wt({title:`Sync ${a} before advanced rule review?`,description:J?"This manual sync will use the current Space access and advanced filters until you review them in Teams.":"This manual sync will use the current Space access and advanced filters until a coordinator or manager reviews them in Teams.",confirmLabel:"Sync anyway",cancelLabel:J?"Review in Teams first":"Cancel"}))return}re(!0);try{const J=await r(e,b);P(J),J&&w.syncPeerFeedbackById.set(i,J)}finally{re(!1)}}async function ge(){if(!i||!await Wt({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;be(!0),fe("Removing…");let J=!1;try{await t(i,s),J=!0}catch{fe("Retry remove")}finally{be(!1),J&&fe("Remove device")}}const ae=tj()===i&&i!=="",Ee=`device-drawer-${i||"unknown"}`,le=ej(e),Te=M?`Sync: ${ur(M)}`:"Sync: never",B=Bu(),oe=`${ae?"Collapse":"Expand"} device ${a}`;return o(Wo,{asChild:!0,open:ae,onOpenChange:J=>{J?U_(i):nc===i&&U_(null)},children:o("div",{ref:j,className:"peer-card","data-peer-device-id":i||void 0,children:[o(Yh,{asChild:!0,children:o("button",{"aria-label":oe,className:"device-row-head device-row-head--trigger",type:"button",children:[o(QO,{state:le}),o("span",{className:"device-row-name",title:i||void 0,children:a}),l?o("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,o("span",{className:"device-row-chips",children:[o("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),m?o("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,o("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),g.badgeLabel?o("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:g.badgeLabel}):null,f.badgeLabel?o("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:f.badgeLabel}):null,e.discovered_via_group_id?o("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),o("span",{className:"device-row-meta",children:Te}),o("span",{"aria-hidden":"true",className:"device-row-chevron",children:o(ZO,{})})]})}),o(zo,{"aria-label":`Device actions for ${a}`,className:"device-row-drawer",id:Ee,children:[o("div",{className:"peer-actions",children:[o("button",{type:"button",className:"settings-button",disabled:ue,onClick:()=>{Pe()},title:b?void 0:"Address details are hidden; sync will target this device by ID.",children:ue?"Syncing…":"Sync now"}),o("div",{className:"sync-labeled-field",children:[o("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),o(Se,{"aria-label":`Friendly name for ${a}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:I,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:H,onInput:J=>L(J.currentTarget.value)})]}),o("button",{type:"button",className:"settings-button",disabled:I,onClick:()=>{ne()},children:O}),o("button",{type:"button",className:"settings-button danger",disabled:ie,onClick:()=>{ge()},children:Y})]}),o("div",{className:"peer-scope",children:[F?o("div",{className:"peer-meta",children:B?"Review this device's Space access and advanced rules in Teams if the defaults are too broad.":"A coordinator or manager can review this device's Space access and advanced rules in Teams if the defaults are too broad."}):m?o("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,o("div",{className:"peer-scope-summary",children:"Device details"}),o("div",{className:"peer-addresses",children:N}),k?o("div",{className:"peer-meta",children:k}):null,o("div",{className:"peer-meta",children:[M?`Sync: ${ur(M)}`:"Sync: never",U?`Ping: ${ur(U)}`:"Ping: never"].join(" · ")}),o("div",{className:"peer-scope-summary",children:"Space access"}),o("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?o("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(J=>o("li",{className:"peer-scope-chip",title:J.detail,children:J.label},J.scopeId))}):null,f.isVisible?o("div",{className:"settings-note",role:"status",children:[o("strong",{children:f.title}),o("div",{children:f.message}),o("div",{children:f.detail})]}):null,o("div",{className:"peer-meta",children:v.note}),o("div",{className:"peer-scope-summary",children:"Space sync progress"}),o("div",{className:"peer-meta",children:h.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":h.emptyMessage}),h.rows.length>0?o("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:h.rows.map(J=>o("li",{title:J.detail,children:[o("span",{className:"peer-scope-rejection-label",children:J.label}),o("span",{className:`badge ${J.status==="received"?"badge-online":"actor-badge"}`,children:J.badgeLabel})]},J.scopeId))}):null,g.total>0?o("div",{className:"peer-scope-rejections","data-peer-rejection-count":g.total,children:[o("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),o("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),o("ul",{className:"peer-scope-rejections-list",children:g.reasons.map(J=>o("li",{children:[o("span",{className:"peer-scope-rejection-label",children:J.label}),o("span",{className:"peer-scope-rejection-count",children:J.count.toLocaleString()})]},J.reason))}),g.lastAt?o("div",{className:"peer-meta",children:["Last rejected ",ur(g.lastAt)]}):null]}):null,o("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),o("div",{className:"peer-meta",children:A.summary}),o("div",{className:"peer-meta",children:A.detail}),e.claimed_local_actor?o("div",{className:"peer-meta",children:aj(e.claimed_local_actor_scope)}):null,o("div",{className:"peer-actor-row",children:o("button",{type:"button",className:"settings-button",onClick:()=>ij(E?.deviceId??i),children:A.actionLabel})}),o("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),o("div",{className:"peer-meta",children:[v.statusLabel,". ",v.summary," ",v.note]}),B?o("div",{className:"peer-actions",children:o("button",{type:"button",className:"settings-button",onClick:oj,children:"Manage Spaces in Teams"})}):o("div",{className:"peer-meta",children:"Space access is managed in Teams by a coordinator or manager."}),o(Nr,{feedback:R})]})]})]})})}function cj(e){const t=w.syncPeersSectionFeedback,n=w.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?o(Z,{children:[o(Nr,{feedback:t}),e.peers.map(i=>{const a=String(i.peer_device_id||i.name||"unknown-peer");return o(sj,{peer:i,...e},a)})]}):o(Z,{children:[o(Nr,{feedback:t}),o(F_,{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 lj(e,t){et(e,o(cj,{...t}))}var Un=async()=>{},rc="";function Uu(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function dj(e){Un=e}function uj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Bn("syncActorsSkeleton"),Uu(!1);const n=S_({actors:w.lastSyncActors,peers:w.lastSyncPeers,duplicatePeople:w.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.`)),KO(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,a)=>{await GS(i,a),await Un()},onMerge:async(i,a)=>{try{await Bp(i,a),se("People combined. Assigned devices moved to the selected person."),await Un()}catch(s){throw se(ot(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await qS(i),se("Person removed. Assigned devices have been unassigned."),await Un()}catch(a){throw se(ot(a,"Failed to remove person."),"warning"),a}}})}function pj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Uu(!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&&Cr(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function mj(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;UO(e,{operations:w.lastShareOperations,onAdvance:n=>RS(n),onLoadOperation:n=>xS(n),onReload:Un});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=w.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":w.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function Gu(){const e=document.getElementById("syncPeers");if(!e)return;Bn("syncPeersSkeleton");const t=w.lastSyncPeers,n=Array.isArray(t)?t:[];CO(w.syncPeersSectionFeedback,n)&&(w.syncPeersSectionFeedback=null),lj(e,{peers:n,onRename:async(r,i)=>{try{return await Ip(r,i),await Un(),{message:"Device name saved.",tone:"success"}}catch(a){return{message:ot(a,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const a=String(r?.peer_device_id||""),s=f_(await Sc({address:i,peerDeviceId:a||void 0}));let c;s.ok?a&&Au(a)?c={message:`Triggered sync for ${r?.name||(a?a.slice(0,8):"unknown")}. ${Bu()?"Review Space access and advanced rules in Teams if this device needs tighter sharing.":"A coordinator or manager can review Space access and advanced rules in Teams if this device needs tighter sharing."}`,tone:"warning"}:c={message:s.message,tone:"success"}:c={message:s.message,tone:"warning"};try{await Un()}catch{c={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return c}catch(a){return{message:ot(a,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Np(r);const a={message:`Removed peer ${i}.`,tone:"success"};return w.syncPeerFeedbackById.delete(r),w.syncPeersSectionFeedback={...a,relatedPeerDeviceId:r},await Un(),a}catch(a){return{message:ot(a,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function fj(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Uu(!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&&Cr(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&&Cr(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 q_(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||YO({devices:Array.isArray(w.lastSyncLegacyDevices)?w.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==rc&&(rc=r,q_())},panel:e,value:rc})}function hj(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Vr(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){wi(n,"Enter a name for the person.");return}Ua(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await US(i),se("Person created."),n.value="",await e()}catch(a){se(ot(a,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(rc||"").trim();if(!i||!r||!await Wt({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const a=r.textContent||"Attach device history";r.textContent="Attaching…";try{await HS(i),se("Old device history attached to you."),await e()}catch(s){se(ot(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=a,r.disabled=!1})}function gj(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function qu(e=gj()){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 H_=!1;function vj(){H_||(H_=!0,window.addEventListener("hashchange",()=>{qu()}))}var Xt={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function yj(e){Xt.loadSyncData=e}var bj=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function _j(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=w.lastCoordinatorAdminStatus?.readiness,r=String(w.lastCoordinatorAdminStatus?.active_group||"").trim();if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent=r?`Teams is ready for ${r}. Advanced admin tools now live in Teams.`:"Teams is ready. Advanced admin tools now live in Teams.";return}const i=n==="partial"?"Finish Teams setup before creating remote invites. Use Teams to check what is missing.":"Configure a coordinator URL, Team, and admin secret before creating remote invites. Use Teams to finish setup.";e.disabled=!0,t.hidden=!1,t.textContent=i}function Hu(){const e=document.getElementById("syncAdminDisclosureMount");e&&NM(e,{open:k_,onOpenChange:t=>{pO(t),Hu(),ac(),Ku()}})}function wj(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function Ku(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(w.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(w.lastTeamInvite?.warnings)?w.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function ic(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=w.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 ac(){const e=document.getElementById("syncInvitePolicyMount");e&&et(e,y(Rn,{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!==Xt.invitePolicy&&(Xt.invitePolicy=n,ac())},options:bj,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:Xt.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function Sj(e,t){Hu(),ac();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),a=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),m=document.getElementById("syncProjectInviteReviewHeading"),f=document.getElementById("syncRecipientName"),g=document.getElementById("syncRecipientDeviceName");let h="",v=0;r?.addEventListener("click",()=>{Ro()||se("Project sharing is unavailable. Refresh Projects and try again.","warning")});const b=async(_,S)=>{if(!u||!f||!g)return"other";const C=await Tp(_);if(S!==v||d?.value.trim()!==_)return"stale";if(C.kind!=="project_share_invite")return"other";const N=(C.projects??[]).map(E=>`${E.display_name} (${E.existing_memory_count} existing ${E.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${C.inviter_name||"A teammate"} invited you${C.team_name?` through ${C.team_name}`:""} to share ${N||"selected projects"}.`),f.value=Br(C.recipient_name),g.value=Br(C.device_name),u.hidden=!1,h=_,l&&(l.textContent="Accept and start syncing"),m?.focus(),"project"};d?.addEventListener("input",()=>{v+=1,d.value.trim()!==h&&(h="",u&&(u.hidden=!0),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!a||!s||!c||i.disabled)return;const _=a.value.trim(),S=Number(s.value);let C=!0;if(_?Ua(a):C=wi(a,"Team name is required."),!S||S<1?C=wi(s,"Must be at least 1 hour."):Ua(s),!!C){i.disabled=!0,i.textContent="Creating…";try{const N=await wp({group_id:_,policy:Xt.invitePolicy,ttl_hours:S||24});w.lastTeamInvite=N,Ku(),c.value=String(N.encoded||""),c.hidden=!1,c.focus(),c.select();const E=Array.isArray(N.warnings)?N.warnings:[];se(E.length?`Invite created. Copy it above and review ${E.length===1?"1 warning":`${E.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",E.length?"warning":"success")}catch(N){se(ot(N,"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",_=>{Vr(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){wi(d,"Paste a team invite or pairing payload.");return}if(Ua(d),h!==_){const C=v;try{const N=await b(_,C);if(N==="project"||N==="stale")return}catch{}if(C!==v||d.value.trim()!==_)return;h=_,l.textContent="Accept invite";return}const S=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(S){const C=N=>Br(N)==="";if(C(S.recipient_name)){f&&wi(f,"Enter a human-readable name using 120 characters or fewer.");return}if(C(S.device_name)){g&&wi(g,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const C=await vc(_,S);w.lastTeamJoin=C;const N=C,E=typeof N.type=="string"?N.type:"team_join";let A;if(E==="pair"){const M=String(C.peer_device_id??"").trim();A={message:M?`Paired with device ${M.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(E==="project_share"){const M=N.restart_required===!0||N.setup_state==="pending_inviter"||C.status==="pending_setup",U=typeof N.detail=="string"?N.detail.trim():"";A=M?{message:U||(N.restart_required===!0?"Project invitation accepted. Restart codemem to finish setup.":N.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 A={message:C.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};w.syncJoinFlowFeedback=A,ic(),d.value="",h="",u&&(u.hidden=!0);try{await t()}catch(M){A={message:ot(M,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},w.syncJoinFlowFeedback=A,ic()}}catch(C){w.syncJoinFlowFeedback={message:ot(C,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},ic(),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 _=f_(await Sc());se(_.message,_.warning?"warning":void 0)}catch(_){se(ot(_,"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 Vu({element:e,hidden:t=!1,restoreParent:n=null}){const r=G(null);return yt(()=>{e&&(e.hidden=t)},[e,t]),yt(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),o("div",{ref:r})}function Cj({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return o(Z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Invite a teammate.",o("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?o(Vu,{element:e,hidden:!t,restoreParent:n}):null]})}function Tj(){return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Pair another device.",o("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),o("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>Yi("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function Nj({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return o(Z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Accept an invite or pairing.",o("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?o(Vu,{element:e,hidden:!t,restoreParent:n}):null]})}function Ij({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return o(Z,{children:[u?o(Z,{children:[o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["Join this device.",o("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?o(Vu,{element:r,hidden:!1,restoreParent:a}):null,o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["This device is not on the team yet.",o("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):o(Z,{children:[o(Nj,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggle:c}),o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:o(Cj,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?o(Tj,{}):null]})}function oc({count:e,label:t}){return o("div",{className:"sync-section-heading",children:[o("div",{className:"sync-action-text sync-section-label",children:t}),e?o("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function sc({children:e}){return o("div",{className:"section-meta sync-section-note",children:e})}function kj({item:e,onAction:t}){const[n,r]=x(!1);return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:[e.title,o("span",{className:"sync-action-command",children:e.summary})]}),o("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function Ej({request:e,onApprove:t,onDeny:n}){const[r,i]=x(null),[a,s]=x(null),[c,l]=x("Approve"),[d,u]=x("Deny");return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:o("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),o("div",{className:"actor-actions",children:[o("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),o("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),o(Nr,{feedback:a})]})}function Pj({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,a]=x(null),[s,c]=x(null),l=e.actionLabel||"Pair with this device",[d,u]=x(l),[p,m]=x("Remove broken device record");return o("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[o("div",{className:"peer-title",children:[o("strong",{title:e.displayTitle||void 0,children:e.displayName}),o("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),o("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?o("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),o("div",{className:"peer-meta",children:e.note}),o("div",{className:"peer-actions",children:[e.mode==="accept"?o("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const f=await r(e)||null;c(f),u(f?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{a(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?o("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?o("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?o(Z,{children:[o("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),o("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("remove"),m("Removing…");try{c(await n(e)||null),m("Remove broken device record")}catch{m("Retry")}finally{a(null)}},children:p})]}):null]}),o(Nr,{feedback:s})]})}function Aj(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return o(Z,{children:[r?o(oc,{label:"Needs attention"}):null,r?o(sc,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?o("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:o("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,o("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>o(kj,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function xj({children:e}){return e?o(Z,{children:[o(oc,{label:"Add devices & teammates"}),o(sc,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function Rj({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!w.syncDiscoveredFeedback?null:on(o(Z,{children:[o(oc,{count:t.length||void 0,label:"Devices waiting for review"}),o(sc,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),o(Nr,{feedback:w.syncDiscoveredFeedback}),t.map(a=>o(Pj,{row:a,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${a.deviceId}:${a.incomingRequestId}:${a.fingerprint}`))]}),e)}function Dj({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!w.syncJoinRequestsFeedback?null:on(o(Z,{children:[o(oc,{count:t.length||void 0,label:"Join requests to review"}),o(sc,{children:"Approve or deny requests here before those devices become part of the team."}),o(Nr,{feedback:w.syncJoinRequestsFeedback}),t.map(i=>o(Ej,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function K_(e){return o(Z,{children:[o(Aj,{...e}),o(xj,{children:e.children}),o(Dj,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),o(Rj,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function V_(e){e&&(e.textContent="")}function cc(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 Lj(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ga(){return Lj()?"auto":"smooth"}var Wu="syncTeamActionsMount",$j="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function Mj(e,t,n=!1){return e.length>1&&(!t||n)}function Oj(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 jj(e,t){const n=document.createElement("div");n.id=Wu,e.appendChild(n),et(n,y(K_,{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 W_(e,t){const n=document.getElementById(Wu);n&&(yi(n),n.remove()),V_(e),t.forEach(r=>{V_(r)})}function qa(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Hu(),ac(),Ku(),ic(),_j();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),a=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Bn("syncTeamSkeleton"),wj();const p=w.lastSyncCoordinator,m=w.lastSyncViewModel||{primaryStatus:T_({status:w.lastSyncStatus,coordinator:p,peers:w.lastSyncPeers,shareOperations:w.lastShareOperations,shareOperationsLoadError:w.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=P=>{if(P.kind==="possible-duplicate-person"){const W=document.getElementById("syncActorsList");W instanceof HTMLElement&&(W.scrollIntoView({block:"center",behavior:Ga()}),cc(W));return}const I=String(P.deviceId||"").trim();if(!I)return;if(P.kind==="name-device"){const W=document.querySelector(`[data-device-name-input="${CSS.escape(I)}"]`);if(W instanceof HTMLInputElement){W.scrollIntoView({block:"center",behavior:Ga()}),W.focus(),W.select(),cc(W);return}}const D=document.querySelector(`[data-peer-device-id="${CSS.escape(I)}"]`);if(D instanceof HTMLElement){D.scrollIntoView({block:"center",behavior:Ga()}),cc(D);return}const O=document.querySelector(`[data-discovered-device-id="${CSS.escape(I)}"]`);O instanceof HTMLElement&&(O.scrollIntoView({block:"center",behavior:Ga()}),cc(O))},g=async P=>{const I=Array.isArray(P.actorIds)?P.actorIds.map(re=>String(re||"").trim()).filter(Boolean):[],D=(Array.isArray(w.lastSyncActors)?w.lastSyncActors:[]).filter(re=>I.includes(String(re?.actor_id||"").trim()));if(D.length<2){se("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const O=await eA({title:"Review possible duplicate people",summary:P.title.replace(/^Possible duplicate person:\s*/,""),actors:D.map(re=>({actorId:String(re?.actor_id||""),label:String(re?.display_name||re?.actor_id||"Unknown person"),isLocal:!!re?.is_local}))});if(O.action==="different-people"){_O(I,"different-people"),se("Okay. I will keep these people separate on this device."),await Xt.loadSyncData();return}if(O.action!=="merge")return;const W=D.find(re=>String(re?.actor_id||"")===O.primaryActorId),ue=D.find(re=>String(re?.actor_id||"")===O.secondaryActorId);if(!W?.actor_id||!ue?.actor_id){se("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await Bp(String(W.actor_id),String(ue.actor_id)),wO(I),se(`Combined duplicate people into ${String(W.display_name||W.actor_id)}.`),await Xt.loadSyncData()}catch(re){try{await Xt.loadSyncData()}catch{}se(ot(re,"Failed to combine these people."),"warning")}},h=async P=>await ud({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:P,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:I=>I.trim()?null:"Enter a device name to pair this device."}),v=!!p?.configured,b=lO(p);e.title=v?String(p.coordinator_url||"").trim():"";const _=document.getElementById("syncOnlineBadge");if(_?Oj(_,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!v){W_(n,[c,u]),t.hidden=!1,n.hidden=!1,jj(n,m.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const S=String(p.presence_status||""),C=Array.isArray(w.lastSyncPeers)?w.lastSyncPeers:[],N=Array.isArray(m.attentionItems)?m.attentionItems:[],E=Array.isArray(p.discovered_devices)?p.discovered_devices:[],A=String(p.coordinator_url||"").trim(),M=E.map(P=>{const I=String(P.device_id||"").trim(),D=g_({coordinatorName:String(P.display_name||"").trim(),deviceId:I})||"Discovered device",O=I&&D!==I?I:null,W=String(P.fingerprint||"").trim(),ue=String(P.incoming_reciprocal_request_id||"").trim(),re=Array.isArray(P.groups)?P.groups.map(Ae=>String(Ae||"").trim()).filter(Boolean):[],ie=C.find(Ae=>String(Ae?.peer_device_id||"")===I),be=Mj(re,!!ie,P.needs_local_approval===!0),Y=m_({device:P,pairedLocally:!!ie}),fe=String(ie?.fingerprint||"").trim(),ne=!!ie&&!!W&&!!fe&&fe!==W,Pe=w.pendingCoordinatorApprovalsByDeviceId.get(I),ge=P.needs_local_approval===!0&&Pe?.coordinatorUrl===A&&Pe?.incomingRequestId===ue,ae=ge?"approval-pending":P.needs_local_approval===!0?"needs-local-approval":"not-required",Ee=!ge&&!b&&AM({device:P,hasAmbiguousCoordinatorGroup:be,pairedLocally:!!ie}),le=Array.isArray(P.addresses)?P.addresses:[],Te=Number(P.address_count??0),B=Number.isFinite(Te)&&Te>0?Te:0,oe=[le.length?le.map(Ae=>Qi()?R_(String(Ae||"")):String(Ae||"")).filter(Boolean).join(" · "):B>0?`${B} ${P.stale?"last-known":"fresh"} ${B===1?"address":"addresses"} hidden`:"No fresh addresses"];!le.length&&O&&oe.push(`device id: ${I}`);let K=null,J=Ee?"accept":"none",Oe=null;return ne?J="conflict":ge?(K="Waiting for refreshed coordinator status. You do not need to approve again.",J="approval-pending"):b&&(!ie||Y.state==="needs-your-approval")?(K=b.message,J="setup-blocked"):be?(K="This device appears in multiple coordinator groups. Review the Team setup before approving it here.",J="ambiguous"):ie&&Au(I)?(K="Review this device's Space access and advanced rules in Teams before you sync it.",J="scope-pending"):ie?.last_error?(oe.push(`error: ${String(ie.last_error)}`),Ee||(J="paired")):ie?.status?.peer_state?(oe.push(`status: ${String(ie.status.peer_state)}`),Ee||(J="paired")):!ie&&P.stale?(K="Wait for a fresh coordinator presence update, then review this device again here.",J="stale"):ie&&!Ee&&(J="paired"),J==="paired"&&(Oe=Y.state==="waiting-for-other-device"?Y.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:K,actionLabel:Y.actionLabel||(ie?"Review device":"Pair with this device"),approvalBadgeLabel:ge?"Approval sent":Y.badgeLabel,approvalState:ae,availabilityLabel:P.stale?"Offline":"Available",connectionLabel:ne?I_.conflicts:ie?I_.pairedLocally:"Not connected on this device",coordinatorUrl:A,deviceId:I,displayName:D,displayTitle:O,fingerprint:W,groupId:re[0]??"",incomingRequestId:ue,mode:J,note:oe.join(" · "),pairedMessage:Oe}}),U=new Set(M.filter(P=>P.approvalState==="approval-pending").map(P=>P.deviceId)),k=N.filter(P=>!P.deviceId||!U.has(P.deviceId)),F=[],j=M.filter(P=>P.mode!=="paired"&&P.mode!=="none"&&P.mode!=="scope-pending"),H=M.filter(P=>P.mode==="accept"||P.mode==="scope-pending").length,L=k.length+F.length+H;l&&(l.hidden=j.length===0&&!w.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=F.length===0&&!w.syncJoinRequestsFeedback),W_(n,[c,u]);const R=document.createElement("div");R.id=Wu,n.appendChild(R),et(R,y(K_,{actionItems:k,actionableCount:L,children:y(Ij,{invitePanel:r,invitePanelOpen:Iu,inviteRestoreParent:i,joinPanel:a,joinPanelOpen:ku,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(mO(!Iu),qa())},onToggleJoinPanel:()=>{a&&(fO(!ku),qa())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:S}),discoveredListMount:u,discoveredRows:j,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async P=>{if(P.kind==="possible-duplicate-person"){await g(P);return}f(P)},onDenyJoinRequest:async()=>null,onInspectConflict:P=>{const I=document.querySelector(`[data-peer-device-id="${CSS.escape(P.deviceId)}"]`);if(I instanceof HTMLElement){I.scrollIntoView({block:"center",behavior:Ga()}),se(`Opened the conflicting local device record for ${P.displayName}.`,"warning");return}se("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async P=>{if(!await Wt({title:`Remove ${P.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 Np(P.deviceId);const I={message:`Removed the broken local device record for ${P.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return w.syncDiscoveredFeedback=I,await Xt.loadSyncData(),I}catch(I){return{message:ot(I,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async P=>{try{const I=await h(P.displayName);return I?await Fj(P,I):null}catch(I){return{message:ot(I,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:F,presenceStatus:S,primaryStatus:m.primaryStatus}))}async function Fj(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),a=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!a||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await oS(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:a||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&w.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s}),w.pendingAcceptedSyncPeers=[...Array.isArray(w.pendingAcceptedSyncPeers)?w.pendingAcceptedSyncPeers.filter(u=>String(u?.peer_device_id||"").trim()!==e.deviceId):[],{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],gO(e.deviceId);let d=n?{message:$j,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"};w.syncDiscoveredFeedback=d,n&&qa();try{t.trim()!==l.trim()&&(await Ip(e.deviceId,t.trim()),w.pendingAcceptedSyncPeers=w.pendingAcceptedSyncPeers.map(u=>String(u?.peer_device_id||"").trim()===e.deviceId?{...u,name:t.trim()}:u),n||(d={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(u){d={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ot(u,"Device connected, but naming did not finish."),tone:"warning"}}w.syncDiscoveredFeedback=d;try{await Xt.loadSyncData()}catch(u){d={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ot(u,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},w.syncDiscoveredFeedback=d}return d}function Bj(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 Si(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function z_(e){return Si(e)?"Unclear project identity":e.displayProject}function Et(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function Uj(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function Gj(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qj(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function Hj(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function Kj(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 Vj(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function Wj({group:e}){const t=e.memorySamples??[],n=t.length;return o("details",{className:"legacy-review-samples",children:[o("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),o("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?o("ul",{className:"legacy-review-sample-list",children:t.map(r=>o("li",{className:"legacy-review-sample",children:[o("div",{className:"legacy-review-sample-title",children:r.title}),o("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",Kj(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?o("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,o("div",{className:"legacy-review-group-meta mono",children:Vj(r)})]},r.id))}):o("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function J_(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${Gj(t)}\\b`,"g"),qj(t,n))),r}function zj(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 Jj({item:e,onReview:t}){return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:e.peerName}),o("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),o("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function Yj({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],a=Object.fromEntries(r.map(I=>[I.workspaceIdentity,I.suggestedScopeId??""])),[s,c]=x({}),[l,d]=x({}),[u,p]=x(a),[m,f]=x({}),[g,h]=x("all"),[v,b]=x(""),[_,S]=x(null),C=r.length,N=e.totalGroupCount??C,E=r.filter(Si).length,A=r.filter(I=>I.suggestedScopeId&&!Si(I)&&Et(I)).length,M=r.filter(I=>m[I.workspaceIdentity]&&Et(I)).length,U=r.filter(I=>m[I.workspaceIdentity]&&Et(I)&&!!u[I.workspaceIdentity]).length,k=r.filter(I=>{const D=Si(I);return g==="suggested"&&(!I.suggestedScopeId||D)||g==="cleanup"&&!D||g==="no-suggestion"&&(I.suggestedScopeId||D)||g==="selected"&&!m[I.workspaceIdentity]?!1:!v.trim()||zj(I,i).includes(v.trim().toLowerCase())});async function F(I){const D=u[I.workspaceIdentity]||I.suggestedScopeId||"";if(!(!D||!t||_)){S(I.workspaceIdentity),d(O=>{const W={...O};return delete W[I.workspaceIdentity],W});try{const O=await t(I,D,!!s[I.workspaceIdentity],s[I.workspaceIdentity]?.confirmation_token);c(O?W=>({...W,[I.workspaceIdentity]:O}):W=>{const ue={...W};return delete ue[I.workspaceIdentity],ue})}catch(O){d(W=>({...W,[I.workspaceIdentity]:J_(O,D,i)}))}finally{S(null)}}}function j(I,D){p(O=>({...O,[I.workspaceIdentity]:D})),c(O=>{const W={...O};return delete W[I.workspaceIdentity],W}),d(O=>{const W={...O};return delete W[I.workspaceIdentity],W})}function H(I,D){f(O=>({...O,[I.workspaceIdentity]:D}))}function L(I){f(D=>({...D,...Object.fromEntries(k.filter(Et).map(O=>[O.workspaceIdentity,I]))}))}function R(){f(I=>({...I,...Object.fromEntries(r.filter(D=>D.suggestedScopeId&&!Si(D)&&Et(D)).map(D=>[D.workspaceIdentity,!0]))}))}async function P(){if(!t||_||U===0)return;const I=r.filter(D=>m[D.workspaceIdentity]&&Et(D)&&!!u[D.workspaceIdentity]);if(!I.every(D=>s[D.workspaceIdentity])){S("bulk");try{for(const D of I){if(s[D.workspaceIdentity])continue;const O=u[D.workspaceIdentity]||D.suggestedScopeId||"";if(O)try{const W=await t(D,O,!1);d(ue=>{const re={...ue};return delete re[D.workspaceIdentity],re}),W&&c(ue=>({...ue,[D.workspaceIdentity]:W}))}catch(W){d(ue=>({...ue,[D.workspaceIdentity]:J_(W,O,i)}))}}}finally{S(null)}}}return o("div",{className:"legacy-review-card",children:[o("div",{className:"legacy-review-header",children:[o("div",{children:[o("div",{className:"actor-title",children:[o("strong",{children:"Legacy shared review"}),o("span",{className:"badge badge-offline",children:"Needs project review"})]}),o("div",{className:"peer-meta legacy-review-summary",children:[N.toLocaleString()," older"," ",N===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",C<N?` Showing ${C.toLocaleString()} projects; open Projects to review the rest.`:""]}),o("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),o("div",{className:"legacy-review-toolbar",children:[o("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${C.toLocaleString()}`],["suggested",`Suggested ${A.toLocaleString()}`],["cleanup",`Needs cleanup ${E.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${U.toLocaleString()}`]].map(([I,D])=>o("button",{className:g===I?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>h(I),type:"button",children:D},I))}),o("div",{className:"legacy-review-bulk-row",children:[o("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:I=>b(I.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),o("button",{className:"settings-button",onClick:()=>L(!0),type:"button",children:"Select visible"}),o("button",{className:"settings-button",onClick:R,type:"button",children:"Select suggested"}),o("button",{className:"settings-button",onClick:()=>L(!1),type:"button",children:"Clear visible"}),t&&i.length>0?o("button",{className:"settings-save",disabled:_!=null||U===0||r.filter(I=>m[I.workspaceIdentity]&&Et(I)&&!!u[I.workspaceIdentity]).every(I=>s[I.workspaceIdentity]),onClick:()=>{P()},type:"button",children:_==="bulk"?"Previewing…":`Preview ${U.toLocaleString()} selected`}):t&&M>0?o("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,U>0&&r.filter(I=>m[I.workspaceIdentity]&&Et(I)&&!!u[I.workspaceIdentity]).every(I=>s[I.workspaceIdentity])?o("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?o("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:k.map(I=>o("li",{className:"legacy-review-group",children:[o("div",{className:"legacy-review-group-main",children:[o("div",{className:"legacy-review-title-wrap",children:[o("input",{"aria-label":`Select ${z_(I)}`,checked:!!m[I.workspaceIdentity],className:"cm-checkbox",disabled:!Et(I),onChange:D=>H(I,D.currentTarget.checked),type:"checkbox"}),o("div",{children:[o("div",{className:"legacy-review-group-title",children:z_(I)}),o("div",{className:"legacy-review-group-meta",children:[Bj(I.identitySource),Uj(I,i)]}),Et(I)?I.peerOwnedMemoryCount?o("div",{className:"legacy-review-cleanup-note",children:[(I.reassignableMemoryCount??I.memoryCount).toLocaleString()," ","local memor",(I.reassignableMemoryCount??I.memoryCount)===1?"y":"ies"," ","can be reassigned; ",I.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",I.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:o("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),Si(I)?o("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),o("span",{className:"legacy-review-count",children:[I.memoryCount.toLocaleString()," memor",I.memoryCount===1?"y":"ies"]})]}),I.suggestionReason?o("div",{className:"legacy-review-reason",children:I.suggestionReason}):null,l[I.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:l[I.workspaceIdentity]}):null,s[I.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:[s[I.workspaceIdentity].warning," This will reassign"," ",s[I.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[I.workspaceIdentity].memory_count.toLocaleString()," memories",s[I.workspaceIdentity].skipped_memory_count?`; ${s[I.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,o(Wj,{group:I}),i.length>0&&t&&Et(I)?o("label",{className:"legacy-review-target",children:[o("span",{children:"Destination Space"}),o("select",{className:"peer-scope-input",disabled:_!=null,onChange:D=>j(I,D.currentTarget.value),value:u[I.workspaceIdentity]||"",children:[o("option",{value:"",children:"Choose Space…"}),i.map(D=>o("option",{value:D.scopeId,children:[D.label," · ",Hj(D.authorityType),D.scopeId===I.suggestedScopeId?" · suggested":""]},D.scopeId))]})]}):null,i.length>0&&t&&Et(I)?o("div",{className:"legacy-review-actions",children:o("button",{type:"button",className:"settings-button",disabled:_!=null||!u[I.workspaceIdentity],onClick:()=>{F(I)},children:_===I.workspaceIdentity?s[I.workspaceIdentity]?"Reassigning…":"Previewing…":s[I.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},I.workspaceIdentity))}):null]})}function Xj({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return o(Z,{children:[t?o(Yj,{item:t,onReassign:n,onReview:r??i}):null,e.map(a=>o(Jj,{item:a,onReview:i},`${a.peerName}:${a.actorId}:${a.scopeLabel}`))]})}function Qj(){Ih("mine"),w.feedQuery="",window.location.hash="feed"}function Zj(){window.location.hash="projects"}async function e1(e,t,n,r){try{const i=await jS({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return w.lastSyncLegacySharedReview=i.legacy_shared_review??null,se(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),Y_(),null}catch(i){if(i instanceof Ep)return i.preview;const a=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw se(a,"warning"),new Error(a)}}function Y_(){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(w.lastSyncSharingReview)?w.lastSyncSharingReview:[],a=w.lastSyncLegacySharedReview,s=Math.max(0,Number(a?.memory_count??0)),c=a?.has_data?{groups:Array.isArray(a.groups)?a.groups.map(d=>{const u=d;return{displayProject:String(u.display_project||u.project||"Unknown project"),identitySource:String(u.identity_source||"unknown"),lastUpdatedAt:typeof u.last_updated_at=="string"?u.last_updated_at:null,memoryCount:Number(u.memory_count||0),memorySamples:Array.isArray(u.memory_samples)?u.memory_samples.map(p=>{const m=p,f=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:f,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(u.peer_owned_memory_count||0),reassignableMemoryCount:Number(u.reassignable_memory_count||0),suggestedScopeId:typeof u.suggested_scope_id=="string"?u.suggested_scope_id:null,suggestionReason:typeof u.suggestion_reason=="string"?u.suggestion_reason:null,workspaceIdentity:String(u.workspace_identity||u.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(a.scope_id||"legacy-shared-review"),totalGroupCount:Number(a.total_group_count||a.groups?.length||0),targetScopes:Array.isArray(a.target_scopes)?a.target_scopes.map(d=>{const u=d;return{authorityType:String(u.authority_type||"unknown"),label:String(u.label||u.scope_id||"Unknown domain"),scopeId:String(u.scope_id||"")}}).filter(d=>d.scopeId):[]}:null;if(!i.length&&!c){yi(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=w.currentProject?`current project (${w.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`,et(n,y(Xj,{items:i.map(d=>({actorDisplayName:String(d.actor_display_name||d.actor_id||"unknown"),actorId:String(d.actor_id||"unknown"),peerName:String(d.peer_name||d.peer_device_id||"Device"),privateCount:Number(d.private_count||0),scopeLabel:String(d.scope_label||"All allowed projects"),shareableCount:Number(d.shareable_count||0)})),legacyReview:c,onLegacyReassign:e1,onLegacyReview:Zj,onReview:Qj}))}var lc="";function t1(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const a of r){const s=String(a.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],a])}for(const[a,s]of w.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){w.pendingCoordinatorApprovalsByDeviceId.delete(a);continue}if(n)continue;const c=i.get(a);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||w.pendingCoordinatorApprovalsByDeviceId.delete(a))}}function n1(){return[...w.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var Ha=null,zu=0,r1=15e3;function X_(e){return`project:${e||""}|includeJoinRequests:false`}function i1(e){const t=X_(e);return!Ha||Ha.key!==t||Date.now()>=Ha.expiresAtMs?null:Ha.payload}function a1(e,t){Ha={key:X_(e),expiresAtMs:Date.now()+r1,payload:t}}function o1(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function s1(){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 Ci(){const e=++zu;try{const t=w.currentProject||"",n=!1,r=w.activeTab==="health";let i=!1;const a=!Qi();let s;r?(s=i1(t),s||(s=await eo(a,t,{includeJoinRequests:!1}),i=!0)):(s=await eo(a,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=w.lastDeviceIdentityInventory,u=w.lastShareOperations,p=!1,m=!1,f=w.deviceIdentityInventoryLoadError,g=!1;const h=bO();try{c=await iS()}catch{p=!0}try{l=await Qa()}catch{m=!0}if(w.activeTab==="advanced"){f=!1;try{d=await wc()}catch{f=!0}}try{const N=await Fp();u=Array.isArray(N.items)?N.items:[]}catch{g=!0}if(e!==zu)return;i&&a1(t,o1(s)),t1(s.coordinator);const v=JSON.stringify([s,c,l,d,f,u,g,h,n1()]);if(v===lc)return;lc=v;const b=s.status&&typeof s.status=="object"?s.status:null;b&&(w.lastSyncStatus=b),Array.isArray(c?.items)?w.lastSyncActors=c.items:w.lastSyncActors=[];const _=Array.isArray(s.peers)?s.peers:[],S=new Set(_.map(N=>String(N?.peer_device_id||"").trim()).filter(Boolean)),C=Array.isArray(w.pendingAcceptedSyncPeers)?w.pendingAcceptedSyncPeers.filter(N=>{const E=String(N?.peer_device_id||"").trim();return E&&!S.has(E)}):[];w.pendingAcceptedSyncPeers=C,w.lastSyncPeers=[..._,...C],f||(w.lastDeviceIdentityInventory=d),w.deviceIdentityInventoryLoadError=f,w.lastShareOperations=u,w.shareOperationsLoadError=g,w.lastSyncSharingReview=s.sharing_review||[],w.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,w.lastSyncCoordinator=s.coordinator||null,w.lastCoordinatorAdminStatus=l&&typeof l=="object"?l:null,w.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],w.lastSyncAttempts=s.attempts||[],w.lastSyncLegacyDevices=s.legacy_devices||[],w.lastSyncDuplicatePersonDecisions=h,w.lastSyncViewModel=uO({actors:w.lastSyncActors,peers:w.lastSyncPeers,coordinator:w.lastSyncCoordinator,status:b,shareOperations:w.lastShareOperations,shareOperationsLoadError:g,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:w.lastSyncDuplicatePersonDecisions}),M_(),qa(),uj(),mj(),Y_(),Gu(),q_(),$_(),xb(),p&&pj(),m&&(w.lastCoordinatorAdminStatus=null,qa())}catch{if(e!==zu)return;lc="",w.deviceIdentityInventoryLoadError=!0,Bn("syncTeamSkeleton"),Bn("syncActorsSkeleton"),Bn("syncPeersSkeleton"),Bn("syncDiagSkeleton"),s1(),fj(),kO()}}function c1(){lc="",w.lastSyncPeers?.length&&Gu()}async function l1(){try{w.pairingPayloadRaw=await aS()||null,Mu()}catch{w.pairingPayloadRaw=null,Mu()}}function d1(e){cM(),gs(),yj(Ci),dj(Ci),xO(Gu),Sj(e,Ci),hj(Ci),RO(e),qu(),vj()}function u1(e,t){const n=Me("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function p1(){try{const e=await Zw();if(!e?.version)return;u1(e.version,"4c47ee4")}catch{}}var Ju=null,Q_=1500,Z_="codemem-legacy-upgrade-notice-dismissed",Gn=null,Qt=!1,Yu=!1,Ka=null;function ew(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function tw(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=ew(n.total_group_count,r.length),a=ew(n.memory_count);return i<=0||a<=0?null:{groupCount:i,memoryCount:a}}function nw(){try{return localStorage.getItem(Z_)==="1"}catch{return!1}}function dc(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(Z_,"1")}catch{}}function rw(){const e=Me("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 m1(){const e=rw(),t=Me("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function iw(e){const t=Me("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),dc(),Va(!1);return}if(e.key==="Enter"){const a=Me("legacyUpgradeReviewGroups");Vr(e,{onSubmit:()=>a?.click(),disabled:!a||a.disabled});return}if(e.key!=="Tab")return;const n=rw();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 aw(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 Va(e,t){const n=Me("legacyUpgradeModalBackdrop"),r=Me("legacyUpgradeModal"),i=Me("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){Ka=document.activeElement,document.addEventListener("keydown",iw),m1(),aw(!0);return}aw(!1),document.removeEventListener("keydown",iw),Ka&&document.contains(Ka)&&Ka.focus(),Ka=null}}function ow(e){!e||Yu||nw()||(Yu=!0,Va(!0,e))}async function f1(){if(!(Yu||nw()))try{ow(tw(await eo(!1,"",{includeJoinRequests:!1})))}catch{}}function Ir(e,t){const n=Me("viewerReconnectOverlay"),r=Me("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.")}async function Xu(){try{return await Qw(),!0}catch{return!1}}function h1(){return document.visibilityState!=="hidden"&&!r_()}function sw(){if(Qt)return;Qt=!0,Qu(),kr("error","(reconnecting)"),Ir(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Xu()){if(Gn&&(clearTimeout(Gn),Gn=null),Qt=!1,Ir(!0,"Viewer responded. Restoring your session…"),h1()){kr("refreshing"),Wa();try{await uc()}catch{}}else kr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Qt||Ir(!1);return}Ir(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Gn=setTimeout(e,Q_)};Gn=setTimeout(e,Q_)}function kr(e,t){w.refreshState=e;const n=Me("refreshStatus");if(!n)return;const r=a=>{const s=Me("refreshAnnouncer");!s||Ju===e||(s.textContent=a,Ju=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}`,Ju=null}function Qu(){w.refreshTimer&&(clearInterval(w.refreshTimer),w.refreshTimer=null)}function Wa(){w.refreshTimer||(w.refreshTimer=setInterval(()=>qn(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Qu(),kr("paused","(tab hidden)")):!r_()&&!Qt&&(Wa(),qn())});function g1(){const e=w.advancedSection==="sync",t=Me("advancedSyncContent"),n=Me("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Me("advancedSyncButton"),i=Me("advancedTeamsButton");r?.setAttribute("aria-pressed",String(e)),i?.setAttribute("aria-pressed",String(!e)),queueMicrotask(()=>{const a=window.location.hash.replace(/^#/,"");qu(a==="sync/diagnostics"||a==="advanced/sync/diagnostics"?"diagnostics":"main")})}function cw(e){const t=new Set(xI(w.lastCoordinatorAdminStatus));nr.forEach(n=>{const r=Me(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),nr.forEach(n=>{const r=Me(`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")}),g1()}function Ti(e,t={}){const n=Xi(e,w.lastCoordinatorAdminStatus);n==="advanced"&&Cl(t.advancedSection??Sl()??w.advancedSection),Nh(n,t.canonicalHash?{canonicalHash:!0}:{}),cw(n),qn()}function v1(){nr.forEach(e=>{Me(`tabBtn-${e}`)?.addEventListener("click",()=>Ti(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Me("advancedSyncButton")?.addEventListener("click",()=>Cl("sync",!0)),Me("advancedTeamsButton")?.addEventListener("click",()=>Cl("teams",!0)),window.addEventListener("hashchange",()=>{const e=wl();if(e){const t=Sl();Ti(e,t?{advancedSection:t}:{})}}),Ti(w.activeTab)}async function y1(){try{const e=await Za();w.knownProjects=e,c1();const t=yl("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 b1(e){w.pendingDeviceIdentityFocus=e?.trim()||null,Ti("devices",{canonicalHash:!0})}var za=$N({},{onOpenTeamSetup:Db,onReviewDevices:b1}),lw={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Zu=0,ep=null,Pt=null;async function _1(){const e=[];let t=0;for(;;){const n=await ro({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return Ao(e)}function w1(){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 w.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of w.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),a=Ba(r);n(i,a==="connected"||a==="available"?"available":a==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function S1(){return w.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 dw(e){if(e==="advanced_sync"){Ti("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}Ti(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function tp(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=C1(e,++Zu);return ep=t,t}async function C1(e,t){Pt||_s(e,lw,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,a]=await Promise.all([_1(),_c(),SS(),wc().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:Pt?.inventory,unavailable:!0})),Ci()]);if(t!==Zu)return ep??!1;const s=w1(),c=S1(),l=Up(w.lastSyncStatus);return!a.unavailable&&a.inventory&&(w.lastDeviceIdentityInventory=a.inventory),w.deviceIdentityInventoryLoadError=a.unavailable,_s(e,r,i,n,s,{inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l,onCommitted:async()=>{const[d,u]=await Promise.all([tp(),za()]);return d&&u},onNavigate:dw,peerRuntimeMetadata:c}),Pt={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==Zu?ep??!1:(Pt?_s(e,Pt.intent,Pt.reconciliation,Pt.projects,Pt.availability,{coordinatorEnrollmentIssueCount:Pt.coordinatorEnrollmentIssueCount,inventory:Pt.inventory,inventoryUnavailable:Pt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([tp(),za()]);return n&&r},onNavigate:dw,peerRuntimeMetadata:Pt.peerRuntimeMetadata,refreshError:!0}):_s(e,lw,{version:1,items:[]},[],[],{loadError:!0}),!1)}}yl("projectFilter")?.addEventListener("change",()=>{w.currentProject=yl("projectFilter")?.value||"",vr(!0),qn()});var np=null;async function qn(){Qt||(np&&clearTimeout(np),np=setTimeout(()=>uc(),80))}async function uc(){if(!Qt){if(w.refreshInFlight){w.refreshQueued=!0;return}w.refreshInFlight=!0;try{kr("refreshing");const e=w.activeTab,t=[eL(),P$()];let n=!0;e==="feed"&&t.push(Qa().then(i=>{w.lastCoordinatorAdminStatus=i&&typeof i=="object"?i:null}).catch(()=>{w.lastCoordinatorAdminStatus=null})),e==="feed"&&t.push(iu()),e==="projects"&&t.push(bu()),e==="sharing"&&t.push(za()),e==="devices"&&t.push(tp().then(i=>{n=i})),(e==="advanced"&&w.advancedSection==="sync"||e==="health")&&t.push(Ci()),e==="advanced"&&w.advancedSection==="teams"&&t.push(hd()),w.syncPairingOpen&&t.push(l1()),await Promise.all(t),ow(tw(w.lastSyncLegacySharedReview));const r=Xi(w.activeTab,w.lastCoordinatorAdminStatus);r!==w.activeTab&&Nh(r),cw(w.activeTab),kr(n?"idle":"error")}catch{await Xu()?kr("error"):sw()}finally{w.refreshInFlight=!1,w.refreshQueued&&!Qt&&(w.refreshQueued=!1,uc())}}}BI();var uw=document.getElementById("toastRoot");uw&&wI(uw);var pw=document.getElementById("legacyTeamSetupMount");pw&&yL(pw,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(w.activeTab==="sharing"?(t=await bu(n),e=await za(n)):(e=await za(n),t=await bu(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),UI(bl("themeToggle")),Ph(Nl()),v1(),BD(),ZL(()=>qn(),{onOpenTeamSetup:Db}),d1(()=>qn()),PA(),oM(Qu,Wa,()=>qn()),y1(),Me("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Ir(!0,"Checking whether the viewer server is back…"),!await Xu()){sw();return}Gn&&(clearTimeout(Gn),Gn=null),Qt=!1,Ir(!0,"Viewer responded. Restoring your session…"),Wa();try{await uc()}catch{}Qt||Ir(!1)}),Me("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{dc(),Va(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Me("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{dc(),Va(!1),window.location.hash="projects"}),Me("legacyUpgradeNotNow")?.addEventListener("click",()=>{dc(),Va(!1)}),p1(),f1(),qn(),Wa()})();
|
|
110
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${en(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=Ob(e);if(i===null)return r;e=i;let a='<a href="'+e+'"';return t&&(a+=' title="'+en(t)+'"'),a+=">"+r+"</a>",a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Ob(e);if(i===null)return en(n);e=i;let a=`<img src="${e}" alt="${en(n)}"`;return t&&(a+=` title="${en(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:en(e.text)}},Pu=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}},Ut=class om{options;renderer;textRenderer;constructor(t){this.options=t||xr,this.options.renderer=this.options.renderer||new oc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Pu}static parse(t,n){return new om(n).parse(t)}static parseInline(t,n){return new om(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","html","def","paragraph","text"].includes(s.type)){n+=c||"";continue}}let a=i;switch(a.type){case"space":n+=this.renderer.space(a);break;case"hr":n+=this.renderer.hr(a);break;case"heading":n+=this.renderer.heading(a);break;case"code":n+=this.renderer.code(a);break;case"table":n+=this.renderer.table(a);break;case"blockquote":n+=this.renderer.blockquote(a);break;case"list":n+=this.renderer.list(a);break;case"checkbox":n+=this.renderer.checkbox(a);break;case"html":n+=this.renderer.html(a);break;case"def":n+=this.renderer.def(a);break;case"paragraph":n+=this.renderer.paragraph(a);break;case"text":n+=this.renderer.text(a);break;default:{let s='Token with "'+a.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 a=t[i];if(this.options.extensions?.renderers?.[a.type]){let c=this.options.extensions.renderers[a.type].call({parser:this},a);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){r+=c||"";continue}}let s=a;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}},Ba=class{options;block;constructor(e){this.options=e||xr}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?Bt.lex:Bt.lexInline}provideParser(e=this.block){return e?Ut.parse:Ut.parseInline}},OD=class{defaults=_u();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ut;Renderer=oc;TextRenderer=Pu;Lexer=Bt;Tokenizer=ac;Hooks=Ba;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 a of i.header)n=n.concat(this.walkTokens(a.tokens,t));for(let a of i.rows)for(let s of a)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(a=>{let s=i[a].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 a=t.renderers[i.name];a?t.renderers[i.name]=function(...s){let c=i.renderer.apply(this,s);return c===!1&&(c=a.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 a=t[i.level];a?a.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 oc(this.defaults);for(let a in n.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let s=a,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 ac(this.defaults);for(let a in n.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let s=a,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 Ba;for(let a in n.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let s=a,c=n.hooks[s],l=i[s];Ba.passThroughHooks.has(a)?i[s]=d=>{if(this.defaults.async&&Ba.passThroughHooksRespectAsync.has(a))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,a=n.walkTokens;r.walkTokens=function(s){let c=[];return c.push(a.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 Bt.lex(e,t??this.defaults)}parser(e,t){return Ut.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(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 a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(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?Bt.lex:Bt.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?Ut.parse:Ut.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let s=(i.hooks?i.hooks.provideLexer(e):e?Bt.lex:Bt.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?Ut.parse:Ut.parseInline)(s,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(s){return a(s)}}}onError(e,t){return n=>{if(n.message+=`
|
|
111
|
+
Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+en(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},Lr=new OD;function Ae(e,t){return Lr.parse(e,t)}Ae.options=Ae.setOptions=function(e){return Lr.setOptions(e),Ae.defaults=Lr.defaults,Ib(Ae.defaults),Ae},Ae.getDefaults=_u,Ae.defaults=xr,Ae.use=function(...e){return Lr.use(...e),Ae.defaults=Lr.defaults,Ib(Ae.defaults),Ae},Ae.walkTokens=function(e,t){return Lr.walkTokens(e,t)},Ae.parseInline=Lr.parseInline,Ae.Parser=Ut,Ae.parser=Ut.parse,Ae.Renderer=oc,Ae.TextRenderer=Pu,Ae.Lexer=Bt,Ae.lexer=Bt.lex,Ae.Tokenizer=ac,Ae.Hooks=Ba,Ae.parse=Ae;var pU=Ae.options,mU=Ae.setOptions,fU=Ae.use,hU=Ae.walkTokens,gU=Ae.parseInline,vU=Ae,yU=Ut.parse,bU=Bt.lex,FD={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 BD(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:")}Nb.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&(BD(e.getAttribute("href")||"")?(e.setAttribute("rel","noopener noreferrer"),e.setAttribute("target","_blank")):e.removeAttribute("href"))});function Au(e){const t=Ae.parse(String(e||""),{async:!1});return Nb.sanitize(t,FD)}function UD(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?v("div",{className:"summary-section",key:r},v("div",{className:"summary-section-label"},Tx(r)),v("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:Au(i)}})):null}).filter(Boolean)}function qD(e){const t=e.map(n=>String(n||"").trim()).filter(Boolean);if(!t.length)return null;if(t.every(n=>/.+?:\s+.+/.test(n))){const n=t.map((r,i)=>{const a=r.indexOf(":"),s=r.slice(0,a).trim(),c=r.slice(a+1).trim();return!s||!c?null:v("div",{className:"summary-section",key:`${s}-${i}`},v("div",{className:"summary-section-label"},s),v("div",{className:"summary-section-content",dangerouslySetInnerHTML:{__html:Au(c)}}))}).filter(Boolean);if(n.length)return v("div",{className:"feed-body facts"},n)}return v("div",{className:"feed-body"},v("ul",null,t.map((n,r)=>v("li",{key:`${n}-${r}`},n))))}function qb(e,t="feed-body"){const n=String(e||"").trim();return n?v("div",{className:t,dangerouslySetInnerHTML:{__html:Au(n)}}):null}function GD(e){const t=["request","outcome","plan","completed","learned","investigated","next","next_steps","notes"],n=s=>{if(!s||typeof s!="object"||Array.isArray(s))return!1;const c=s;return t.some(l=>{const d=c[l];return typeof d=="string"&&d.trim().length>0})},r=e?.summary;if(r&&typeof r=="object"&&!Array.isArray(r)){const s=r.summary;if(n(r))return r;if(n(s))return s}const i=e?.metadata_json;if(n(i))return i;if(i&&n(i.summary))return i.summary;const a=String(e?.body_text||"").trim();if(a.includes("## ")){const s={request:"request",completed:"completed",learned:"learned",investigated:"investigated","next steps":"next_steps",notes:"notes"},c={},l=/(?:^|\n)##\s+([^\n]+)\n([\s\S]*?)(?=\n##\s+|$)/g;for(let d=l.exec(a);d;d=l.exec(a)){const u=s[String(d[1]||"").trim().toLowerCase()],p=String(d[2]||"").trim();u&&p&&(c[u]=p)}if(n(c))return c}return null}function sc(e,t){return String(e?.kind||"").toLowerCase()==="session_summary"||t?.is_summary===!0?!0:String(t?.source||"").trim().toLowerCase()==="observer_summary"}function HD(e,t){const n=String(e?.kind||"").trim().toLowerCase();return sc(e,t)?"session_summary":n||"change"}var Eu=["Enter"," "],KD=["ArrowDown","PageUp","Home"],Gb=["ArrowUp","PageDown","End"],VD=[...KD,...Gb],WD={ltr:[...Eu,"ArrowRight"],rtl:[...Eu,"ArrowLeft"]},zD={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Ua="Menu",[qa,JD,YD]=os(Ua),[$r,Hb]=dt(Ua,[YD,On,pi]),Ga=On(),Kb=pi(),[Vb,Jn]=$r(Ua),[XD,Ha]=$r(Ua),Wb=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:a,modal:s=!0}=e,c=Ga(t),[l,d]=D(null),u=q(!1),p=pt(a),m=ga(i);return W(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",y,{capture:!0,once:!0}),document.addEventListener("pointermove",y,{capture:!0,once:!0})},y=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),o(Ca,{...c,children:o(Vb,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:o(XD,{scope:t,onClose:oe(()=>p(!1),[p]),isUsingKeyboardRef:u,dir:m,modal:s,children:r})})})};Wb.displayName=Ua;var QD="MenuAnchor",xu=K((e,t)=>{const{__scopeMenu:n,...r}=e,i=Ga(n);return o(Na,{...i,...r,ref:t})});xu.displayName=QD;var Du="MenuPortal",[ZD,zb]=$r(Du,{forceMount:void 0}),Jb=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,a=Jn(Du,t);return o(ZD,{scope:t,forceMount:n,children:o(ot,{present:n||a.open,children:o(fr,{asChild:!0,container:i,children:r})})})};Jb.displayName=Du;var Tt="MenuContent",[eL,Lu]=$r(Tt),Yb=K((e,t)=>{const n=zb(Tt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=Jn(Tt,e.__scopeMenu),s=Ha(Tt,e.__scopeMenu);return o(qa.Provider,{scope:e.__scopeMenu,children:o(ot,{present:r||a.open,children:o(qa.Slot,{scope:e.__scopeMenu,children:s.modal?o(tL,{...i,ref:t}):o(nL,{...i,ref:t})})})})}),tL=K((e,t)=>{const n=Jn(Tt,e.__scopeMenu),r=q(null),i=be(t,r);return W(()=>{const a=r.current;if(a)return Ko(a)},[]),o($u,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:X(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),nL=K((e,t)=>{const n=Jn(Tt,e.__scopeMenu);return o($u,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),rL=pr("MenuContent.ScrollLock"),$u=K((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,disableOutsideScroll:y,...g}=e,h=Jn(Tt,n),b=Ha(Tt,n),w=Ga(n),_=Kb(n),I=JD(n),[N,T]=D(null),x=q(null),j=be(t,x,h.onContentChange),B=q(0),P=q(""),F=q(0),O=q(null),G=q("right"),$=q(0),A=y?na:z,E=y?{as:rL,allowPinchZoom:!0}:void 0,C=U=>{const V=P.current+U,de=I().filter(Ce=>!Ce.disabled),ie=document.activeElement,ne=de.find(Ce=>Ce.ref.current===ie)?.textValue,Re=gL(de.map(Ce=>Ce.textValue),V,ne),ye=de.find(Ce=>Ce.textValue===Re)?.ref.current;(function Ce(re){P.current=re,window.clearTimeout(B.current),re!==""&&(B.current=window.setTimeout(()=>Ce(""),1e3))})(V),ye&&setTimeout(()=>ye.focus())};W(()=>()=>window.clearTimeout(B.current),[]),jo();const L=oe(U=>G.current===O.current?.side&&yL(U,O.current?.area),[]);return o(eL,{scope:n,searchRef:P,onItemEnter:oe(U=>{L(U)&&U.preventDefault()},[L]),onItemLeave:oe(U=>{L(U)||(x.current?.focus(),T(null))},[L]),onTriggerLeave:oe(U=>{L(U)&&U.preventDefault()},[L]),pointerGraceTimerRef:F,onPointerGraceIntentChange:oe(U=>{O.current=U},[]),children:o(A,{...E,children:o(ea,{asChild:!0,trapped:i,onMountAutoFocus:X(a,U=>{U.preventDefault(),x.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:o(mr,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:p,onInteractOutside:m,onDismiss:f,children:o(dd,{asChild:!0,..._,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:N,onCurrentTabStopIdChange:T,onEntryFocus:X(l,U=>{b.isUsingKeyboardRef.current||U.preventDefault()}),preventScrollOnEntryFocus:!0,children:o(Ts,{role:"menu","aria-orientation":"vertical","data-state":m_(h.open),"data-radix-menu-content":"",dir:b.dir,...w,...g,ref:j,style:{outline:"none",...g.style},onKeyDown:X(g.onKeyDown,U=>{const V=U.target.closest("[data-radix-menu-content]")===U.currentTarget,de=U.ctrlKey||U.altKey||U.metaKey,ie=U.key.length===1;V&&(U.key==="Tab"&&U.preventDefault(),!de&&ie&&C(U.key));const ne=x.current;if(U.target!==ne||!VD.includes(U.key))return;U.preventDefault();const Re=I().filter(ye=>!ye.disabled).map(ye=>ye.ref.current);Gb.includes(U.key)&&Re.reverse(),fL(Re)}),onBlur:X(e.onBlur,U=>{U.currentTarget.contains(U.target)||(window.clearTimeout(B.current),P.current="")}),onPointerMove:X(e.onPointerMove,Va(U=>{const V=U.target,de=$.current!==U.clientX;U.currentTarget.contains(V)&&de&&(G.current=U.clientX>$.current?"right":"left",$.current=U.clientX)}))})})})})})})});Yb.displayName=Tt;var iL="MenuGroup",Mu=K((e,t)=>{const{__scopeMenu:n,...r}=e;return o(le.div,{role:"group",...r,ref:t})});Mu.displayName=iL;var aL="MenuLabel",Xb=K((e,t)=>{const{__scopeMenu:n,...r}=e;return o(le.div,{...r,ref:t})});Xb.displayName=aL;var cc="MenuItem",Qb="menu.itemSelect",lc=K((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,a=q(null),s=Ha(cc,e.__scopeMenu),c=Lu(cc,e.__scopeMenu),l=be(t,a),d=q(!1),u=()=>{const p=a.current;if(!n&&p){const m=new CustomEvent(Qb,{bubbles:!0,cancelable:!0});p.addEventListener(Qb,f=>r?.(f),{once:!0}),wl(p,m),m.defaultPrevented?d.current=!1:s.onClose()}};return o(Zb,{...i,ref:l,disabled:n,onClick:X(e.onClick,u),onPointerDown:p=>{e.onPointerDown?.(p),d.current=!0},onPointerUp:X(e.onPointerUp,p=>{d.current||p.currentTarget?.click()}),onKeyDown:X(e.onKeyDown,p=>{const m=c.searchRef.current!=="";n||m&&p.key===" "||Eu.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});lc.displayName=cc;var Zb=K((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...a}=e,s=Lu(cc,n),c=Kb(n),l=q(null),d=be(t,l),[u,p]=D(!1),[m,f]=D("");return W(()=>{const y=l.current;y&&f((y.textContent??"").trim())},[a.children]),o(qa.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:o(ud,{asChild:!0,...c,focusable:!r,children:o(le.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...a,ref:d,onPointerMove:X(e.onPointerMove,Va(y=>{r?s.onItemLeave(y):(s.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:X(e.onPointerLeave,Va(y=>s.onItemLeave(y))),onFocus:X(e.onFocus,()=>p(!0)),onBlur:X(e.onBlur,()=>p(!1))})})})}),oL="MenuCheckboxItem",e_=K((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return o(a_,{scope:e.__scopeMenu,checked:n,children:o(lc,{role:"menuitemcheckbox","aria-checked":dc(n)?"mixed":n,...i,ref:t,"data-state":Fu(n),onSelect:X(i.onSelect,()=>r?.(dc(n)?!0:!n),{checkForDefaultPrevented:!1})})})});e_.displayName=oL;var t_="MenuRadioGroup",[sL,cL]=$r(t_,{value:void 0,onValueChange:()=>{}}),n_=K((e,t)=>{const{value:n,onValueChange:r,...i}=e,a=pt(r);return o(sL,{scope:e.__scopeMenu,value:n,onValueChange:a,children:o(Mu,{...i,ref:t})})});n_.displayName=t_;var r_="MenuRadioItem",i_=K((e,t)=>{const{value:n,...r}=e,i=cL(r_,e.__scopeMenu),a=n===i.value;return o(a_,{scope:e.__scopeMenu,checked:a,children:o(lc,{role:"menuitemradio","aria-checked":a,...r,ref:t,"data-state":Fu(a),onSelect:X(r.onSelect,()=>i.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});i_.displayName=r_;var ju="MenuItemIndicator",[a_,lL]=$r(ju,{checked:!1}),o_=K((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,a=lL(ju,n);return o(ot,{present:r||dc(a.checked)||a.checked===!0,children:o(le.span,{...i,ref:t,"data-state":Fu(a.checked)})})});o_.displayName=ju;var dL="MenuSeparator",s_=K((e,t)=>{const{__scopeMenu:n,...r}=e;return o(le.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});s_.displayName=dL;var uL="MenuArrow",c_=K((e,t)=>{const{__scopeMenu:n,...r}=e,i=Ga(n);return o(Rs,{...i,...r,ref:t})});c_.displayName=uL;var Ou="MenuSub",[pL,l_]=$r(Ou),mL=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:i}=e,a=Jn(Ou,t),s=Ga(t),[c,l]=D(null),[d,u]=D(null),p=pt(i);return W(()=>(a.open===!1&&p(!1),()=>p(!1)),[a.open,p]),o(Ca,{...s,children:o(Vb,{scope:t,open:r,onOpenChange:p,content:d,onContentChange:u,children:o(pL,{scope:t,contentId:ut(),triggerId:ut(),trigger:c,onTriggerChange:l,children:n})})})};mL.displayName=Ou;var Ka="MenuSubTrigger",d_=K((e,t)=>{const n=Jn(Ka,e.__scopeMenu),r=Ha(Ka,e.__scopeMenu),i=l_(Ka,e.__scopeMenu),a=Lu(Ka,e.__scopeMenu),s=q(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=a,d={__scopeMenu:e.__scopeMenu},u=oe(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return W(()=>u,[u]),W(()=>{const p=c.current;return()=>{window.clearTimeout(p),l(null)}},[c,l]),o(xu,{asChild:!0,...d,children:o(Zb,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":m_(n.open),...e,ref:$o(t,i.onTriggerChange),onClick:p=>{e.onClick?.(p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:X(e.onPointerMove,Va(p=>{a.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(a.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:X(e.onPointerLeave,Va(p=>{u();const m=n.content?.getBoundingClientRect();if(m){const f=n.content?.dataset.side,y=f==="right",g=y?-5:5,h=m[y?"left":"right"],b=m[y?"right":"left"];a.onPointerGraceIntentChange({area:[{x:p.clientX+g,y:p.clientY},{x:h,y:m.top},{x:b,y:m.top},{x:b,y:m.bottom},{x:h,y:m.bottom}],side:f}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(p),p.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:X(e.onKeyDown,p=>{const m=a.searchRef.current!=="";e.disabled||m&&p.key===" "||WD[r.dir].includes(p.key)&&(n.onOpenChange(!0),n.content?.focus(),p.preventDefault())})})})});d_.displayName=Ka;var u_="MenuSubContent",p_=K((e,t)=>{const n=zb(Tt,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,a=Jn(Tt,e.__scopeMenu),s=Ha(Tt,e.__scopeMenu),c=l_(u_,e.__scopeMenu),l=q(null),d=be(t,l);return o(qa.Provider,{scope:e.__scopeMenu,children:o(ot,{present:r||a.open,children:o(qa.Slot,{scope:e.__scopeMenu,children:o($u,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:X(e.onFocusOutside,u=>{u.target!==c.trigger&&a.onOpenChange(!1)}),onEscapeKeyDown:X(e.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:X(e.onKeyDown,u=>{const p=u.currentTarget.contains(u.target),m=zD[s.dir].includes(u.key);p&&m&&(a.onOpenChange(!1),c.trigger?.focus(),u.preventDefault())})})})})})});p_.displayName=u_;function m_(e){return e?"open":"closed"}function dc(e){return e==="indeterminate"}function Fu(e){return dc(e)?"indeterminate":e?"checked":"unchecked"}function fL(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function hL(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function gL(e,t,n){const r=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=hL(e,Math.max(i,0));r.length===1&&(a=a.filter(c=>c!==n));const s=a.find(c=>c.toLowerCase().startsWith(r.toLowerCase()));return s!==n?s:void 0}function vL(e,t){const{x:n,y:r}=e;let i=!1;for(let a=0,s=t.length-1;a<t.length;s=a++){const c=t[a],l=t[s],d=c.x,u=c.y,p=l.x,m=l.y;u>r!=m>r&&n<(p-d)*(r-u)/(m-u)+d&&(i=!i)}return i}function yL(e,t){return t?vL({x:e.clientX,y:e.clientY},t):!1}function Va(e){return t=>t.pointerType==="mouse"?e(t):void 0}var bL=Wb,_L=xu,wL=Jb,SL=Yb,CL=Mu,NL=Xb,IL=lc,kL=e_,TL=n_,RL=i_,PL=o_,AL=s_,EL=c_,xL=d_,DL=p_,uc="DropdownMenu",[LL,_U]=dt(uc,[Hb]),ft=Hb(),[$L,f_]=LL(uc),h_=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:a,onOpenChange:s,modal:c=!0}=e,l=ft(t),d=q(null),[u,p]=kt({prop:i,defaultProp:a??!1,onChange:s,caller:uc});return o($L,{scope:t,triggerId:ut(),triggerRef:d,contentId:ut(),open:u,onOpenChange:p,onOpenToggle:oe(()=>p(m=>!m),[p]),modal:c,children:o(bL,{...l,open:u,onOpenChange:p,dir:r,modal:c,children:n})})};h_.displayName=uc;var g_="DropdownMenuTrigger",v_=K((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,a=f_(g_,n),s=ft(n);return o(_L,{asChild:!0,...s,children:o(le.button,{type:"button",id:a.triggerId,"aria-haspopup":"menu","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:$o(t,a.triggerRef),onPointerDown:X(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(a.onOpenToggle(),a.open||c.preventDefault())}),onKeyDown:X(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&a.onOpenToggle(),c.key==="ArrowDown"&&a.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});v_.displayName=g_;var ML="DropdownMenuPortal",y_=e=>{const{__scopeDropdownMenu:t,...n}=e,r=ft(t);return o(wL,{...r,...n})};y_.displayName=ML;var b_="DropdownMenuContent",__=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=f_(b_,n),a=ft(n),s=q(!1);return o(SL,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...r,ref:t,onCloseAutoFocus:X(e.onCloseAutoFocus,c=>{s.current||i.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:X(e.onInteractOutside,c=>{const l=c.detail.originalEvent,d=l.button===0&&l.ctrlKey===!0,u=l.button===2||d;(!i.modal||u)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});__.displayName=b_;var jL="DropdownMenuGroup",OL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(CL,{...i,...r,ref:t})});OL.displayName=jL;var FL="DropdownMenuLabel",BL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(NL,{...i,...r,ref:t})});BL.displayName=FL;var UL="DropdownMenuItem",w_=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(IL,{...i,...r,ref:t})});w_.displayName=UL;var qL="DropdownMenuCheckboxItem",GL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(kL,{...i,...r,ref:t})});GL.displayName=qL;var HL="DropdownMenuRadioGroup",KL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(TL,{...i,...r,ref:t})});KL.displayName=HL;var VL="DropdownMenuRadioItem",WL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(RL,{...i,...r,ref:t})});WL.displayName=VL;var zL="DropdownMenuItemIndicator",JL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(PL,{...i,...r,ref:t})});JL.displayName=zL;var YL="DropdownMenuSeparator",XL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(AL,{...i,...r,ref:t})});XL.displayName=YL;var QL="DropdownMenuArrow",ZL=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(EL,{...i,...r,ref:t})});ZL.displayName=QL;var e$="DropdownMenuSubTrigger",t$=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(xL,{...i,...r,ref:t})});t$.displayName=e$;var n$="DropdownMenuSubContent",r$=K((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=ft(n);return o(DL,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});r$.displayName=n$;var i$=h_,a$=v_,o$=y_,s$=__,S_=w_;function c$({assignProjectDisabled:e,disabled:t,onAssignProject:n,onForget:r,title:i}){return v(i$,null,v(a$,{asChild:!0},v("button",{"aria-label":`Actions for ${i}`,className:"feed-menu-trigger",type:"button"},"⋯")),v(o$,null,v(s$,{align:"end",className:"feed-menu-panel",side:"bottom",sideOffset:4},v(S_,{className:"feed-menu-item",disabled:e,onSelect:()=>n()},e?"Moving…":"Assign to project…"),v(S_,{className:"feed-menu-item danger",disabled:t,onSelect:()=>r()},t?"Forgetting…":"Forget memory"))))}function l$({modes:e,active:t,onSelect:n}){return e.length<=1?null:v("div",{className:"feed-toggle"},e.map(r=>v("button",{key:r.id,className:`toggle-button${r.id===t?" active":""}`,"data-filter":r.id,onClick:()=>n(r.id),type:"button"},r.label)))}function Bu({label:e,variant:t=""}){return v(pu,{variant:"provenance",tone:t||void 0},e)}function d$({tag:e}){const t=Wy(e);return t?v(pu,{variant:"tag",title:String(e)},t):null}function u$({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const a=Ws(e?.metadata_json),s=sc(e,a),c=HD(e,a),l=vt(e),d=e.title||"(untitled)",u=s&&a?.request?a.request:d,p=e.created_at||e.created_at_utc,m=Nx(p),f=Dx(e),y=Vs(e.files||[]),g=e.project||"",h=Mx(e),b=jx(e,a),w=String(e.visibility||a?.visibility||"private").trim(),_=String(e.workspace_kind||a?.workspace_kind||"").trim(),I=String(e.origin_source||a?.origin_source||"").trim(),N=String(e.trust_state||a?.trust_state||"").trim(),T=f.length?` · ${f.map(he=>Wy(he)).join(", ")}`:"",x=y.length?` · ${Rx(y)}`:"",j=Number(e.id||0),B=j>0?`ID ${j}`:"",[P,F]=D(S.newItemKeys.has(l)),O=s?GD({...e,metadata_json:a}):null,G=s?null:m0({...e,metadata_json:a}),$=G?f0(G):[],A=G?h0(G):"summary",E=S.itemViewState.get(l),[C,L]=D(G&&E&&$.some(he=>he.id===E)?E:A),U=`${l}:${C}`,[V,de]=D(S.itemExpandState.get(U)===!0),[ie,ne]=D(w==="shared"?"shared":"private"),[Re,ye]=D(!1),[Ce,re]=D(!1),[Pe,ue]=D(!1),H=O?UD(O):[];W(()=>{G&&($.some(he=>he.id===C)||L(A))},[C,A,$,G]),W(()=>{S.itemViewState.set(l,C)},[C,l]),W(()=>{const he=`${l}:${C}`;de(S.itemExpandState.get(he)===!0)},[C,l]),W(()=>{ne(w==="shared"?"shared":"private")},[w]),W(()=>{if(!P)return;const he=window.setTimeout(()=>{S.newItemKeys.delete(l),F(!1)},700);return()=>window.clearTimeout(he)},[P,l]);const fe=ie,ae=fe==="shared"?"This memory can sync to peers allowed by your project filters.":"This memory stays on this device unless a matching local assignment allows it to sync.",Te=[g?`Project ${g}`:"No project",m].filter(Boolean).join(" · "),ce=[_&&_!==w?`Workspace ${_}`:"",I?`From ${I}`:"",b,N&&N!=="trusted"?$x(N):""].filter(Boolean).join(" · "),Be=[`${T}${x}`.trim(),ce].filter(Boolean).join(" · "),Z=!!G&&g0(C,G),te=[C==="facts"?"feed-body facts":"feed-body",Z&&!V?v0(C).join(" "):""].filter(Boolean).join(" "),Qe=s?H.length?v("div",{className:"feed-body facts"},H):qb(String(e.body_text||""))||v("div",{className:"feed-body"}):G?C==="facts"?qD(G.facts)||v("div",{className:te}):qb(C==="narrative"?G.narrative:G.summary,te)||v("div",{className:te}):v("div",{className:"feed-body"});async function $e(he){const bt=fe;ne(he),ye(!0);try{const Nt=await oC(j,he);Nt?.item&&(t(Nt.item),r()),J(he==="shared"?"Memory will now sync as shared context.":"Memory is private again.")}catch(Nt){ne(bt),J(Nt instanceof Error?Nt.message:"Failed to save visibility.","warning")}finally{ye(!1)}}async function an(){const he=String(e.project||"").trim(),bt=he,Nt=String(u||"this memory").trim(),qi=Nt.length>80?`${Nt.slice(0,79).trimEnd()}…`:Nt,yo=he?`Move "${qi}" from "${he}" 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 "${qi}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`;let kn=[];try{kn=(await wo()).filter(_t=>_t&&_t!==he)}catch{}const Wr=await Qd({title:"Assign to project",description:yo,initialValue:bt,placeholder:"Pick one or type a new project name",suggestions:kn,confirmLabel:"Move",cancelLabel:"Cancel",validate:_t=>{const ar=_t.trim();return ar?ar===he?"Already assigned to this project.":null:"Enter a project name."}});if(Wr==null)return;const ir=Wr.trim();if(!(!ir||ir===he)){ue(!0);try{const _t=await sC(j,ir),ar=Number(_t.moved_memory_count||1);J(ar>1?`Moved ${ar} memories from this session to "${_t.project}".`:`Moved to "${_t.project}".`),await i(),r()}catch(_t){J(_t instanceof Error?_t.message:"Failed to move memory.","warning")}finally{ue(!1)}}}async function Nn(){const he=String(u||"this memory").trim();if(await Xt({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${he.length>80?`${he.slice(0,79).trimEnd()}…`:he}". 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"})){re(!0);try{await cC(j),n(j),r(),await i(),J("Memory forgotten and removed from the active feed.")}catch(bt){J(bt instanceof Error?bt.message:"Failed to forget memory.","warning")}finally{re(!1)}}}const yt=c.replace(/_/g," "),In=y.length?v("div",{className:"feed-files"},y.map((he,bt)=>v("span",{className:"feed-file",key:`${String(he)}-${bt}`},String(he)))):null;return v("article",{className:`feed-item ${c}${P?" new-item":""}`.trim(),"data-key":l},v("div",{className:"feed-kind-banner"},v(pu,{variant:"kind",tone:c},yt)),v("div",{className:"feed-card-body"},v("div",{className:"feed-card-header"},v("div",{className:"feed-header"},v("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:XT(u,S.feedQuery)}}),v("div",{className:"feed-card-subtitle small"},Te)),v("div",{className:"feed-actions"},G?v(l$,{active:C,modes:$,onSelect:he=>L(he)}):null,v(Qs,{label:Cx(p),side:"left"},v("div",{className:"small feed-age"},m)),e.owned_by_self&&j>0?v(c$,{assignProjectDisabled:Pe,disabled:Ce,onAssignProject:()=>{an()},onForget:()=>{Nn()},title:String(u||"memory")}):null)),v("div",{className:"feed-provenance"},v(Bu,{label:h,variant:h==="You"?"mine":"author"}),v(Bu,{label:w||"private",variant:w||"private"}),B?v(Qs,{label:`Memory database id ${j}`,side:"top"},v(Bu,{label:B,variant:"memory-id"})):null),v("div",{className:"feed-meta"},Be||"No tags, files, or provenance details attached."),Qe,v("div",{className:"feed-footer"},v("div",{className:"feed-footer-left"},f.length?v("div",{className:"feed-tags"},f.map((he,bt)=>v(d$,{key:`${String(he)}-${bt}`,tag:he}))):null,e.owned_by_self&&j>0?v("div",{className:"feed-visibility-controls"},v("select",{"aria-label":`Visibility for ${String(e.title||"memory")}`,className:"feed-visibility-select",disabled:Re,onChange:he=>{$e(String(he.currentTarget.value)==="shared"?"shared":"private")},value:fe},v("option",{value:"private"},"Only me"),v("option",{value:"shared"},"Share with peers")),v("div",{className:"feed-visibility-note"},ae)):null),v("div",{className:"feed-footer-right"},Z?v("button",{className:"feed-expand",onClick:()=>{const he=!V;S.itemExpandState.set(U,he),de(he)},type:"button"},V?"Collapse":"Expand"):null)),In))}function p$({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return v("div",{className:"feed-skeleton-item","aria-hidden":"true"},v("div",{className:"feed-skeleton-banner"}),v("div",{className:"feed-skeleton-body"},v("div",{className:`feed-skeleton-line ${n}`}),v("div",{className:`feed-skeleton-line ${r}`}),v("div",{className:"feed-skeleton-footer"},v("div",{className:"feed-skeleton-chip w-36"}),v("div",{className:"feed-skeleton-chip w-56"}),v("div",{className:"feed-skeleton-chip"}))))}function m$({items:e,loadingText:t,ops:n}){if(t)return v("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>v(p$,{index:r,key:`skeleton-${r}`})));if(!e.length){const r=!!S.feedQuery.trim()||S.feedTypeFilter!=="all"||S.feedScopeFilter!=="all";return v("div",{className:"small feed-empty-state"},v("strong",null,r?"No memories match the current filters.":"No memories yet."),v("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 v(z,null,e.map(r=>v(u$,{item:r,key:vt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData})))}function C_({id:e,active:t,options:n,onSelect:r}){return v("div",{className:"feed-toggle",id:e},n.map(({value:i,label:a})=>{const s=i===t;return v("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},a)}))}function f$({text:e}){return v("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function h$({query:e,onQuery:t}){return v("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 g$({errorText:e,items:t,loadingText:n,ops:r}){const[i,a]=D(!1);return v(z,null,v("div",{className:"feed-controls"},v(f$,{text:n||y0(t.length,r.hasMorePages())}),v("div",{className:"feed-controls-right"},v(h$,{query:S.feedQuery,onQuery:r.updateFeedQuery}),v(C_,{active:S.feedScopeFilter,id:"feedScopeToggle",onSelect:s=>{s!==S.feedScopeFilter&&(Sg(s),r.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),v(C_,{active:S.feedTypeFilter,id:"feedTypeToggle",onSelect:s=>{s!==S.feedTypeFilter&&(dR(s),r.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),v("button",{"aria-controls":"contextInspectorPanel","aria-expanded":i,className:"settings-button feed-inspector-button",onClick:()=>a(s=>!s),type:"button"},i?"Hide Context Inspector":"Context Inspector"))),v(b0,{open:i}),v("div",{className:"feed-list",id:"feedList"},v(z,null,e?v("div",{className:"small feed-empty-state",role:"alert"},v("strong",null,e),v("div",null,"Check the viewer connection, then retry the Feed."),v("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null,!e||t.length>0?v(m$,{items:t,loadingText:n,ops:r}):null)))}function v$(e){return S.feedTypeFilter==="observations"?e.filter(t=>!sc(t,Ws(t?.metadata_json))):S.feedTypeFilter==="summaries"?e.filter(t=>sc(t,Ws(t?.metadata_json))):e}function y$(e){const t=e.map(n=>`${Yy(n)}:${n.kind||""}:${n.created_at_utc||n.created_at||""}`);return`${S.feedTypeFilter}|${S.feedScopeFilter}|${S.currentProject}|${Ea(S.feedQuery)}|${t.join("|")}`}var N_="",Wa=0,za=0,Pi=!0,Ai=!0,pc=null,b$=0,Rt=null,I_=!1,Ei=0,Uu="all",k_="",Ja=null,xi="",wU=250;function T_(e){N_=e,Uu=S.feedScopeFilter,k_=S.feedQuery.trim(),xi="",Ei+=1,Wa=0,za=0,Pi=!0,Ai=!0,S.lastFeedItems=[],S.pendingFeedItems=null,S.lastFeedFilteredCount=0,S.lastFeedSignature="",S.newItemKeys.clear(),S.itemViewState.clear(),S.itemExpandState.clear()}function qu(){return Pi||Ai}function _$(e){const t=vt(e);S.lastFeedItems=S.lastFeedItems.map(n=>vt(n)===t?e:n)}function w$(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(vt(r)),i};S.lastFeedItems=S.lastFeedItems.filter(n),Array.isArray(S.pendingFeedItems)&&(S.pendingFeedItems=S.pendingFeedItems.filter(n));for(const r of t){S.newItemKeys.delete(r),S.itemViewState.delete(r);for(const i of Array.from(S.itemExpandState.keys()))i.startsWith(`${r}:`)&&S.itemExpandState.delete(i)}}async function S$(){if(!qu())return;const e=Ei;if(pc===e)return;const t=S.currentProject||"",n=S.feedQuery.trim(),r=Wa,i=za;pc=e;try{const[a,s]=await Promise.all([Pi?mm(t,{limit:20,offset:r,scope:S.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),Ai?fm(t,{limit:50,offset:i,scope:S.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==Ei||t!==(S.currentProject||"")||n!==S.feedQuery.trim())return;const c=s.items||[],l=a.items||[],d=n?l:l.filter(p=>!Jy(p));S.lastFeedFilteredCount+=l.length-d.length,Ai=zs(s,c.length,50),Pi=zs(a,l.length,20),za=Js(s,i+c.length),Wa=Js(a,r+l.length);const u=[...c,...d];S.lastFeedItems=Xy(S.lastFeedItems,u),Mr()}finally{pc===e&&(pc=null)}}function R_(){S.activeTab==="feed"&&(Ja||Rt||qu()&&Fx()&&S$())}var C$={replaceFeedItem:_$,removeFeedItem:w$,updateFeedView:e=>Mr(e),loadFeedData:()=>Ku(),updateFeedQuery:e=>I$(e),hasMorePages:qu};function Gu(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;d0(n,v(g$,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:C$}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Hu(e="Loading selected project..."){Gu([],{loadingText:e})}function N$(){l0(),Gu(S.lastFeedItems,S.lastFeedItems.length||S.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),I_||(window.addEventListener("scroll",()=>{R_()},{passive:!0}),I_=!0)}function I$(e){if(e===S.feedQuery)return;const t=S.feedQuery.trim();S.feedQuery=e,e.trim()!==t&&(T_(S.currentProject||""),Hu("Searching memories…"),Ja&&clearTimeout(Ja),Ja=setTimeout(()=>{Ja=null,Ku().catch(()=>{})},250))}function Mr(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=v$(S.lastFeedItems),r=y$(n),i=e||r!==S.lastFeedSignature;S.lastFeedSignature=r,i&&Gu(n,{errorText:xi||void 0}),window.scrollTo({top:t}),R_()}async function Ku(){const e=S.currentProject||"",t=S.feedScopeFilter!==Uu,n=S.feedQuery.trim(),r=n!==k_;(e!==N_||t||r)&&(T_(e),Hu(r?"Searching memories…":void 0));const i=Ei,a=++b$;Rt={generation:i,requestId:a};const s=!!xi;s&&(xi="",S.lastFeedItems.length>0?Mr(!0):Hu(n?"Searching memories…":void 0));try{const[d,u]=await Promise.all([mm(e,{limit:20,offset:0,scope:S.feedScopeFilter,q:n||void 0}),fm(e,{limit:50,offset:0,scope:S.feedScopeFilter,q:n||void 0})]);if(Rt?.generation!==i||Rt.requestId!==a||i!==Ei||e!==(S.currentProject||"")||n!==S.feedQuery.trim())return;const p=u.items||[],m=d.items||[],f=n?m:m.filter(w=>!Jy(w)),y=m.length-f.length,g=[...p,...f].sort((w,_)=>new Date(_.created_at||0).getTime()-new Date(w.created_at||0).getTime()),h=Ox(S.lastFeedItems,g),b=S.lastFeedItems;if(Bx(h,b)&&b.length>0){const w=new Set(b.map(vt));h.forEach(_=>{w.has(vt(_))||S.newItemKeys.add(vt(_))})}S.pendingFeedItems=null,S.lastFeedItems=h,xi="",S.lastFeedFilteredCount=Math.max(S.lastFeedFilteredCount,y),Ai=zs(u,p.length,50),Pi=zs(d,m.length,20),za=Math.max(za,Js(u,p.length)),Wa=Math.max(Wa,Js(d,m.length)),Uu=S.feedScopeFilter,Rt?.generation===i&&Rt.requestId===a&&(Rt=null),Mr(s)}catch(c){throw Rt?.generation===i&&Rt.requestId===a&&i===Ei&&e===(S.currentProject||"")&&n===S.feedQuery.trim()&&(Pi=!1,Ai=!1,xi="Feed unavailable. Refresh and try again.",Mr(!0)),c}finally{Rt?.generation===i&&Rt.requestId===a&&(Rt=null)}}var k$=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function P_(e){return!!k$.exec(e)?.slice(1,4).map(Number).every(Number.isSafeInteger)}function SU(e){return e}function T$(e){return e.latest_version?e.stale?{title:e.update_available?`Cached update status: Codemem ${e.latest_version} is available`:`Cached update status for Codemem ${e.current_version}`,detail:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale.",tone:"stale"}:e.update_available?{title:`Codemem ${e.latest_version} is available`,detail:`Installed version: ${e.current_version}.`,tone:"available"}:P_(e.current_version)?{title:`Codemem ${e.current_version} is up to date`,detail:"You are running the latest stable release.",tone:"current"}:{title:`Unable to compare Codemem ${e.current_version} with ${e.latest_version}`,detail:"The installed version is not a stable semantic version.",tone:"unavailable"}:{title:"Update check unavailable",detail:e.error?`Could not check for updates: ${e.error}`:"Could not check for updates.",tone:"unavailable"}}function R$({status:e}){const t=T$(e),n=e.update_available||e.stale||!e.latest_version||!P_(e.current_version);return v("section",{class:`health-update-banner health-update-banner--${t.tone}`,role:"status","aria-atomic":"true","aria-label":"Codemem update status"},v("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),v("div",{class:"health-update-copy"},v("h2",null,t.title),v("p",null,t.detail),n&&e.recommended_action?v("p",{class:"health-update-guidance"},v("span",{class:"health-update-guidance-label"},"Recommended action"),v("code",null,e.recommended_action)):null))}function P$(e,t){e&&(e.hidden=!t,He(t?v(R$,{status:t}):null,e))}function A$({label:e,value:t,detail:n,icon:r,className:i,title:a}){const s=v("div",{class:`stat${i?` ${i}`:""}`,style:a?"cursor: help;":void 0},r?v("i",{"data-lucide":r,class:"stat-icon"}):null,v("div",{class:"stat-content"},v("div",{class:"value"},t),v("div",{class:"label"},e),n?v("div",{class:"small"},n):null));return a?v(Qs,{label:a},s):s}function E$({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action()}catch{}t.disabled=!1,t.textContent=r}}function a(){!e.command||!n||ma(e.command,n)}return v("div",{class:"health-action"},v("div",{class:"health-action-text"},e.label,e.command?v("span",{class:"health-action-command"},e.command):null),v("div",{class:"health-action-buttons"},e.action?v("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?v("button",{class:"settings-button health-action-copy",onClick:a,ref:s=>{n=s}},"Copy"):null))}function x$(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function D$({label:e,value:t,icon:n,tooltip:r}){const i=v("div",{class:"stat",style:r?"cursor: help;":void 0},v("i",{"data-lucide":n,class:"stat-icon"}),v("div",{class:"stat-content"},v("div",{class:"value"},x$(t)),v("div",{class:"label"},e)));return r?v(Qs,{label:r},i):i}function A_(e,t){e&&He(v(du,null,t.map(n=>v(D$,{...n,key:`${n.label}-${n.icon}`}))),e)}function E_(e,t){e&&He(v(z,null,t),e)}function Vu(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function L$(e,t){e&&He(v(du,null,t.map(n=>v(A$,{...n,key:n.key??n.label}))),e)}function $$(e,t){if(e){if(!t.length){e.hidden=!0,He(null,e);return}e.hidden=!1,He(v(z,null,t.slice(0,3).map((n,r)=>v(E$,{item:n,key:`${n.label}-${r}`}))),e)}}var x_="scope_id_backfill";function D_(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthMeta"),n=document.getElementById("healthActions"),r=document.getElementById("healthDot");if(!e||!t)return;P$(document.getElementById("healthUpdateBanner"),S.lastUpdateStatus);const i=S.lastStatsPayload||{},a=S.lastUsagePayload||{},s=S.lastRawEventsPayload&&typeof S.lastRawEventsPayload=="object"?S.lastRawEventsPayload:{},c=S.lastSyncStatus||{},l=Array.isArray(i.maintenance_jobs)?i.maintenance_jobs:[],d=l.find(ce=>ce.kind===x_),u=i.reliability||{},p=u.counts||{},m=u.rates||{},f=i.database||{},y=a.totals_filtered||a.totals||a.totals_global||i.usage?.totals||{},g=Array.isArray(a.recent_packs)?a.recent_packs:[],h=g.length?g[0]?.created_at:null,b=g.length?g[0]?.metadata_json||{}:{},w=Number(b?.exact_duplicates_collapsed||0),_=Number(s.pending||0),I=Number(p.errored_batches||0),N=Number(m.flush_success_rate??1),T=Number(m.dropped_event_rate||0),x=au(y.tokens_saved,y.tokens_read),j=kx(x),B=Number(f.tags_coverage||0),P=String(c.daemon_state||"unknown"),F=P==="offline-peers"?"Offline peers":P==="needs_attention"?"Needs attention":P==="rebootstrapping"?"Rebootstrapping":Vy(P),O=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers.length:0,G=P==="disabled"||c.enabled===!1,$=P==="offline-peers",A=!G&&O===0;let E=G?"Disabled":A?"No peers":F;const C=Ci(c.last_sync_at||c.last_sync_at_utc||null),L=Ci(h),U=C!==null&&C>7200,V=C!==null&&C<=300,de=_>=200;let ie=0;const ne=[];_>=1e3?(ie+=40,ne.push("high raw-event backlog")):_>=200&&(ie+=24,ne.push("growing raw-event backlog")),I>0&&_>=200&&(ie+=I>=5?10:6,ne.push("batch errors during backlog pressure")),N<.95&&(ie+=20,ne.push("lower flush success")),T>.02?(ie+=24,ne.push("high dropped-event rate")):T>.005&&(ie+=10,ne.push("non-trivial dropped-event rate")),!G&&!A&&(P==="error"?(ie+=36,ne.push("sync daemon reports errors")):P==="needs_attention"?(ie+=40,ne.push("sync needs manual attention")):P==="stopped"?(ie+=22,ne.push("sync daemon stopped")):P==="degraded"&&!V&&(ie+=20,ne.push("sync daemon degraded")),$?(ie+=4,ne.push("all peers currently offline"),U&&(ie+=4,ne.push("offline peers and sync not recent"))):U?(ie+=26,ne.push("sync looks stale")):C!==null&&C>1800&&(ie+=12,ne.push("sync not recent"))),j!==null&&j<10&&(ie+=8,ne.push("low retrieval reduction")),L!==null&&L>86400&&(ie+=12,ne.push("memory pack activity is old"));let Re="Healthy",ye="status-healthy";ie>=60?(Re="Attention",ye="status-attention"):ie>=25&&(Re="Degraded",ye="status-degraded");const Ce=ye==="status-healthy";r&&(r.className=`health-dot ${ye}`,r.title=Re);const re=`${Number(y.tokens_saved||0).toLocaleString()} saved tokens · ${w.toLocaleString()} deduped in latest pack`,Pe=_>0?"Queue is actively draining":"Queue is clear",ue=G?"Sync disabled":A?"No peers configured":$?`${O} peers offline · last sync ${Kn(C)} ago`:`${O} peers · last sync ${Kn(C)} ago`;Ce&&!G&&!A&&($?E="Peers offline":P==="degraded"&&V&&(E="Syncing"));const H=`last pack ${Kn(L)} ago`,fe=l.map(ce=>{const Be=Number(ce.progress?.current||0),Z=typeof ce.progress?.total=="number"?ce.progress.total:null,te=String(ce.progress?.unit||"items"),Qe=Z&&Z>0?` (${Math.round(100*Be/Z)}%)`:"",$e=Z&&Z>0?`${Be.toLocaleString()}/${Z.toLocaleString()} ${te}${Qe}`:`${Be.toLocaleString()} ${te}`,an=ce.status==="failed",Nn=ce.status==="completed",yt=ce.kind===x_,In=an?"Failed":Nn?"Complete":$e,he=an?String(ce.error||"unknown error").trim():Nn?yt?`${$e} · one-time Sharing-domain upgrade finished`:$e:yt?"One-time upgrade backfill; totals include memories and replication ops":void 0;return{key:String(ce.kind||ce.title||"background-maintenance"),label:String(ce.title||ce.kind||"Background maintenance"),value:In,detail:he,icon:an?"alert-triangle":Nn?"check-circle":"loader",className:an?"status-attention":void 0,title:an?`Error: ${ce.error||"unknown"}`:Nn?`${String(ce.title||"Maintenance")} finished`:yt?`${String(ce.title||"Maintenance")} in progress; inspect with codemem maintenance status`:`${String(ce.title||"Maintenance")} in progress`}});L$(e,[{key:"overall-health",label:"Overall health",value:Re,detail:`Weighted score ${ie}`,icon:"heart-pulse",className:`health-primary ${ye}`,title:ne.length?`Main signals: ${ne.join(", ")}`:"No major risk signals detected"},...fe,{key:"pipeline-health",label:"Pipeline health",value:`${_.toLocaleString()} pending`,detail:Pe,icon:"workflow",title:"Raw-event queue pressure and flush reliability"},{key:"retrieval-impact",label:"Retrieval impact",value:x,detail:re,icon:"sparkles",title:"Reduction from memory reuse across recent usage"},{key:"sync-health",label:"Sync health",value:E,detail:ue,icon:"refresh-cw",title:"Daemon state and sync recency"},{key:"data-freshness",label:"Data freshness",value:Kn(L),detail:H,icon:"clock-3",title:"Recency of last memory pack activity"}]);const ae=async()=>{await Zc()},Te=[];de?(Te.push({label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status"}),Te.push({label:"Then retry failed batches for impacted sessions.",command:"codemem db raw-events-retry <opencode_session_id>"})):P==="stopped"?Te.push({label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}):!G&&!A&&!Ce&&(P==="error"||P==="degraded")?(Te.push({label:"Sync is unhealthy. Restart and run one immediate pass.",command:"codemem serve restart",action:ae,actionLabel:"Sync now"}),Te.push({label:"Then run doctor to see root cause details.",command:"codemem sync doctor"})):!G&&!A&&U&&Te.push({label:"Sync is stale. Run one immediate sync pass.",command:"codemem sync once",action:ae,actionLabel:"Sync now"}),B>0&&B<.7&&Te.length<2&&Te.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"}),d&&d.status!=="completed"&&Te.length<3&&Te.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),$$(n,Te),t.textContent=ne.length?`Why this status: ${ne.join(", ")}.`:"Healthy right now. Diagnostics stay available if you want details.",Vu()}function M$(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=S.lastUsagePayload||{},r=S.currentProject;n?.totals_global||n?.totals;const i=n?.totals_filtered||null,a=!!(r&&i),s=(Array.isArray(n?.events)?n.events:[]).find(N=>N.event==="pack")||null,c=Array.isArray(n?.recent_packs)?n.recent_packs:[],l=c.length?c[0]:null,d=l?.metadata_json||{},u=l?.created_at||"",p=Number(s?.count||0),m=Number(l?.tokens_read||0),f=Number(l?.tokens_saved||0),y=Number(d?.exact_duplicates_collapsed||0),g=!!d?.exact_dedupe_enabled,h=au(f,m),b=p?`${p} packs`:"No packs yet",w=u?`Last pack: ${Ar(u)}`:"",_=a?"Project":"All projects",I=[{label:"Last pack savings",value:l?`${Aa(f)} (${h})`:"n/a",tooltip:l?`Exact: ${f.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:l?Aa(m):"n/a",tooltip:l?`Exact: ${m.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:l?y.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"}];E_(t,[_,b,w].filter(Boolean).join(" · ")),A_(e,I),Vu()}function j$(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=S.lastStatsPayload||{},r=S.lastUsagePayload||{},i=S.lastRawEventsPayload&&typeof S.lastRawEventsPayload=="object"?S.lastRawEventsPayload:{},a=n.database||{},s=S.currentProject,c=r?.totals_global||r?.totals||n.usage?.totals||{},l=r?.totals_filtered||null,d=!!(s&&l),u=d?l:c,p=Number(i.sessions||0),m=Number(i.pending||0),f=d?`
|
|
112
|
+
Global: ${Number(c.work_investment_tokens||0).toLocaleString()} invested`:"",y=d?`
|
|
113
|
+
Global: ${Number(c.tokens_read||0).toLocaleString()} read`:"",g=d?`
|
|
114
|
+
Global: ${Number(c.tokens_saved||0).toLocaleString()} saved`:"",h=[{label:d?"Savings (project)":"Savings",value:Aa(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:Aa(u.tokens_read||0),tooltip:`Tokens injected into context (pack size). Exact: ${Number(u.tokens_read||0).toLocaleString()} injected${y}`,icon:"book-open"},{label:d?"Reduction (project)":"Reduction",value:au(u.tokens_saved,u.tokens_read),tooltip:`Percent reduction from reuse. Factor: ${Ix(u.tokens_saved,u.tokens_read)}.`+y+g,icon:"percent"},{label:d?"Work investment (project)":"Work investment",value:Aa(u.work_investment_tokens||0),tooltip:`Token cost of unique discovery groups. Exact: ${Number(u.work_investment_tokens||0).toLocaleString()} invested${f}`,icon:"pencil"},{label:"Active memories",value:a.active_memory_items||0,icon:"check-circle"},{label:"Embedding coverage",value:Ky(a.vector_coverage),tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:Ky(a.tags_coverage),tooltip:"Share of active memories with tags",icon:"tag"}];if(m>0?h.push({label:"Raw events pending",value:m,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"}),A_(e,h),t){const b=s?` · project: ${s}`:"";E_(t,`DB: ${Px(a.path||"unknown")} · ${Ax(a.size_bytes||0)}${b}`)}Vu()}async function O$(){const e=S.lastStatsPayload?.identity?.actor_id||null,t=S.activeTab==="health"&&!S.lastUpdateStatus?lN().catch(dN):Promise.resolve(S.lastUpdateStatus),[n,r,i,a,s]=await Promise.all([pC(),mC(S.currentProject),fC(S.currentProject),hC(S.currentProject),t]);S.lastStatsPayload=n||{},S.lastUsagePayload=r||{},S.lastRawEventsPayload=a||{},S.lastUpdateStatus=s;const c=S.lastStatsPayload?.identity?.actor_id||null;j$(),M$(),D_(),S.activeTab==="feed"&&e!==c&&Mr(!0)}function Wu(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function L_(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function $_(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var F$={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 B$(e){return e.targetIdentityRef??e.existingIdentityRef??""}function U$({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:a,index:s,onAssign:c,onClear:l,onDecision:d}){const u=ur(),p=`${u}-identity`,m=`${u}-evidence`,f=`${u}-assignment-help`,y=B$(a),g=a.targetIdentityRef??"",[h,b]=D(y);W(()=>b(y),[y]);const w=i.identityChoices.some(L=>L.identityRef===h),_=M_(i,a.existingIdentityRef),I=M_(i,a.suggestedIdentityRef),N=n?.has(a.deviceRef)??!1,T=e||N||r,x=T||!a.actions.assignIdentity.enabled,j=a.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",B=!!h&&!w,P=!a.actions.include.enabled||j||B||!g||h!==g,F=T||P,O=x||!h||j||B||h===g,G=!a.enabled||P,$=e?t:N?Wu("device",a.deviceRef):void 0,A=[m,G?f:void 0,$].filter(Boolean).join(" "),E=[m,$].filter(Boolean).join(" "),C=a.decision==="unresolved";return o("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-device-row${C?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-device-row-${s}`,tabIndex:C?-1:void 0,children:[o("legend",{children:a.displayName}),C?o("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,o("div",{className:"small legacy-team-device-evidence",id:m,children:[o("span",{children:a.enabled?"Current Team device":"Device no longer active on this Team"}),_?o("span",{children:["Current assignment: ",_,a.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!_&&I?o("span",{children:["Suggested person: ",I]}):null,o("span",{children:["Decision: ",F$[a.decision]]})]}),o("label",{htmlFor:p,children:"Person using this device"}),o("select",{"aria-describedby":A,className:"feed-search legacy-team-device-select",disabled:x,id:p,onChange:L=>b(L.currentTarget.value),value:h,children:[o("option",{value:"",children:"Choose a person"}),h&&!w?o("option",{value:h,children:"Current server assignment"}):null,i.identityChoices.map(L=>o("option",{value:L.identityRef,children:L.displayName},L.identityRef))]}),a.enabled?B?o("p",{className:"small",id:f,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):j?o("p",{className:"small",id:f,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!h||!g||h!==g?o("p",{className:"small",id:f,children:h?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:o("p",{className:"small",id:f,children:"Inactive devices can only be removed from this Team."}),o("div",{className:"legacy-team-device-actions",children:[o("button",{"aria-describedby":A,"aria-disabled":O?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{O||c(a,h)},type:"button",children:"Save assignment"}),a.enabled?o(z,{children:[o("button",{"aria-describedby":A,"aria-disabled":F?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{F||d(a,"included",g)},type:"button",children:"Include"}),o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.exclude.enabled&&d(a,"excluded")},type:"button",children:"Exclude"})]}):o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.remove.enabled&&d(a,"removed")},type:"button",children:"Remove"}),a.decision!=="unresolved"?o("button",{"aria-describedby":E,"aria-disabled":T||!a.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&a.actions.clearDecision.enabled&&l(a)},type:"button",children:"Clear decision"}):null]})]})}function q$(e){const t=L_(e.detail.devices);return o("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[o("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),o("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),o("div",{className:"legacy-team-device-list",children:t.map((n,r)=>v(U$,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function G$(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function H$({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:a,presentationName:s,project:c}){const l=ur(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",m=vr(c.mappingChoices.map(A=>({canonicalId:A.resolvedProjectRef,displayName:A.displayName}))),f=[...new Set(c.mappingChoices.map(A=>A.resolvedProjectRef))],y=[...f].sort((A,E)=>A<E?-1:A>E?1:0),g=new Map(y.map((A,E)=>[A,`project-choice-${E+1}`])),h=new Map(c.mappingChoices.map(A=>[A.resolvedProjectRef,A])),b=f.flatMap(A=>{const E=h.get(A);return E?[{...E,label:m.get(A)??E.displayName,token:g.get(A)??""}]:[]}),w=b.find(A=>A.resolvedProjectRef===p)?.token??"",_=JSON.stringify(y),[I,N]=D(w);W(()=>N(w),[w,_]);const T=b.find(A=>A.token===I)?.resolvedProjectRef,x=n?.has(c.projectRef)??!1,j=c.actions.map.blockedReason==="mapping_unavailable",B=c.actions.map.enabled&&!I,P=e||x||r||!c.actions.map.enabled,F=P||!T||T===p,O=G$(c,m),G=[j||B?u:void 0,e?t:x?Wu("project",c.projectRef):void 0].filter(Boolean).join(" "),$=c.resolution==="unresolved";return o("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${$?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:$?-1:void 0,children:[o("legend",{children:s}),o("div",{className:"legacy-team-project-row-content",children:[$?o("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?o("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):o(z,{children:[o("p",{className:"small",children:O?`Saved mapping: ${O}`:"This Project still needs a mapping."}),o("label",{htmlFor:d,children:"Canonical Project"}),o("select",{"aria-describedby":G||void 0,className:"feed-search legacy-team-project-select",disabled:P,id:d,onChange:A=>N(A.currentTarget.value),value:I,children:[o("option",{value:"",children:"Choose a Project"}),b.map(A=>o("option",{value:A.token,children:A.label},A.resolvedProjectRef))]}),j?o("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):B?o("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,o("button",{"aria-describedby":G||void 0,"aria-disabled":F?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!F&&T&&a(c,T)},type:"button",children:"Save mapping"})]})]})]})}function K$(e){const t=$_(e.detail.projects),n=vr(t.map(a=>({canonicalId:a.projectRef,displayName:a.displayName}))),r=e.detail.projects.filter(a=>a.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return o("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[o("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),o("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?o("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,o("div",{className:"legacy-team-project-list",children:t.map((a,s)=>o(H$,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(a.projectRef),index:s,onMap:e.onMap,presentationName:n.get(a.projectRef)??a.displayName,project:a},a.projectRef))}),e.detail.unresolvedProjectCount===0?o("div",{className:"legacy-team-setup-next-action",children:[o("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),o("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 Ya={add:"Add",update:"Update",remove:"Remove"},V$=10;function it(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function zu(e,t,n,r){const i=new Map;for(const a of e){const s=t(a),c=r(a),l=`${c}:${ra(s)}`,d=n(a),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 Ju(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${it(e.projectRefs.size,t)}`:e.displayName}function Xa({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const a=!!(r&&r.length<n.length),s=a&&n.length>V$;return o("section",{children:[o("h4",{children:i}),n.length>0?o(z,{children:[a&&r?o("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>o("li",{children:c},`${i}-summary-${l}`))}):null,s?o("details",{children:[o("summary",{children:["Show all ",it(n.length,`exact ${t}`)]}),o(j_,{items:n,title:i})]}):o(j_,{items:n,title:i})]}):o("p",{className:"small",children:e})]})}function j_({items:e,title:t}){return o("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>o("li",{children:n},`${t}-${r}`))})}function W$({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const a=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=D(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),m=a.teamChanges.map(C=>{const L=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Ya[C.change]} ${C.teamDisplayName}: change device access from ${L} to the reviewed device list.`}),f=a.membershipChanges.map(C=>`${Ya[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),y=vr([...n.projects.map(C=>({canonicalId:C.projectRef,displayName:C.displayName})),...a.projectChanges.map(C=>({canonicalId:C.projectRef,displayName:C.projectDisplayName}))]),g=a.projectChanges.flatMap(C=>[...C.fromResolvedProjectRef&&C.fromResolvedProjectDisplayName?[{canonicalProjectRef:C.fromCanonicalProjectRef,resolvedProjectRef:C.fromResolvedProjectRef,displayName:C.fromResolvedProjectDisplayName}]:[],...C.toResolvedProjectRef&&C.toResolvedProjectDisplayName?[{canonicalProjectRef:C.toCanonicalProjectRef,resolvedProjectRef:C.toResolvedProjectRef,displayName:C.toResolvedProjectDisplayName}]:[]]),h=vr(g.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),b=new Map(g.map(C=>[C.resolvedProjectRef,h.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),w=vr([...n.projects.flatMap(C=>C.canonicalProjectRef?[{canonicalId:C.canonicalProjectRef,displayName:C.displayName}]:[]),...[...a.recipientChanges,...a.deviceAccessChanges].filter(C=>C.canonicalProjectKind==="project").map(C=>({canonicalId:C.canonicalProjectRef,displayName:C.canonicalProjectDisplayName}))]),_=a.projectChanges.map(C=>`${Ya[C.change]} ${y.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?b.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?b.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),I=a.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${Ya[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${w.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),N=a.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${Ya[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${w.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),T=a.teamChanges.length+a.membershipChanges.length+a.projectChanges.length+a.recipientChanges.length+a.deviceAccessChanges.length,x=zu(a.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),j=zu(a.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),B=zu(a.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),P=n.devices.filter(C=>C.decision==="included").length,F=[it(a.teamChanges.length,"Team policy change"),it(a.membershipChanges.length,"membership change"),it(a.projectChanges.length,"Project change"),it(a.recipientChanges.length,"recipient change"),it(a.deviceAccessChanges.length,"device-access change")],O=`${it(n.projects.length,"Project")} included; ${it(P,"included device")}.`,G=Math.max(n.candidate.projectCount,n.projects.length),$=new Set(a.deviceAccessChanges.map(C=>C.deviceRef)).size,A=[...a.teamChanges,...a.membershipChanges,...a.projectChanges,...a.recipientChanges,...a.deviceAccessChanges].filter(C=>C.change==="remove").length,E=a.teamChanges.length===0&&a.membershipChanges.length===0&&a.projectChanges.length===0&&a.recipientChanges.length>0&&a.recipientChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")&&a.deviceAccessChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")?`No new access will be added. This removes legacy default sharing for ${n.candidate.displayName}.${$>0?` ${it($,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${it(G,"reviewed Project")}.`:`${it(T,"server-confirmed access change")} will be applied atomically; ${it(A,"removal")} ${A===1?"is":"are"} included.`;return o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:"Review every server-confirmed access change before activating this Team."}),o("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[o("p",{className:"legacy-team-setup-net-effect",children:[o("strong",{children:"Net effect:"})," ",E]}),o("p",{children:[o("strong",{children:it(T,"exact access change")})," to review."]}),o("ul",{children:F.map(C=>o("li",{children:C},C))}),o("p",{className:"small",children:["Scope: ",O]})]}),o("div",{className:"legacy-team-setup-delta",children:[o(Xa,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:m,title:"Team policy"}),o(Xa,{empty:"No membership changes.",exactItemName:"membership change",exactItems:f,title:"Memberships"}),o(Xa,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:_,summaryItems:x.map(C=>`${Ju(C,"reviewed Project")}, ${it(C.changeCount,"Project change")}`),title:"Projects"}),o(Xa,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:I,summaryItems:j.map(C=>`${Ju(C,"canonical Project")}, ${it(C.changeCount,"recipient change")}`),title:"Recipients"}),o(Xa,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:N,summaryItems:B.map(C=>`${Ju(C,"canonical Project")}, ${it(C.changeCount,"device-access change")}`),title:"Device access"})]}),o("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[o("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:C=>{e&&C.preventDefault()},onChange:C=>{if(e){C.currentTarget.checked=d;return}l(C.currentTarget.checked?s:null)},type:"checkbox"}),o("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?o("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[o("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,o("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 z$(e){let t=null;return async n=>{try{const r=await J$(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){const i=await Y$(n,e,r);return{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...i?{recoveredView:i}:{}}}}}async function J$(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 a=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:a});try{await a}finally{n()?.promise===a&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function Y$(e,t,n){if(!(e.kind==="load"||e.kind==="completion_refresh")&&!(!(n instanceof cr)||!Yu(n.errorCode)))return t.loadDetail(e.candidateRef).catch(()=>{})}function Yu(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function O_(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function X$(e,t,n){return B_(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function F_(e,t){return B_(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function B_(e,t){return{id:e,targetId:t}}var U_="Team setup changed since it was last reviewed. Reload the latest details to continue.",q_="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",Q$="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.";function Z$(){return{status:"closed",generation:0}}function Xu(e,t){switch(t.type){case"open":return e.status==="open"&&wn(e)?e:eM(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&wn(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 tM(e,t.step);case"blocked_navigation":return mc(e,t.step,t.message);case"retry":return nM(e);case"refresh":return iM(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Qu(e,t,"assign_device");case"decide_device":return Qu(e,t,"decide_device");case"clear_device":return Qu(e,t,"clear_device");case"map_project":return rM(e,t);case"finish":return aM(e);case"command_started":return hM(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return oM(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function eM(e,t){return Yn({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 tM(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return mc(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return mc(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return mc(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:O_(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function mc(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?L_(e.view.devices).findIndex(i=>i.decision==="unresolved"):$_(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:X$(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function nM(e){if(e.status!=="open"||e.step==="completed"||Qa(e)||wn(e))return e;const t=fc(e)?.retry??e.errors.find(n=>n.retry)?.retry??"load";return Yn(e,{kind:"load",candidateRef:e.candidateRef,refresh:t==="refresh",focusOnOutcome:!0})}function Qu(e,t,n){if(e.status!=="open"||e.step==="completed"||!Zu(e.view)||fc(e)||Qa(e)||wn(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},a=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(!a||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 Yn(jr(e,{kind:"device",itemRef:t.deviceRef}),a,s)}function rM(e,t){if(e.status!=="open"||e.step==="completed"||!Zu(e.view)||fc(e)||Qa(e)||wn(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:Yn(jr(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 iM(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Qa(e)||wn(e)?e:Yn(jr(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function aM(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:Yn(jr(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 Yn(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 oM(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"?cM(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?lM(r,n.attemptId):t.view?G_({...fM(r,n),message:sM(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function sM(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 cM(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?G_(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=dM(t,n.cause),a={...r,errors:[...jr(r,i.scope).errors,i],message:""};return t.kind!=="load"||!t.focusOnOutcome?a:{...a,focus:F_(a.nextFocusId,{hasError:!0,recovery:a.view?.state==="unavailable",step:a.step}),nextFocusId:a.nextFocusId+1}}function G_(e,t,n){const r=pM(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,a=t.state==="unavailable"?[{scope:{kind:"global"},message:mM(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:a,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=a.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:F_(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!H_(s,t.attemptId)&&(s=Yn(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function lM(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:O_(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return H_(n,t)||(n=Yn(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function dM(e,t){const n=t instanceof cr&&Yu(t.errorCode),r=t instanceof cr&&t.errorCode==="team_setup_roster_unavailable",i=n?U_:r?e.kind==="finish"?Q$:q_:uM(e.kind),a=n||r||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load";return e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{scope:n||r?{kind:"global"}:{kind:"device",itemRef:e.deviceRef},message:i,retry:a}:e.kind==="map_project"?{scope:n||r?{kind:"global"}:{kind:"project",itemRef:e.projectRef},message:i,retry:a}:{scope:e.kind==="load"?{kind:"load"}:{kind:"global"},message:i,retry:a}}function uM(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 pM(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function Zu(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function wn(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 Qa(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function fc(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function mM(e){return Yu(e)?U_:e==="team_setup_roster_unavailable"?q_: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 jr(e,t){return{...e,errors:e.errors.filter(n=>n.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in n.scope)?!1:n.scope.itemRef!==t.itemRef)}}function fM(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?jr(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?jr(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function hM(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function H_(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var gM={role:"list"},vM={role:"listitem"};function yM(e){const t=e.session,n=t.view,r=fc(t),i=t.commands.some(_=>_.kind==="load"),a=Qa(t)||wn(t),s=t.commands.some(_=>_.kind==="finish"),c=n?.state==="unavailable"||r?.retry==="refresh",l=r!=null&&(!n||c),d=!Zu(n)||a||!!r,u=[r?"legacy-team-setup-error":null,a?"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",m=t.errors.filter(_=>_.scope.kind==="device"||_.scope.kind==="project"),f=m.length>0,y=m.some(_=>_.retry==="refresh"),g=new Set(m.flatMap(_=>_.scope.kind==="device"?[_.scope.itemRef]:[])),h=new Set(m.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 o(gr,{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:o("div",{"aria-busy":a?"true":"false",className:"modal-card legacy-team-setup-card",children:[o("div",{className:"modal-header",children:[o("div",{id:"legacy-team-setup-title",tabIndex:-1,children:o(mk,{children:p})}),o(Zr,{ariaDisabled:a,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),o("div",{className:"modal-body legacy-team-setup-body",children:[o("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?o("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?o("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?o("strong",{children:"Current setup details are unavailable"}):null,o("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),o("button",{"aria-busy":a?"true":void 0,"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{a||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,f?o("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[m.map(_=>o("p",{"aria-live":"assertive",id:"itemRef"in _.scope?Wu(_.scope.kind,_.scope.itemRef):void 0,role:"alert",children:_.message},"itemRef"in _.scope?`${_.scope.kind}:${_.scope.itemRef}`:_.scope.kind)),o("button",{"aria-busy":a?"true":void 0,"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{a||e.onRetry()},type:"button",children:i?y?"Refreshing…":"Retrying…":y?"Refresh Team setup":"Retry"})]}):null,n?o(z,{children:[t.step!=="completed"&&!l?o(bM,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,o("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?o(q$,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:g,busyDeviceRefs:b,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?o(K$,{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"?o(W$,{blocked:d||f,blockedDescriptionId:f?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):o(_M,{busy:a,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),o("div",{className:"modal-footer legacy-team-setup-actions",children:o("button",{"aria-disabled":a?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function bM(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return o(z,{children:[o("ol",{...gM,"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,a)=>{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 v("li",{...vM,className:"legacy-team-setup-step",key:i.step},o("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:a+1}),o("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${a+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?o("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?o("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function _M(e){return e.step==="completed"?o("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[o("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),o("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:o("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[o("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),o("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),o("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?o("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 wM={clearDecision:MC,finish:FC,loadDetail:DC,onCompleted:()=>{},refreshCandidate:OC,saveAssignment:LC,saveDecision:$C,saveProjectMapping:jC},ep="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(ep,{detail:t})),t.handled}function SM(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 CM({dependencies:e}){const[t,n]=D(Z$),r=q(null),i=Se(()=>z$(e),[e]),a=l=>{n(d=>Xu(d,l))};return gt(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&wn(p)?Xu(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Xu(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(ep,l),()=>{window.removeEventListener(ep,l)}},[]),W(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))a({type:"command_started",id:l.id}),i(l).then(d=>a({type:"effect_outcome",outcome:d}))},[i,t]),W(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),a({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:o(yM,{session:t,onAssign:(l,d)=>a({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>a({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(wn(t)){a({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}a({type:"close"})},onCloseAutoFocus:l=>IM(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){a({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}a({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>a({type:"finish"}),onMap:(l,d)=>a({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>a({type:"navigate",step:l}),onOpenAutoFocus:NM,onRefresh:()=>a({type:"refresh"}),onRetry:()=>a({type:"retry"})})}var NM=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function IM(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(SM(t.current)?t.current:n)?.focus(),t.current=null}function kM(e,t={}){He(o(CM,{dependencies:{...wM,...t}}),e)}var Za=new WeakMap;function Xn(e,t=""){const n=document.createElement("p");return t&&(n.className=t),n.textContent=e,n}function TM(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 a=document.createElement("span");a.className="project-status-badge needs_attention",a.textContent="Blocked",r.append(i,a);const s=Xn(e.repairAction,"settings-note");if(s.id=`recipient-policy-repair-help-${e.blockedItemId}`,n.append(r,Xn(e.reason,"project-inventory-meta"),s,Xn(`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(Xn("Open Projects to repair this item.","settings-note"));return n}function RM(e,t,n={}){const r=`review:${t.blockedItems.map(s=>n.onRepair&&(n.isRepairAvailable?.(s.repair)??!0)?"1":"0").join("")}:${JSON.stringify(t)}`;if(Za.get(e)===r)return;if(!t.continuity&&t.blockedItems.length===0){e.replaceChildren(),e.hidden=!0,Za.set(e,r);return}e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review",i.setAttribute("aria-labelledby","recipientPolicyReviewTitle");const a=document.createElement("h2");if(a.id="recipientPolicyReviewTitle",a.textContent=t.blockedItems.length>0?"Sharing needs repair":"Existing sharing kept as-is",i.appendChild(a),t.continuity){const s=t.continuity.findingCount,c=Xn(`${s.toLocaleString()} older sharing finding${s===1?" was":"s were"} not changed because Codemem could not safely translate ${s===1?"it":"them"} automatically.`,"settings-note");c.setAttribute("role","status"),c.setAttribute("aria-live","polite"),t.blockedItems.length===0&&i.appendChild(Xn("No action is required for this update. Codemem did not change your existing Team or local sharing configuration.","section-meta")),i.appendChild(c)}if(t.blockedItems.length>0){const s=Xn("Codemem did not change access for these items, but their current availability cannot be confirmed until these source-state problems are repaired.","section-meta project-attention-note"),c=document.createElement("h3");c.className="recipient-policy-blocked-heading",c.textContent="Needs repair";const l=document.createElement("div");l.className="project-inventory-list recipient-policy-review-list";for(const d of t.blockedItems)l.appendChild(TM(d,n));i.append(s,c,l)}e.replaceChildren(i),Za.set(e,r)}function PM(e,t){const n=t instanceof Error?t.message:"Unable to load recipient migration review.",r=`error:${n}`;if(Za.get(e)===r)return;e.hidden=!1;const i=document.createElement("section");i.className="card recipient-policy-review";const a=document.createElement("h2");a.textContent="Recipient migration review";const s=Xn(n,"settings-note project-attention-note");s.setAttribute("role","status"),i.append(a,s),e.replaceChildren(i),Za.set(e,r)}var V_=[["","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"]],ct=null,Pt=0,hc=250,AM=100,tp=[],gc=new Set,vc=new Set,yc=new Map,bc=new Map,Or=new Map,eo=new Map,_c=!1,to=new Map,no=!1,Qn=!1,Di=0,Sn=0,ro=0,Li=null,io=null,At=new Set,W_=new WeakMap,wc={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},$i=wc,Zn=!1,np;function rp(e=!1){if(!e&&io)return io;const t=Nm().then(n=>({ok:!0,summary:n})).catch(()=>({ok:!1}));return io=t,t.then(()=>{io===t&&(io=null)}),t}function Ee(e){return document.getElementById(e)}function EM(e){return V_.find(([t])=>t===e)?.[1]??e.replaceAll("_"," ")}function xM(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 tn(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Sc(e){return e.identity_source!=="unmapped"&&!tn(e)}function DM(e){const t=to.get(e.workspace_identity);(!t||tn(t)&&!tn(e))&&to.set(e.workspace_identity,e)}function ip(e){return tn(e)?"Received from peers":Nc(e.resolved_scope_id)}function LM(e){return tn(e)?"source-owned project":xM(e.resolution_reason)}function $M(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 z_(e){if(!e)return"No recent sessions";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function J_(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Fr(){const e=At.size,t=Ee("projectsShareSelected");t&&(t.textContent=e===0?"Share selected":`Share selected (${e})`,t.disabled=e===0||!Qn||!Zn,t.classList.add("project-selection-target"));const n=Ee("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=W_.get(r)??[],a=i.filter(s=>At.has(s)).length;r.checked=i.length>0&&a===i.length,r.indeterminate=a>0&&a<i.length}for(const r of document.querySelectorAll(".project-recipient-action"))r.disabled=!Qn||!Zn}function MM(e){const t=e.every(n=>At.has(n));for(const n of e)t?At.delete(n):At.add(n);Fr()}function Y_(e,t){const n=J_(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),W_.set(i,n),i.addEventListener("change",()=>MM(n));const a=document.createElement("span");return a.className="sr-only",a.textContent=t,r.append(i,a),r}function jM(e){if(!Zn)return[];const t=new Set(e),n=new Map($i.teams.filter(a=>a.status==="active").map(a=>[a.teamId,a.displayName])),r=new Map($i.identities.filter(a=>a.status==="active"||a.status==="pending").map(a=>[a.identityId,a.displayName])),i=new Map;for(const a of $i.projectRecipients)if(!(a.status!=="active"||!t.has(a.canonicalProjectIdentity)))if(a.recipientKind==="team"){const s=n.get(a.teamId);s&&i.set(`team:${a.teamId}`,{key:`team:${a.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(a.identityId);s&&i.set(`identity:${a.identityId}`,{key:`identity:${a.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((a,s)=>`${a.kind}:${a.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function X_(e){const t=document.createElement("div");t.className="project-recipient-summary";const n=jM(e),r=document.createElement("div");if(r.className="project-recipient-status",r.textContent=Zn?n.length===0?"Not shared with any recipients.":e.length===1?`Shared with ${n.length.toLocaleString()} recipient${n.length===1?"":"s"}.`:`${n.length.toLocaleString()} recipient${n.length===1?"":"s"} across these Project identities.`:"Recipient access is unavailable.",t.appendChild(r),n.length>0){const i=document.createElement("ul");i.className="project-recipient-chips",i.setAttribute("aria-label","Active recipients");for(const a of n){const s=document.createElement("li");s.className=`project-recipient-chip project-recipient-chip-${a.kind.toLowerCase()}`,s.textContent=`${a.kind}: ${a.displayName}`,i.appendChild(s)}t.appendChild(i)}return t}function Q_(e,t){const n=document.createElement("button");return n.className="settings-button project-recipient-action project-selection-target",n.type="button",n.disabled=!Qn||!Zn,e.length===1?(n.textContent="Manage recipients",n.setAttribute("aria-label",`Manage recipients for ${t}`),n.dataset.projectFocusKey=`manage:${e[0]}`,n.addEventListener("click",()=>{oa({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)At.add(r);Fr(),oa({mode:"project-add",projectIds:[...e].sort()})})),n}function OM(e){return e.git_remote?e.git_remote:e.cwd?e.cwd:e.workspace_identity}function ap(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function op(e){return e.project||e.display_project||"Unnamed Project"}function Z_(e){const t=String(e||"").trim();return t?S.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function FM(){return new Set(S.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function BM(e){return!no||e.authority_type!=="coordinator"||!e.group_id?!1:!FM().has(String(e.group_id).trim())}function Cc(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function ew(){_c&&(_c=!1,ct?.())}async function UM(){let e;try{const t=await Vc();e=t&&typeof t=="object"?t:null}catch{S.lastProjectCoordinatorAdminGroups=[],no=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){S.lastProjectCoordinatorAdminGroups=[],no=!1;return}try{const t=await lm(!1);S.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],no=!0}catch{S.lastProjectCoordinatorAdminGroups=[],no=!1}}function qM(e){return e.kind==="team_default"}function sp(e){const t=e.label||"Untitled Space";return qM(e)?`${t} (default)`:t}function GM(e,t){const n=sp(e);return t.some(r=>r.scope_id!==e.scope_id&&sp(r)===n)?`${n} · Space ID ${e.scope_id}`:n}function HM(e){const t=Z_(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 KM(e){return e?tp.find(t=>t.scope_id===e)??null:null}function Nc(e){const t=KM(e);return e?t?`${sp(t)} · ${HM(t)}`:"Unknown Space":"—"}function cp(){return tp.filter(e=>e.scope_id!=="legacy-shared-review"&&!BM(e))}function VM(e){return cp().some(t=>t.scope_id===e)}function tw(...e){for(const t of e)if(t&&VM(t))return t;return e.find(t=>!!t)??""}function WM(e){const t=Z_(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function zM(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function JM(){const e=new Map;for(const t of cp()){const n=zM(t),r=WM(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.values()]}function nw(e){for(const t of JM()){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=GM(r,t.scopes),n.appendChild(i)}e.appendChild(n)}}function YM(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 lp(e,t,n=[]){try{await XC({...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}),Or.delete(e.workspace_identity),yc.delete(e.workspace_identity),J("Project Space assignment updated. Device access grants are unchanged."),ct?.()}catch(r){if(r instanceof No){Or.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),ct?.();return}J(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function XM(e,t){const n=e.filter(Sc);if(n.length!==0)try{await QC({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}))}),J(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access grants are unchanged.`),bc.delete(ap(n[0])),ct?.()}catch(r){J(r instanceof No?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":r instanceof Error?r.message:"Unable to update project Spaces.","warning")}}async function QM(e){if(e.mapping_id!=null)try{await ZC(e.mapping_id),Or.delete(e.workspace_identity),yc.delete(e.workspace_identity),J("Project Space assignment removed. The next fallback now applies."),ct?.()}catch(t){J(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function rw(e,t=!1){try{const n=eo.get(e.workspace_identity),r=await tN({...t&&n?{confirmation_token:n.confirmationToken}:{},confirmed:t,workspace_identity:e.workspace_identity});eo.delete(e.workspace_identity),J(`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.`),ct?.()}catch(n){if(n instanceof bm){eo.set(e.workspace_identity,{confirmationToken:n.preview.confirmation_token,localOwnedMemoryCount:n.preview.local_owned_memory_count,peerOwnedMemoryCount:n.preview.peer_owned_memory_count}),ct?.();return}J(n instanceof Error?n.message:"Unable to forget project memories.","warning")}}async function iw(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await wo()).filter(i=>i&&i!==t)}catch{}const r=await Qd({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const a=i.trim();return a?a===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await eN({project:r.trim(),workspace_identity:e.workspace_identity});J(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),ct?.()}catch(i){J(i instanceof Error?i.message:"Unable to change project.","warning")}}async function ZM(e){const t=to.get(e);if(t&&!tn(t))return{offset:Pt,project:t};try{let n=0,r=0;for(;;){const i=await Wi({limit:hc,offset:n,q:e});r+=1;const a=i.projects.find(c=>c.workspace_identity===e&&!tn(c));if(a)return{offset:i.offset,project:a};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=AM)return null;n=s}}catch{return null}}function aw(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(a=>a.dataset.projectWorkspaceIdentity===e&&a.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 a=r?.dataset.projectClusterKey;a&&vc.add(a)}return n.open=!0,gc.add(`${t.dataset.projectRepairable}:${e}`),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}async function ej(e){if(Cc()){J("Finish the open Space assignment, then try Repair again.","warning");return}const t=Sn,n=Ee("projectsSearch")?.value??"",r=Ee("projectsStatusFilter")?.value??"",i=Pt,a=await ZM(e.projectIdentity);if(Sn!==t||(Ee("projectsSearch")?.value??"")!==n||(Ee("projectsStatusFilter")?.value??"")!==r||Pt!==i)return;if(Cc()){J("Finish the open Space assignment, then try Repair again.","warning");return}if(!a){J("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:s}=a;if(e.kind==="reassign_project"){if(s.identity_source==="unmapped"||s.session_count===0){J("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await iw(s);return}if(!aw(s.workspace_identity)){const c=Ee("projectsSearch"),l=c?.value??"",d=s.workspace_identity;c&&(c.value=d);const u=Ee("projectsStatusFilter"),p=u?.value??"",m="";u&&(u.value=m);const f=Pt;Pt=a.offset;const y=Sn;if(await ao(),!aw(s.workspace_identity)){if(Sn!==y||c&&c.value!==d||u&&u.value!==m||Pt!==a.offset)return;c&&(c.value=l),u&&(u.value=p),Pt=f,await ao(),J("Project administration could not be opened. Refresh Projects and try again.","warning")}}}function tj(e){const t=Sn,n=(Li?.catch(()=>{})??Promise.resolve()).then(async()=>{if(Sn===t)try{await ej(e)}catch(r){J(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Li=n,n.then(()=>{Li===n&&(Li=null)},()=>{Li===n&&(Li=null)}),n}function nj(e){const t=document.createElement("div");if(t.className="project-inventory-actions",Sc(e)&&e.memory_count!=null&&e.guardrail_warnings.every(f=>!f.requires_confirmation)){const f=document.createElement("button");f.className="settings-button",f.type="button",f.textContent="Share",f.disabled=!Qn,Qn||(f.title="The complete project list is unavailable."),f.addEventListener("click",()=>Qo([e.workspace_identity])),t.appendChild(f)}if(tn(e)){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project was received from a peer. Change its project or Space on the source device; this node keeps the received identity read-only.",t.appendChild(f),t}if(e.identity_source==="unmapped"){const f=document.createElement("div");return f.className="settings-note",f.textContent="This project is missing a stable path, git remote, or workspace id. It stays Local only until it has a stable identity.",t.appendChild(f),t}const n=document.createElement("label");n.className="sr-only";const r=`project-domain-${e.workspace_identity.replace(/[^a-z0-9_-]/gi,"-")}`;n.htmlFor=r,n.textContent=`Space for ${e.display_project}`;const i=document.createElement("select");i.id=r,i.className="project-domain-select";const a=cp().some(f=>f.scope_id===e.resolved_scope_id);if(!a&&e.resolved_scope_id){const f=document.createElement("option");f.value=e.resolved_scope_id,f.textContent=`${Nc(e.resolved_scope_id)} — not assignable`,f.disabled=!0,i.appendChild(f)}nw(i),i.value=tw(yc.get(e.workspace_identity),e.suggested_scope_id,e.resolved_scope_id);const s=document.createElement("button");s.className="settings-button",s.type="button",s.textContent=e.suggested_scope_id&&i.value===e.suggested_scope_id?"Confirm suggestion":"Save Space",s.disabled=!i.value||i.value===e.resolved_scope_id&&!a,s.addEventListener("click",()=>{lp(e,i.value)}),i.addEventListener("change",()=>{yc.set(e.workspace_identity,i.value),Or.delete(e.workspace_identity),t.querySelector(".project-space-guardrail-confirmation")?.remove(),s.textContent="Save Space",s.disabled=!i.value,ct?.()}),i.addEventListener("blur",ew);const c=document.createElement("button");c.className="settings-button",c.type="button",c.textContent="Keep local-only",c.addEventListener("click",()=>{lp(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",()=>{QM(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",()=>{iw(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",()=>{rw(e)}),t.append(n,i,s,c,l,d,u);const p=Or.get(e.workspace_identity);if(p){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation project-space-guardrail-confirmation",f.setAttribute("role","alert");const y=document.createElement("strong");y.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"),N=document.createElement("strong");N.textContent=`${YM(_)}: `;const T=document.createElement("span");T.textContent=_.message,I.append(N,T),h.appendChild(I)}const b=document.createElement("button");b.className="settings-button",b.type="button",b.textContent="I understand, save Space",b.addEventListener("click",()=>{const _=Or.get(e.workspace_identity);!_||_.scopeId!==i.value||lp(e,_.scopeId,_.requiredGuardrailTokens)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{Or.delete(e.workspace_identity),ct?.()}),f.append(y,g,h,b,w),t.appendChild(f)}const m=eo.get(e.workspace_identity);if(m){const f=document.createElement("div");f.className="settings-note project-guardrail-confirmation",f.setAttribute("role","alert");const y=document.createElement("strong");y.textContent="Confirm project memory cleanup.";const g=document.createElement("p");g.textContent=`${m.localOwnedMemoryCount.toLocaleString()} locally owned memor${m.localOwnedMemoryCount===1?"y":"ies"} will be forgotten. ${m.peerOwnedMemoryCount.toLocaleString()} peer-owned memor${m.peerOwnedMemoryCount===1?"y":"ies"} will be left unchanged.`;const 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",()=>{rw(e,!0)});const w=document.createElement("button");w.className="settings-button",w.type="button",w.textContent="Cancel",w.addEventListener("click",()=>{eo.delete(e.workspace_identity),ct?.()}),f.append(y,g,h,b,w),t.appendChild(f)}return t}function ow(e){const t=document.createElement("article");t.className="project-inventory-row",t.dataset.projectWorkspaceIdentity=e.workspace_identity,t.dataset.projectRepairable=String(Sc(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",Jo(e)&&r.appendChild(Y_([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),Jo(e)&&r.appendChild(Q_([e.workspace_identity],e.display_project)),t.appendChild(r);const a=document.createElement("div");a.className="project-inventory-meta",a.textContent=`${(e.memory_count??0).toLocaleString()} memories · ${e.session_count.toLocaleString()} sessions · ${z_(e.latest_session_at)}`,t.appendChild(a),t.appendChild(X_([e.workspace_identity]));const s=document.createElement("div");s.className="project-advanced-administration";const c=document.createElement("div");c.className="project-inventory-domain",c.textContent=ip(e),s.appendChild(c);const l=document.createElement("div");if(l.className="project-inventory-meta",l.textContent=`${LM(e)} · ${e.identity_source} · ${z_(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 I=document.createElement("li"),N=document.createElement("strong");N.textContent=$M(_);const T=document.createElement("span");T.textContent=` — ${_.lifecycle.label}. ${_.lifecycle.explanation}`,I.append(N,T),w.appendChild(I)}h.append(b,w),s.appendChild(h)}if(tn(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=OM(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 ${Nc(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=EM(b),h.appendChild(w)}s.appendChild(h)}const p=document.createElement("details");p.className="project-inventory-details";const m=`${t.dataset.projectRepairable}:${e.workspace_identity}`;p.open=gc.has(m),p.addEventListener("toggle",()=>{p.open?gc.add(m):gc.delete(m)});const f=document.createElement("summary");f.dataset.projectFocusKey=`admin:${t.dataset.projectRepairable}:${e.workspace_identity}`,f.textContent=u.length>0?`Advanced Project administration — ${u.length.toLocaleString()} item${u.length===1?"":"s"} need attention`:"Advanced Project administration",p.appendChild(f),p.appendChild(s);const y=document.createElement("dl");y.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",ip(e)],["Suggested Space",e.suggested_scope_id?Nc(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),y.append(w,_)}return p.appendChild(y),p.appendChild(nj(e)),t.appendChild(p),t}function rj(e){const t=[...new Set(e.map(n=>ip(n)))];return t.length===1?t[0]:"Mixed Spaces"}function ij(e){if(e.length===1)return ow(e[0]);const t=ap(e[0]),n=e.filter(Jo),r=J_(n),i=document.createElement("article");i.className="project-inventory-row project-inventory-cluster",i.dataset.projectClusterKey=t;const a=op(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(Y_(n,`Select all identities for ${op(e[0])}`));const l=document.createElement("h3");l.className="project-inventory-title",l.id=s,l.textContent=a,c.appendChild(l),r.length>0&&c.appendChild(Q_(r,a)),i.appendChild(c);const d=document.createElement("div");d.className="project-advanced-administration";const u=document.createElement("div");u.className="project-inventory-domain",u.textContent=rj(e),d.appendChild(u);const p=e.reduce((_,I)=>_+(I.memory_count??0),0),m=e.reduce((_,I)=>_+I.session_count,0),f=document.createElement("div");f.className="project-inventory-meta",f.textContent=`${e.length} identities · ${m.toLocaleString()} sessions · ${p.toLocaleString()} memories`,i.appendChild(f),i.appendChild(X_(r));const y=document.createElement("div");y.className="project-inventory-actions";const g=e.filter(Sc);if(g.length===0){const _=document.createElement("div");_.className="settings-note",_.textContent=e.every(tn)?"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.",y.appendChild(_),d.appendChild(y)}else{const _=g.map(P=>({project:P,warnings:(P.guardrail_warnings??[]).filter(F=>F.requires_confirmation)})),I=_.some(({warnings:P})=>P.length>0),N=new Set(g.map(P=>P.suggested_scope_id).filter(P=>!!P)),T=new Set(g.map(P=>P.resolved_scope_id)),x=document.createElement("select");x.className="project-domain-select",x.setAttribute("aria-label",`Space for ${op(e[0])} group`);const j=document.createElement("option");j.value="",j.textContent="Choose Space…",x.appendChild(j),nw(x),x.value=tw(bc.get(t));const B=document.createElement("button");if(B.className="settings-button",B.type="button",B.textContent=`Save Space for ${g.length} identit${g.length===1?"y":"ies"}`,B.disabled=!x.value||I,B.addEventListener("click",()=>{XM(g,x.value)}),x.addEventListener("change",()=>{x.value?bc.set(t,x.value):bc.delete(t),B.disabled=!x.value||I}),x.addEventListener("blur",ew),y.append(x,B),N.size>1||T.size>1||I){const P=document.createElement("div");if(P.className="settings-note project-attention-note",P.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 F=document.createElement("ul");for(const{project:O,warnings:G}of _){if(G.length===0)continue;const $=document.createElement("li"),A=document.createElement("strong");A.textContent=`Blocked identity: ${O.workspace_identity}`;const E=document.createElement("span");E.textContent=` — ${G.map(C=>C.message).join(" ")}`,$.append(A,E),F.appendChild($)}P.appendChild(F)}y.appendChild(P)}d.appendChild(y)}const h=document.createElement("details");h.className="project-inventory-details",h.open=vc.has(t),h.addEventListener("toggle",()=>{h.open?vc.add(t):vc.delete(t)});const b=document.createElement("summary"),w=e.reduce((_,I)=>_+(I.guardrail_warnings??[]).filter(N=>N.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(ow(_));return i.appendChild(h),i}function aj(e){const t=new Map;for(const n of e){const r=ap(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function sw(e){const t=Ee("projectsInventoryList");if(!t)return;t.textContent="";const n=document.createElement("div");n.className="settings-note",n.textContent=e,t.appendChild(n)}function cw(){document.getElementById("projectsInventorySkeleton")?.remove()}function lw(e){const t=Ee("projectsInventoryMeta"),n=Ee("projectsInventoryList");if(!t||!n)return;const r=document.activeElement instanceof HTMLElement?document.activeElement.dataset.projectFocusKey:void 0;cw(),to.clear();for(const s of e.projects)DM(s);if(n.textContent="",e.projects.length===0)sw("No projects match those filters.");else for(const s of aj(e.projects))n.appendChild(ij(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=Ee("projectsPrevPage"),a=Ee("projectsNextPage");i&&(i.disabled=e.offset===0),a&&(a.disabled=!e.has_more),Fr(),r&&[...n.querySelectorAll("[data-project-focus-key]")].find(s=>s.dataset.projectFocusKey===r)?.focus()}function oj(e,t){UM().then(()=>{t===Di&&(Cc()||lw(e))})}async function sj(){const e=new Map;let t=0;for(;;){const n=await Wi({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 dw(e,t,n){const r=Ee("recipientPolicyManagementMount");r&&Th(r,Yo(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&At.clear(),Fr(),ct?.()}})}function uw(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&&Ee("projectsSearch")?.focus();return}const a=JSON.stringify(n.map(d=>[d.candidateRef,d.displayName]));if(r?.dataset.teamSetupSignature===a){e.hidden=!1;return}r?.remove(),e.hidden=!1;const s=document.createElement("section");s.className="card project-team-setup-entry",s.dataset.teamSetupSignature=a;const c=document.createElement("h2");c.textContent="Finish setting up this Team";const l=document.createElement("p");l.className="section-meta",l.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",s.append(c,l);for(const d of n){const u=document.createElement("div");u.className="project-inventory-actions";const p=document.createElement("strong");if(p.textContent=d.displayName,u.appendChild(p),np){const m=document.createElement("button");m.setAttribute("aria-label",`Finish setting up ${d.displayName}`),m.className="settings-button",m.type="button",m.textContent="Finish setting up this Team",m.dataset.teamSetupCandidateRef=d.candidateRef,m.addEventListener("click",()=>np?.(d.candidateRef)),u.appendChild(m)}s.appendChild(u)}if(e.appendChild(s),i){let d=!1;for(const u of s.querySelectorAll("button"))if(u.dataset.teamSetupCandidateRef===i){u.focus(),d=!0;break}d||Ee("projectsSearch")?.focus()}}function pw(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 cj(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 ao(e={}){const t=Ee("projectsInventoryMeta"),n=Ee("projectsInventoryList");if(!t||!n)return e.requireTeamSetupSummary?(await rp(!0)).ok:!0;if(Cc()){if(_c=!0,!e.requireTeamSetupSummary)return!0;const i=++ro,a=await rp(!0);if(i!==ro)return!1;const s=Ee("recipientPolicyReviewMount");return a.ok?(s&&uw(s,a.summary),!0):(s&&pw(s),!1)}_c=!1;const r=++Di;Qn=!1,Zn=!1,Fr(),t.textContent="Loading project inventory…";try{const i=++ro,a=rp(e.requireTeamSetupSummary===!0),[s,c,l,d,u]=await Promise.all([Wi({limit:hc,offset:Pt,q:Ee("projectsSearch")?.value.trim()||void 0,status:Ee("projectsStatusFilter")?.value||void 0}),VC(),sj().then(g=>({ok:!0,projects:g})).catch(()=>({ok:!1,projects:[]})),KC().then(g=>({ok:!0,review:g})).catch(g=>({ok:!1,error:g})),Xc().then(g=>({ok:!0,intent:g})).catch(g=>({ok:!1,error:g}))]);if(r!==Di)return e.requireTeamSetupSummary&&await a,!1;if(tp=c.scopes,Qn=l.ok,Zn=u.ok,$i=u.ok?u.intent:wc,l.ok){const g=new Set(Yo(l.projects).map(h=>h.canonicalProjectIdentity));for(const h of At)g.has(h)||At.delete(h)}const p=Ee("projectShareFlowMount");p&&xh(p,l.projects,{inventoryError:!l.ok});const m=Ee("recipientPolicyReviewMount");if(m){const g=cj(m);"review"in d?RM(g,d.review,{isRepairAvailable:h=>!h.projectIdentity.startsWith("unmapped:"),onRepair:tj}):PM(g,d.error),m.hidden=g.hidden&&!m.querySelector(".project-team-setup-entry")}dw(l.projects,$i,!l.ok||!u.ok),lw(s),oj(s,r),a.then(g=>{if(r!==Di||i!==ro)return;const h=Ee("recipientPolicyReviewMount");if(h){if(!g.ok){pw(h);return}uw(h,g.summary)}});const f=l.ok&&"review"in d&&u.ok;if(!e.requireTeamSetupSummary)return f;const y=await a;return r!==Di||i!==ro?!1:f&&y.ok}catch(i){if(r!==Di)return!1;to.clear(),Qn=!1,Zn=!1,$i=wc;const a=Ee("projectShareFlowMount");return a&&xh(a,[],{inventoryError:!0}),dw([],wc,!0),Fr(),cw(),t.textContent="Project inventory failed to load.",sw(i instanceof Error?i.message:"Unable to load project inventory."),!1}}function lj(e,t={}){ct=e,np=t.onOpenTeamSetup,At.clear();const n=Ee("projectsStatusFilter");if(n&&n.options.length===0)for(const[a,s]of V_){const c=document.createElement("option");c.value=a,c.textContent=s,n.appendChild(c)}const r=()=>{Sn+=1,Pt=0,ct?.()};Ee("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),Ee("projectsPrevPage")?.addEventListener("click",()=>{Sn+=1,Pt=Math.max(0,Pt-hc),ct?.()}),Ee("projectsNextPage")?.addEventListener("click",()=>{Sn+=1,Pt+=hc,ct?.()});const i=Ee("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{At.size!==0&&oa({mode:"project-add",projectIds:[...At].sort()})})),Fr()}function dp(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(a=>a.trim()):r;if(t.requireNonEmpty&&i.some(a=>a.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function dj(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,a]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof a!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=a}return r}var mw="codemem-settings-advanced",fw="gpt-5.1-codex-mini",hw="claude-4.5-haiku",uj=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],pj={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"},mj=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),fj={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 hj(){try{return globalThis.localStorage?.getItem(mw)==="1"}catch{return!1}}function gj(e){try{globalThis.localStorage?.setItem(mw,e?"1":"0")}catch{}}function Cn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function ke(e,t,n){if(Cn(t,n))return t[n];if(Cn(e,n))return e[n]}function xe(e){return e==null?"":String(e)}function Ic(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 vj(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function yj(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Xe(e){const t=e.trim();return t===""?"":t}function bj(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:hw,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:fw,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:hw,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:fw,source:"Recommended (direct API)"}}function _j(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(a=>{if(typeof a!="string")return;const s=a.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return Xe(xe(n[t]));case"observer_runtime":return Xe(xe(n.observer_runtime));case"observer_auth_source":return Xe(xe(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([a,s])=>{typeof a=="string"&&a.trim()&&typeof s=="string"&&(i[a.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Cn(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(!Cn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Cn(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 Ic(n[t]);default:return Cn(n,t)?n[t]:""}}function wj(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Cn(r,i)&&(r[i]=_j(t,i))}),r}function Sj(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let a=[];try{a=dp(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("claude_command"))throw I;const N=r.claude_command;a=Array.isArray(N)?N.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=dp(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(I){if(!i||n.has("codex_command"))throw I;const N=r.codex_command;s=Array.isArray(N)?N.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=dp(t.observerAuthCommand,{label:"observer auth command"})}catch(I){if(!i||n.has("observer_auth_command"))throw I;const N=r.observer_auth_command;c=Array.isArray(N)?N.filter(T=>typeof T=="string"):[]}let l={};try{l=dj(t.observerHeaders)}catch(I){if(!i||n.has("observer_headers"))throw I;const N=r.observer_headers;N&&typeof N=="object"&&!Array.isArray(N)&&Object.entries(N).forEach(([T,x])=>{typeof T=="string"&&T.trim()&&typeof x=="string"&&(l[T]=x)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),m=t.observerRichMaxOutputTokens.trim(),f=t.rawEventsSweeperIntervalS.trim(),y=d===""?"":Number(d),g=u===""?"":Number(u),h=p===""?"":Number(p),b=m===""?"":Number(m),w=Number(f),_=f===""?"":w;if(d!==""&&!Number.isFinite(y))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(m!==""&&(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(f!==""&&(!Number.isFinite(w)||w<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:a,codex_command:s,observer_provider:Xe(t.observerProvider),observer_model:Xe(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Xe(t.observerSimpleModel),observer_simple_temperature:g,observer_reasoning_effort:Xe(t.observerReasoningEffort),observer_reasoning_summary:Xe(t.observerReasoningSummary),observer_rich_model:Xe(t.observerRichModel),observer_rich_temperature:h,observer_rich_reasoning_effort:Xe(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Xe(t.observerRichReasoningSummary),observer_rich_max_output_tokens:b,observer_runtime:Xe(t.observerRuntime||"api_http")||"api_http",observer_auth_source:Xe(t.observerAuthSource||"auto")||"auto",observer_auth_file:Xe(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:y,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:Xe(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Xe(t.syncCoordinatorUrl),sync_coordinator_group:Xe(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function Cj(e){const t=e.config||{},n=e.effective||{},r=ke(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,m])=>typeof p=="string"&&p.trim()&&typeof m=="string")):{},a=ke(t,n,"claude_command"),s=Array.isArray(a)?a.filter(p=>typeof p=="string"):[],c=ke(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=ke(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:xe(ke(t,n,"observer_provider")),observerModel:xe(ke(t,n,"observer_model")),observerTierRoutingEnabled:Ic(ke(t,n,"observer_tier_routing_enabled")),observerSimpleModel:xe(ke(t,n,"observer_simple_model")),observerSimpleTemperature:xe(ke(t,n,"observer_simple_temperature")),observerReasoningEffort:xe(ke(t,n,"observer_reasoning_effort")),observerReasoningSummary:xe(ke(t,n,"observer_reasoning_summary")),observerRichModel:xe(ke(t,n,"observer_rich_model")),observerRichTemperature:xe(ke(t,n,"observer_rich_temperature")),observerRichReasoningEffort:xe(ke(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:xe(ke(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:xe(ke(t,n,"observer_rich_max_output_tokens")),observerRuntime:xe(ke(t,n,"observer_runtime"))||"api_http",observerAuthSource:xe(ke(t,n,"observer_auth_source"))||"auto",observerAuthFile:xe(ke(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:xe(ke(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:xe(ke(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:xe(ke(t,n,"observer_max_chars")),packObservationLimit:xe(ke(t,n,"pack_observation_limit")),packSessionLimit:xe(ke(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:xe(ke(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Ic(ke(t,n,"sync_enabled")),syncHost:xe(ke(t,n,"sync_host")),syncPort:xe(ke(t,n,"sync_port")),syncInterval:xe(ke(t,n,"sync_interval_s")),syncMdns:Ic(ke(t,n,"sync_mdns")),syncCoordinatorUrl:xe(ke(t,n,"sync_coordinator_url")),syncCoordinatorGroup:xe(ke(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:xe(ke(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:xe(ke(t,n,"sync_coordinator_presence_ttl_s"))}}function Nj(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=bj(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Xe(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Cn(t,r))?"Env override":n.source}: ${n.model}`}function Ij(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 kj(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function Tj(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 Rj(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 Pj(e){return!e}function Aj(e,t,n){return t.has(e)||n.has(e)}function Ej(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:hj(),controller:null,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...fj}}};function xj(){Y.controller?.hideTooltip()}function Br(e){if(Y.controller){Y.controller.setRenderState(e);return}Y.renderState={...Y.renderState,...e}}function Dj(e){Br({values:{...Y.renderState.values,...e}})}function Lj(e){const t=["observer","queue","sync"].includes(e)?e:"observer";Y.activeTab=t,Y.controller?.setActiveTab(t)}function kc(e,t=!0){S.settingsDirty=e,t&&Y.controller?.setDirty(e)}function $j(e){Y.showAdvanced=e,Y.controller?.setShowAdvanced(e)}function gw(){return Y.open}function Mj(e){return Aj(e,Y.protectedKeys,mj)}function vw(e={}){return Sj({values:Y.renderState.values,touchedKeys:Y.touchedKeys,baseline:Y.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function jj(e){Br({observerStatus:e&&typeof e=="object"?e:null})}function Oj(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},a=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=Cj(t);Y.envOverrides=i,Y.protectedKeys=new Set(a),S.configDefaults=n,S.configPath=t.path||"",Br({effectiveText:Object.keys(i).length>0?"Some fields are managed by environment settings.":"",overridesVisible:Object.keys(i).length>0,pathText:S.configPath?`Config path: ${S.configPath}`:"Config path: n/a",providers:vj(t.providers),statusText:"No unsaved changes",values:s}),Y.touchedKeys=new Set;try{Y.baseline=wj(vw({allowUntouchedParseErrors:!0}),r,i)}catch{Y.baseline={}}kc(!1)}async function Fj(){if(!Y.open)try{const[e,t]=await Promise.all([HS(),GS().catch(()=>null)]);Oj(e),jj(t)}catch{}}function up(e){return String(e||"").replace(/_/g," ")}function pp(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 Bj(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 Uj(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 qj(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function Gj({status:e}){if(!e)return o("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const t=e.active,n=e.available_credentials||{},r=e.latest_failure,i=Object.entries(n).filter(([,a])=>a&&typeof a=="object");return o("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[t?o(z,{children:[o("div",{className:"status-label",children:"Active observer"}),o("div",{className:"status-active",children:[String(t.provider||"unknown")," → ",String(t.model||"")," via"," ",Bj(t.auth?.method||"none")," ",o("span",{"aria-label":t.auth?.token_present===!0?"token present":"token missing",className:t.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:o("i",{"aria-hidden":"true","data-lucide":t.auth?.token_present===!0?"check":"x"})})]})]}):o(z,{children:[o("div",{className:"status-label",children:"Observer status"}),o("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),i.length?o(z,{children:[o("div",{className:"status-label",children:"Available credentials"}),o("div",{children:i.map(([a,s],c)=>{const l=s,d=Object.values(l).some(Boolean);return o("span",{className:"status-cred",children:[c>0?" · ":null,o("span",{"aria-label":d?"credential available":"no credential",className:d?"cred-ok":"cred-none",role:"img",children:d?o("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(a),": ",Uj(l)]},a)})})]}):null,r&&typeof r=="object"?o(z,{children:[o("div",{className:"status-label",children:"Latest processing issue"}),o("div",{className:"status-issue",children:[o("div",{className:"status-issue-message",children:typeof r.error_message=="string"&&r.error_message.trim()?r.error_message.trim():"Raw-event processing failed."}),o("div",{className:"status-issue-meta",children:[[typeof r.observer_provider=="string"?r.observer_provider.trim():"",typeof r.observer_model=="string"&&r.observer_model.trim()?`→ ${r.observer_model.trim()}`:"",typeof r.observer_runtime=="string"&&r.observer_runtime.trim()?`(${r.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${qj(r.updated_at)}`,typeof r.attempt_count=="number"&&Number.isFinite(r.attempt_count)?`Attempts ${r.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof r.impact=="string"&&r.impact.trim()?o("div",{className:"status-issue-impact",children:r.impact.trim()}):null]})]}):null]})}function yw(e,t){const n=t.getBoundingClientRect(),r=8,i=8,a=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-a/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-a-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function oo(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function Hj(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 Kj(){const e=Le("settingsModal");(Hj(e)[0]||e)?.focus()}function Vj(){const[e,t]=D({anchor:null,content:"",visible:!1}),n=q(null);return W(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},a=u=>{const p=oo(u.target);p&&r(p)},s=u=>{const p=oo(u.target);if(!p)return;const m=u.relatedTarget;m instanceof Element&&p.contains(m)||i()},c=u=>{const p=oo(u.target);p&&r(p)},l=u=>{oo(u.target)&&i()},d=u=>{const p=oo(u.target);p&&(u.preventDefault(),t(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const f=p.dataset.tooltip?.trim()||"";return f?{anchor:p,content:f,visible:!0}:m}))};return document.addEventListener("pointerover",a),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",a),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),gt(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&yw(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),W(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&yw(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:Se(()=>typeof document>"u"?null:dn(o("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function Wj({DialogContent:e,onClose:t}){const[n,r]=D(Y.open),[i,a]=D(["observer","queue","sync"].includes(Y.activeTab)?Y.activeTab:"observer"),[s,c]=D(S.settingsDirty),[l,d]=D(Y.renderState),[u,p]=D(Y.showAdvanced),{tooltipPortal:m,setTooltip:f}=Vj();Y.open=n,Y.activeTab=i,S.settingsDirty=s,Y.renderState=l,Y.showAdvanced=u,W(()=>(Y.controller={hideTooltip:()=>{f({anchor:null,content:"",visible:!1})},setActiveTab:g=>{const h=["observer","queue","sync"].includes(g)?g:"observer";Y.activeTab=h,a(h)},setDirty:g=>{S.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,gj(g),p(g)}},()=>{Y.controller&&(Y.controller=null)}),[]),W(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const y=oe(()=>{Y.startPolling&&Y.refresh&&t(Y.startPolling,Y.refresh)},[t]);return o(z,{children:[o(gr,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:g=>{g.preventDefault()},onOpenAutoFocus:g=>{g.preventDefault(),Kj()},onOpenChange:g=>{if(g){r(!0);return}y()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:o(e,{})}),m]})}function Ge({children:e,className:t="field",hidden:n=!1,id:r}){return o("div",{className:t,hidden:n,id:r,children:e})}function so({children:e,hidden:t=!1}){return o("div",{className:"settings-note",hidden:t,children:e})}function mp({detail:e,title:t}){return o("div",{className:"settings-section-intro",children:[o("div",{className:"settings-section-intro-title",children:t}),o("div",{className:"small settings-section-intro-detail",children:e})]})}function zj({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:a,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:m,observerStatusBannerSlot:f}){return o(z,{children:[o(mp,{detail:"Set how codemem reaches your model provider and where it should look for credentials.",title:"Connection and credentials"}),f,o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Connection"}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerProvider",children:"Model provider"}),o("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),o(Hn,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider."})]}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerModel",children:l()}),o("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),o(_e,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),o("div",{className:"small",children:u()}),o("div",{className:"small",id:"observerModelHint",children:p()})]}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRuntime",children:"Connection mode"}),o("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),o(Hn,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Switch between provider API credentials and local Claude or Codex CLI auth."})]}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),o(Si,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),o("div",{className:"small",children:m("codex_command")})]}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),o(Si,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),o("div",{className:"small",children:m("claude_command")})]}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),o(_e,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),o("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Authentication"}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),o("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),o(Hn,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),o("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),o(Ge,{hidden:!r,id:"observerAuthFileField",children:[o("label",{htmlFor:"observerAuthFile",children:"Token file path"}),o(_e,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),o("div",{className:"small",children:m("observer_auth_file")})]}),o(Ge,{hidden:!i,id:"observerAuthCommandField",children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerAuthCommand",children:"Token command"}),o("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),o(Si,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),o("div",{className:"small",children:m("observer_auth_command")})]}),o("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),o(so,{hidden:a(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),o(_e,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),o(_e,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),o(Ge,{className:"field settings-advanced",hidden:a(),children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),o("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),o(Si,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),o("div",{className:"small",children:m("observer_headers")})]})]})]})}function Tc({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:a,onCheckedChange:s}){const c=`${i}Label`;return o("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[o("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:a}),o(bi,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"})]})}function Jj({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:a}){return o(z,{children:[o(mp,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Processing"}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),o("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),o(_e,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),o("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Tiered observer routing"}),o(Tc,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),o("div",{className:"small",children:a()}),o(so,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),o("div",{hidden:!t,children:[o("h4",{children:"Simple tier"}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerSimpleModel",children:"Model"}),o("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(_e,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),o("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),o(_e,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),o("div",{className:"settings-advanced",hidden:!t||n(),children:[o("h4",{children:"Shared reasoning defaults"}),o("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),o(Ge,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),o(_e,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),o(Ge,{className:"field settings-advanced",children:[o("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),o(_e,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),o("div",{hidden:!t,children:[o("h4",{children:"Rich tier"}),o(Ge,{children:[o("div",{className:"field-label",children:[o("label",{htmlFor:"observerRichModel",children:"Model"}),o("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),o(_e,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),o("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),o(_e,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),o(_e,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),o(_e,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),o(_e,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),o("div",{className:"settings-group settings-advanced",hidden:n(),children:[o("h3",{className:"settings-group-title",children:"Pack limits"}),o(so,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),o(_e,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),o("div",{className:"small",children:"Default number of observations to include in a pack."})]}),o(Ge,{className:"field settings-advanced",hidden:n(),children:[o("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),o(_e,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),o("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function Yj({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return o(z,{children:[o(mp,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),o("div",{className:"settings-group",children:[o("h3",{className:"settings-group-title",children:"Device Sync"}),o(Tc,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),o(_e,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),o("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncHost",children:"Sync host"}),o(_e,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncPort",children:"Sync port"}),o(_e,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),o(Tc,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),o(_e,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),o("div",{className:"small",children:i("sync_coordinator_url")})]}),o("div",{className:"field",children:[o("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),o(_e,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),o("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),o("div",{className:"field settings-advanced",hidden:t(),children:o(so,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),o(_e,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),o("div",{className:"field settings-advanced",hidden:t(),children:[o("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),o(_e,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function Xj({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:a,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,observerStatusBannerSlot:d}){const u=!i||r.isSaving;return o("div",{className:"modal-card",onKeyDown:p=>ui(p,{onSubmit:s,disabled:u}),children:[o("div",{className:"modal-header",children:[o("h2",{id:"settingsTitle",children:"Settings"}),o(Zr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:a})]}),o("div",{className:"modal-body",children:[o("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),o("div",{className:"settings-advanced-toolbar",children:[o(Tc,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),o("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:o("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),o(so,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),o(Ug,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:uj,triggerClassName:"settings-tab",value:t,children:[o(wr,{className:"settings-panel",forceMount:!0,value:"observer",children:o(zj,{...e,observerStatusBannerSlot:d})}),o(wr,{className:"settings-panel",forceMount:!0,value:"queue",children:o(Jj,{...e})}),o(wr,{className:"settings-panel",forceMount:!0,value:"sync",children:o(Yj,{...e})})]}),o("div",{className:"small mono",id:"settingsPath",children:r.pathText}),o("div",{className:"small",id:"settingsEffective",children:r.effectiveText}),o("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."}),o("div",{className:"settings-note",hidden:n,children:"Advanced controls are hidden right now to keep this screen focused on everyday settings."})]}),o("div",{className:"modal-footer",children:[o("div",{className:"small",id:"settingsStatus",children:r.statusText}),o("button",{className:"settings-save","data-primary-action":"true",disabled:u,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function Qj(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:a}=e,s={};return Object.entries(t).forEach(([c,l])=>{a(c)||Cn(r,c)&&!i.has(c)||yj(l,n[c])||(s[c]=l)}),s}function Zj(e){const t=s=>{const c=pj[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 eO(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=>up(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>up(String(p))):[],a=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>up(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: ${pp(r)}.`),i.length&&d.push(`Live settings updated: ${pp(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),a.length&&d.push(`Restart required for ${pp(a)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=a.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var tO=()=>Nj(Y.renderState.values,Y.envOverrides),nO=()=>Ij(Y.renderState.values),rO=()=>kj(Y.renderState.values),iO=()=>Tj(Y.renderState.values),aO=()=>Rj(Y.renderState.values),oO=()=>Pj(Y.showAdvanced),{onTextInput:sO,onSelectValueChange:cO,onSwitchInput:lO}=Zj({getTouchedKeys:()=>Y.touchedKeys,getValues:()=>Y.renderState.values,updateFormState:Dj,setDirty:e=>kc(e)});function dO(){const e=Y.renderState.observerStatus;return o(Gj,{status:e})}function uO(){const e=Y.renderState.values,t=String(S.configDefaults?.observer_max_chars||""),n=e.observerAuthSource==="file",r=e.observerAuthSource==="command",i=e.observerTierRoutingEnabled;return o(Xj,{panelProps:{values:e,observerMaxCharsDefault:t,providerOptions:Array.from(new Set(Y.renderState.providers.concat(e.observerProvider?[e.observerProvider]:[]))).sort((a,s)=>a.localeCompare(s)).map(a=>({label:a,value:a})),showAuthFile:n,showAuthCommand:r,showTieredRouting:i,hiddenUnlessAdvanced:oO,onTextInput:sO,onSelectValueChange:cO,onSwitchInput:lO,getObserverModelLabel:rO,getObserverModelTooltip:iO,getObserverModelDescription:aO,getObserverModelHint:tO,getTieredRoutingHelperText:nO,protectedConfigHelp:Ej},activeTab:Y.activeTab,showAdvanced:Y.showAdvanced,renderState:Y.renderState,settingsDirty:S.settingsDirty,onClose:()=>{Y.startPolling&&Y.refresh&&Rc(Y.startPolling,Y.refresh)},onSave:()=>{Y.startPolling&&Y.refresh&&hO(Y.startPolling,Y.refresh)},onActiveTabChange:Lj,onAdvancedToggle:$j,observerStatusBannerSlot:o(dO,{})})}function pO(){return o(Wj,{DialogContent:uO,onClose:Rc})}function mO(){const e=Le("settingsDialogMount");e&&He(o(pO,{}),e)}function bw(){Le("settingsDialogMount")&&(Y.shellMounted||(mO(),Y.shellMounted=!0))}function fO(e){Y.shellMounted||bw(),Y.open=!0,Y.previouslyFocused=document.activeElement,e(),Y.controller?.setOpen(!0)}function Rc(e,t){if(S.settingsDirty&&!globalThis.confirm("Discard unsaved changes?")){Y.controller?.setOpen(!0);return}Y.open=!1,Y.controller?.setOpen(!1),xj(),(Y.previouslyFocused&&typeof Y.previouslyFocused.focus=="function"?Y.previouslyFocused:td("settingsButton"))?.focus(),Y.previouslyFocused=null,Y.touchedKeys=new Set,e(),t()}async function hO(e,t){if(!Y.renderState.isSaving){Br({isSaving:!0,statusText:"Saving changes…"});try{const n=Qj({current:vw({allowUntouchedParseErrors:!0}),baseline:Y.baseline,envOverrides:Y.envOverrides,touchedKeys:Y.touchedKeys,isProtected:Mj});if(Object.keys(n).length===0){Br({isSaving:!1,statusText:"No unsaved changes"}),kc(!1),Rc(e,t);return}const r=eO(await KS(n));Br({isSaving:!1,statusText:"Saved changes"}),kc(!1),Rc(e,t),J(r.message,r.type)}catch(n){Br({isSaving:!1,statusText:`Save failed: ${n instanceof Error?n.message:"unknown error"}`})}}}function gO(e,t,n){Y.startPolling=t,Y.refresh=n,bw(),td("settingsButton")?.addEventListener("click",()=>fO(e))}function vO(e){e.dataset.syncRenderRoot="preact"}function yO(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function at(e,t){vO(e),He(t,e)}function Mi(e){e.dataset.syncRenderRoot==="preact"&&He(null,e)}function bO(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 _O(e){return typeof e=="object"&&e!==null}function wO(e,t){return S.pairingCommandRaw="",{payloadText:e,hintText:t}}function SO(e){if(!_O(e))return wO("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 S.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function CO(){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 NO(){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 IO(){const e=S.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 kO(){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 TO(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 RO({items:e}){return o(z,{children:e.map((t,n)=>o("div",{class:"stat",children:o("div",{class:"stat-content",children:[o("div",{class:"value",children:t.value}),o("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function PO({attempts:e,note:t}){return o(z,{children:[t?o("div",{class:"small",children:t}):null,e.map((n,r)=>o("div",{class:"diag-line",children:[o("div",{class:"left",children:[o("div",{children:[n.peerLabel," — ",n.status]}),n.detail?o("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?o("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null]}),o("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function _w({text:e}){return o(z,{children:e})}function AO({title:e,detail:t}){return o("div",{class:"sync-empty-state",children:[o("strong",{children:e}),o("span",{children:t})]})}function EO(e,t){if(!t.length){Mi(e);return}at(e,o(RO,{items:t}))}function xO(e,t,n){if(!t.length){Mi(e);return}at(e,o(PO,{attempts:t,note:n}))}function Ur(e,t){at(e,o(AO,{...t}))}function ww(e,t,n){at(e,o(_w,{text:n.payloadText})),t&&at(t,o(_w,{text:n.hintText}))}function Sw({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:a,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=q(null),p=q(null),m=q(!1);gt(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),W(()=>{if(!e){m.current=!1;return}m.current||(m.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const f=o(_a,{forceMount:!0,asChild:!0,children:o("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return o(ba,{open:e,onOpenChange:t,children:[o(bd,{asChild:!0,children:o("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?a:i})}),l?dn(f,l):f]})}function DO({open:e,onOpenChange:t}){return o(Sw,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[o("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),o("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),o("div",{className:"actor-create-row",children:[o("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),o(_e,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),o("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),o("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),o("div",{className:"sync-ttl-group",children:[o("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),o(_e,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),o("span",{children:"hours"})]}),o("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),o("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),o(Si,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),o("div",{className:"peer-meta",id:"syncInviteAdminHint"}),o("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function LO({contentHost:e,open:t,onOpenChange:n}){return o(Sw,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[o("div",{className:"peer-title",children:[o("strong",{children:"Pairing command"}),o("div",{className:"peer-actions",children:o("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),o("div",{className:"pairing-body",children:o("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),o("div",{className:"peer-meta",id:"pairingHint"})]})}function $O(e,t){at(e,o(DO,{...t}))}function MO(e,t){at(e,o(LO,{...t}))}function pe(e){return String(e??"").trim()}function jO(e){return pe(e).replace(/\s+/g," ").toLowerCase()}function OO(e){const t=pe(e);return t?t.slice(0,8):"Unnamed device"}function Cw(e){return pe(e?.last_error).toLowerCase()}function Nw(e){return e.includes("401")&&e.includes("unauthorized")}function Iw(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var FO={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 BO(e){const t=kw(e);return!pe(e.device?.device_id)||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":!0}function Tw(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),a=HO(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${a}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>Rw(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=>Rw(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:pe(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function Rw(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=pe(e.error);return UO(n)?"trust":qO(n)?"scope":null}function UO(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function qO(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function GO(e){const t=pe(e?.reason);return FO[t]??(t.replaceAll("_"," ")||"sync filters")}function HO(e){const t=new Map;for(const n of e){const r=GO(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 Pw(e){const t=pe(e.localName);if(t)return t;const n=pe(e.coordinatorName);return n||OO(pe(e.deviceId))}function KO(e){const t=pe(e.localName),n=pe(e.coordinatorName);return t||n?!1:!!pe(e.deviceId)}function VO(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 co(e){const t=pe(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=Cw(e);return Nw(n)?"needs-repair":Iw(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function ji(e){const t=e?.status||{},n=pe(t.peer_state),r=Cw(e),i=pe(t.sync_status)==="ok"||pe(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}:Nw(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}:Iw(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 WO={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 zO(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,a]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(a??0));if(s===0)continue;const c=i;r.push({reason:c,label:WO[c]??i,count:s})}return r.sort((i,a)=>a.count-i.count||i.label.localeCompare(a.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function Aw(e){return Array.isArray(e)?e.map(t=>pe(t)).filter(t=>!!t):[]}function Ew(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 Pc(e,t){return e?e.replaceAll("_"," "):t}function JO(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=pe(r.scope_id),a=pe(r.label);if(!i&&!a)return null;const s=a||"Untitled Space",c=[Pc(pe(r.kind),"user"),Pc(pe(r.authority_type),"local"),`${Pc(pe(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 xw(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=pe(n.scope_id),i=pe(n.label);if(!r&&!i)return null;const a=i||"Untitled Space",s=pe(n.last_applied_cursor),c=pe(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=Pc(pe(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(m=>!!m).join(" · ");return{scopeId:r||a,label:a,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var YO=["personal","private","home","mine","me"],XO=["oss","open source","opensource","community","public"],QO=["work","client"],ZO=["local","legacy","review"];function e1(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>pe(t)??"").join(" ").toLowerCase()}function t1(e){return[e.scope_id,e.label,e.kind].map(t=>pe(t)??"").join(" ").toLowerCase()}function Dw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fp(e,t){const n=e1(e);return t.some(r=>{const i=Dw(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function Lw(e){return fp(e,YO)||fp(e,XO)}function n1(e){const t=t1(e);return ZO.some(n=>{const r=Dw(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function r1(e){return!Lw(e)&&(!n1(e)||fp(e,QO))}function i1(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(pe(e.discovered_via_group_id)||pe(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(Lw),r=t.some(r1);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 a1(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=Aw(e?.effective_include),n=Aw(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${Ew(t,"all projects")}`,a=`Exclude filter: ${Ew(n,"no exclusions")}`,s=a1(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:a,summary:`${r}. ${i}; ${a}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function s1(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=pe(n?.display_name),i=pe(n?.actor_id),a=jO(r);if(!r||!i||!a)return;const s=t.get(a)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(a,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function $w(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=pe(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const a=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>pe(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||a.add(c)})}),{visibleActors:t.filter(s=>!a.has(pe(s?.actor_id))),hiddenLocalDuplicateCount:a.size}}var c1=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),l1=new Set(["pending","verifying","waiting"]);function d1(e){return(Array.isArray(e?.groups)?e.groups.map(t=>pe(t)).filter(Boolean):[]).join(", ")||"none"}function u1(e){return pe(e?.projects?.[0]?.display_name)||"the shared Project"}function p1(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=ji(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function m1(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&ji(n).state==="mutual-trust"&&!xw(n).rows.some(r=>r.status==="pending"))}function f1(e){return e.some(t=>pe(t.status?.peer_state)==="online"&&ji(t).state==="mutual-trust")}function h1(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=pe(n.status?.peer_state),i=ji(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function g1(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 Mw(e){const t=e.coordinator,n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.shareOperations)?e.shareOperations:[],i=Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],a=d1(t);if(e.status?.enabled===!1||t?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${a}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${a}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const s=r.find(p=>p.lifecycle?.state==="needs_attention"),c=i.find(p=>p.state==="needs_attention");if(s)return{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${a}. 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: ${a}. Team access needs review before it can continue.`,nextAction:"Open Sharing, review Project access, then sync again."};const l=r.find(p=>{const m=p.lifecycle?.state;return m!==void 0&&c1.has(m)}),d=i.find(p=>{const m=p.state;return m!==void 0&&l1.has(m)});if(l||d){const p=l?u1(l):"the shared Project",m=l?.lifecycle?.primary_action?.kind,f=l?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:f?"Removal pending":"Setup pending",meta:f?`Team: ${a}. Future access removal for ${p} is still pending.`:`Team: ${a}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:f?`Keep both devices online, then sync again to finish removing future access for ${p}.`:m==="retry_setup"?`Open Project sharing below and retry setup for ${p}.`:m==="copy_invite"?`Copy the invitation for ${p} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${p}.`}}if(g1(e.status))return{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${a}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."};if(p1(n,t))return{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${a}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."};const u=pe(t?.presence_status);return u==="not_enrolled"?{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${a}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."}:u!=="posted"?{state:"unreachable",badgeLabel:t?.configured?"Unreachable":"Setup needed",meta:t?.configured?`Team: ${a}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:t?.configured?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}:h1(n,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${a}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:t?.sync_enabled===!0&&m1(n,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${a}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:f1(n)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${a}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function v1(e){return e.discovered?.stale?e.peer?co(e.peer)!=="connected":!0:!1}function jw(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 hp(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 y1(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 b1(e){const t=pe(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>pe(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 _1(e,t){const n=new Map,r=i=>{const a=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,a),a};return e.forEach(i=>{const a=pe(i?.peer_device_id);if(!a)return;const s=r(a);s.peer=i,s.localName=pe(i?.name)}),t.forEach(i=>{const a=pe(i?.device_id);if(!a)return;const s=r(a);s.discovered=i,s.coordinatorName=pe(i?.display_name)}),[...n.values()]}function w1(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=_1(n,r),a=e.duplicatePersonDecisions??{},s=s1(t).filter(l=>!a[[...l.actorIds].sort().join("::")]),c=[];return s.forEach(l=>{c.push({id:`duplicate:${l.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:l.includesLocal?5:15,title:`Possible duplicate person: ${l.displayName}`,summary:l.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:l.actorIds})}),i.forEach(l=>{const d=Pw({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId}),u=l.peer?co(l.peer):"waiting",p=l.peer?ji(l.peer):null,m=pe(l.discovered?.fingerprint),f=pe(l.peer?.fingerprint);if(l.peer&&m&&f&&m!==f){c.push(jw({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 y=p?.description||pe(l.peer?.last_error)||"Sync needs review.";c.push(jw({id:l.deviceId,name:d,title:p?.state==="needs-repairing"?`${d} needs re-pairing`:`${d} needs review`,summary:y}))}l.peer&&p?.state==="trusted-by-you"&&c.push(hp({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(hp({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(hp({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&&KO({localName:l.localName,coordinatorName:l.coordinatorName,deviceId:l.deviceId})&&c.push(y1({id:l.deviceId,name:d,summary:"Give this device a friendly name so it is easier to recognize later."}))}),{primaryStatus:Mw({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>co(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>v1(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var Ow={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 er(e){const t=document.getElementById(e);t&&t.remove()}var Fw=!1;function S1(e){Fw=e}var gp=!1;function C1(e){gp=e}var vp=!1;function N1(e){vp=e}var I1=new Set,yp=new Set,bp=new Set,Bw="codemem-sync-duplicate-person-decisions";function k1(e){const t=String(e||"").trim();t&&(yp.add(t),bp.add(t),I1.add(t))}function _p(e){const t=String(e||"").trim();return!!t&&yp.has(t)}function T1(e){const t=String(e||"").trim();t&&yp.delete(t)}function R1(e){const t=String(e||"").trim();return!t||!bp.has(t)?!1:(bp.delete(t),!0)}function wp(){try{const e=localStorage.getItem(Bw);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Uw(e){try{localStorage.setItem(Bw,JSON.stringify(e))}catch{}}function qw(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function P1(){return wp()}function A1(e,t){const n=qw(e);if(!n)return;const r=wp();r[n]=t,Uw(r)}function E1(e){const t=qw(e);if(!t)return;const n=wp();delete n[t],Uw(n)}function Gw(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function Hw(e){const t=String(e||"");return t?Gw(t):""}function x1(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function D1(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Ac(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 Sp(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Ac(e)}function L1(e){return(Array.isArray(S.lastSyncPeers)?S.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function $1(){return $w({actors:S.lastSyncActors,peers:S.lastSyncPeers,duplicatePeople:S.lastSyncViewModel?.duplicatePeople}).visibleActors}function Kw(e){return $1().filter(t=>String(t?.actor_id||"")!==e)}function M1(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 ${Sp(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Cp(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=ds("div","sync-action"),i=ds("div","sync-action-text");i.textContent=n.label,i.appendChild(ds("span","sync-action-command",n.command));const a=ds("button","settings-button sync-action-copy","Copy");a.addEventListener("click",()=>ma(n.command,a)),r.append(i,a),e.appendChild(r)})}}function Vw(e,t){return t&&e.error_redacted===!0}function Ww(){const e=document.getElementById("syncAttempts");if(!e)return;const t=S.lastSyncAttempts,n=String(S.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Ur(e,IO());return}const r=TO(n,t.slice(0,5).some(i=>i.status==="error"));xO(e,t.slice(0,5).map(i=>{const a=i.started_at||i.started_at_utc||"",s=String(i.peer_device_id||"").trim(),c=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===s):null,l=String(c?.name||"").trim()||(s?s.slice(0,8):"unknown"),d=i.status==="error",u=[],p=ha();if(d&&i.error){const m=String(i.error);u.push(p?Gw(m):m),Vw(i,p)&&u.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!d&&(i.ops_in||i.ops_out)&&u.push(`${i.ops_in??0} in · ${i.ops_out??0} out`),!p&&i.address&&u.push(i.address),{status:i.status||"unknown",peerLabel:l,detail:u.join(" · "),startedAt:a?Ar(a):"",...Vw(i,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}}),r)}function j1(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncAttempts"),n=document.getElementById("syncMeta"),r=document.getElementById("syncActions");e&&Ur(e,NO()),t&&Ur(t,kO()),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."),Cp(r,[])}function Oi(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function O1(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=Oi(n.would_remove),a=Oi(n.ambiguous),s=Oi(r.applied),c=Oi(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||a>0?`${a} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function zw(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;er("syncDiagSkeleton");const r=S.lastSyncStatus;if(!r){Ur(e,CO()),Cp(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},a=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=a.last_ping_at||r.last_ping_at||bO(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),m=String(r.daemon_detail||""),f=String(r.daemon_state||"unknown"),y=r.retention||{},g=r.cleanup_diagnostics,h=g?.stale_peer_rows??{},b=Oi(h.would_remove),w=Oi(h.ambiguous),_=y.enabled===!0,I=Number(y.last_deleted_ops||0),N=y.last_run_at||null,T=String(y.last_error||""),x=f==="offline-peers"?"Offline peers":f==="needs_attention"?"Needs attention":f==="rebootstrapping"?"Rebootstrapping":Vy(f),j=f==="disabled"||r.enabled===!1,B=Object.keys(i).length,P=!j&&B===0;if(t){const G=j?["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"]:P?["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: ${x}`,`Peers: ${B}`,c?`Last sync: ${Kn(Ci(c))} ago`:"Last sync: never"];f==="offline-peers"&&G.push("All peers are currently offline; sync will resume automatically"),m&&f==="stopped"&&G.push(`Detail: ${m}`),m&&(f==="needs_attention"||f==="rebootstrapping")&&G.push(`Detail: ${m}`),_&&G.push(N?`Retention last ran ${Kn(Ci(N))} 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 F=j?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:P?[{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:x},{label:"Pending events",value:p},{label:"Last sync",value:c?`${Kn(Ci(c))} ago`:"never"},{label:"Last peer ping",value:l?`${Kn(Ci(l))} ago`:"never"},{label:"Retention",value:_?N?`${I.toLocaleString()} ops last run (approx)`:"Enabled":"Disabled"}];!j&&!P&&(d||u)&&F.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!j&&!P&&s.seconds_since_last&&F.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!j&&!P&&a.seconds_since_last&&F.push({label:"Since last peer ping",value:`${a.seconds_since_last}s`}),!j&&_&&T&&F.push({label:T,value:"Retention"}),!j&&!P&&g&&F.push({label:"Cleanup",value:O1(g)}),EO(e,F);const O=[];P||f==="offline-peers"||(f==="stopped"?(O.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),O.push({label:"Run one sync pass now.",command:"codemem sync once"})):f==="needs_attention"?O.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):f==="rebootstrapping"?O.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||f==="error"?(O.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),O.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!j&&!P&&p>0&&O.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!j&&w>0?O.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!j&&b>0&&O.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Cp(n,O)}var F1="syncRedactMount",B1="syncRedactLabel",Jw=()=>{};function U1(e){Jw=e}var Np=()=>{};function Ip(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;MO(e,{contentHost:t,open:S.syncPairingOpen,onOpenChange:r=>{if(pR(r),Ip(),r){const i=document.getElementById("pairingPayload"),a=document.getElementById("pairingHint");i&&ww(i,a,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Np()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=S.pairingCommandRaw;r&&await ma(r,n)})}function kp(){Ip();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;ww(e,t,SO(S.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!S.pairingCommandRaw)}function Yw(){const e=document.getElementById(F1);e&&at(e,v(bi,{"aria-labelledby":B1,checked:ha(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{mR(t),Yw(),Np(),zw(),Jw(),Ww(),kp()},thumbClassName:"sync-redact-switch-thumb"}))}function q1(e){Np=e,Ip(),Yw()}function G1(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function Fi(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),G1(e),e.addEventListener("input",()=>lo(e),{once:!0}),!1}function lo(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function lt(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 qr=new Map,Tp=null,H1={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 K1(e){return H1[e instanceof Error?e.message:String(e)]??"Setup could not be retried. Review diagnostics for details."}function V1(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 W1(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Rp(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 z1({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[a,s]=D(!1),[c,l]=D(()=>qr.get(e.operation_id)??null),d=q(null),u=e.lifecycle.primary_action;W(()=>{Tp!==e.operation_id||!d.current||(Tp=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"};qr.set(e.operation_id,b),l(b)}catch(h){const b={message:h instanceof Error?h.message:"Invite could not be copied.",tone:"warning"};qr.set(e.operation_id,b),l(b)}finally{s(!1)}}async function m(){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"};qr.set(e.operation_id,h),Tp=e.operation_id,l(h),await r()}catch(g){const h={message:K1(g),tone:"warning"};qr.set(e.operation_id,h),l(h),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function f(){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"};qr.set(e.operation_id,h),l(h);return}if(!Qo(g,e.person.display_name)){const h={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};qr.set(e.operation_id,h),l(h)}}function y(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){m();return}f()}}return o("section",{"aria-label":`${Rp(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[o("div",{className:"peer-scope-summary",children:Rp(e.lifecycle.state)}),o("ul",{"aria-label":`${Rp(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((g,h)=>o("li",{className:"peer-scope-chip",children:g.display_name},`${g.display_name}:${h}`))}),o("div",{className:"peer-scope-summary",children:e.lifecycle.label}),o("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?o("div",{className:"peer-actions",children:o("button",{"aria-busy":a,className:"settings-button",disabled:a,type:"button",onClick:y,children:a?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?o("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function J1({operations:e,...t}){const n=e[0].person,r=W1(e);return o("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[o("h3",{className:"device-row-name",children:n.display_name}),r.length>0?o("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>o("li",{children:i.display_name},i.device_id))}):null,e.map(i=>o(z1,{operation:i,...t},i.operation_id))]})}function Y1(e){return e.operations.length===0?null:o("div",{className:"project-share-person-groups",children:V1(e.operations).map(t=>o(J1,{...e,operations:t},t[0].person.actor_id))})}function X1(e,t){at(e,o(Y1,{...t}))}function Xw({title:e,detail:t}){return o("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[o("strong",{children:e}),o("span",{children:t})]})}function Q1(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 Z1({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const a=String(e.actor_id||""),s=Ac(e),c=L1(a),l=Kw(a),d=l.map(O=>String(O.actor_id||"")).join("|"),[u,p]=D(s),[m,f]=D(!1),[y,g]=D("Rename"),[h,b]=D(!1),[w,_]=D("Merge into selected person"),[I,N]=D(""),[T,x]=D(!1);W(()=>{p(s),f(!1),g("Rename"),b(!1),_("Merge into selected person"),N(""),x(!1)},[a,c,t,s,d]);const j=l.length?M1(I,a):"No other people are available yet. Create another person first if you need to merge duplicates.",B=[{label:"Merge into person",value:""},...l.map(O=>{const G=String(O.actor_id||"");return{label:O.is_local?Sp(O):Ac(O),value:G}})];async function P(){const O=u.trim();if(!O)return;f(!0),g("Saving…");let G=!1;try{await n(a,O),G=!0}catch{g("Retry rename")}finally{f(!1),G&&g("Rename")}}async function F(){if(!I)return;const O=l.find($=>String($.actor_id||"")===I);if(!O||!await Xt({title:`Merge ${s} into ${Ac(O)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;b(!0),_("Merging…");let G=!1;try{await r(I,a),G=!0}catch{_("Retry merge")}finally{b(!1),G&&_("Merge into selected person")}}return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:Sp(e)}),o("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?Q1(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:o("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),o("div",{className:"actor-actions",children:e.is_local?o("div",{className:"peer-meta",children:"Rename yourself in config"}):o(z,{children:[o(_e,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:m||h,type:"text",value:u,onInput:O=>p(O.currentTarget.value),onKeyDown:O=>ui(O,{onSubmit:()=>{P()},disabled:m||h||!u.trim()})}),o("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:m||h,onClick:()=>{P()},children:y}),o("button",{type:"button",className:"settings-button danger",disabled:m||h,onClick:async()=>{await Xt({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(a)},children:"Remove"}),o("button",{type:"button",className:"settings-button",disabled:m||h,onClick:()=>x(O=>!O),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?o(z,{children:[o("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),o("div",{className:"actor-merge-controls",children:[o(Hn,{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:N,options:B,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:I,viewportClassName:"sync-radix-select-viewport"}),o("button",{type:"button",className:"settings-button",disabled:h||l.length===0||!I,onClick:()=>{F()},children:w})]}),o("div",{className:"peer-meta actor-merge-note",children:j})]}):null]})})]})}function eF({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?o(z,{children:e.map(a=>{const s=String(a.actor_id||a.display_name||a.is_local||"");return o(Z1,{actor:a,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):o(Xw,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function tF(e,t){at(e,o(eF,{...t}))}function nF(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function rF(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${Ar(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function iF({devices:e}){return o(z,{children:rF(e)})}function aF(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=nF(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),Mi(e.mount),Mi(e.meta);return}const n=t.map(aF),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,at(e.mount,o(Hn,{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"})),at(e.meta,o(iF,{devices:t}))}var sF={online:"Online",offline:"Offline",degraded:"Degraded",attention:"Action required",syncing:"Syncing",unknown:"Status unknown"};function cF({state:e,size:t=8,"aria-label":n}){return o("span",{"aria-label":n??sF[e],className:`presence-pip presence-pip--${e}`,role:"img",style:`--presence-pip-size: ${t}px`})}function Gr({feedback:e}){return e?.message?o("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function lF(){return o("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[o("title",{children:"Chevron"}),o("path",{d:"m9 18 6-6-6-6"})]})}function dF(e){switch(co(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Ec=null,Qw=0,Pp=new Set;function Zw(e){if(Ec!==e){Ec=e,Qw+=1;for(const t of Pp)t(Qw)}}function uF(){const[,e]=D(0);return W(()=>(Pp.add(e),()=>{Pp.delete(e)}),[]),Ec}var pF={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 eS(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 mF(e,t,n,r=!1,i=!1,a=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||a&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${eS(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: ${eS(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 fF(e){S.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function hF(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 gF(){window.location.hash="advanced/teams"}function Ap(e=S.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function vF({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),a=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||a,c=ji(e),l=pF[VO(e)],d=e.status||{},u=JO(e),p=_p(i),m=p&&u.total===0,f=i1(e),y=zO(e),g=xw(e),h=o1(e.project_scope||{}),b=x1(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(te=>String(te)))):[],_=Number(e.address_count??0),I=Number.isFinite(_)&&_>0?_:0,N=w.length?w.map(te=>ha()?Hw(te):te).join(" · "):I>0?`${I} ${I===1?"address":"addresses"} hidden`:"No addresses",T=S.lastDeviceIdentityInventory?.items.find(te=>te.deviceId===i||te.evidenceDeviceIds.includes(i)),x=mF(T,String(e.actor_id||"")||null,S.lastSyncActors,S.deviceIdentityInventoryLoadError,S.lastDeviceIdentityInventory?.truncated===!0,S.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),j=String(d.last_sync_at||d.last_sync_at_utc||""),B=String(d.last_ping_at||d.last_ping_at_utc||""),P=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,F=R1(i),O=q(null),[G,$]=D(a),[A,E]=D(()=>S.syncPeerFeedbackById.get(i)??null),[C,L]=D(!1),[U,V]=D("Save name"),[de,ie]=D(!1),[ne,Re]=D(!1),[ye,Ce]=D("Remove device");W(()=>{p&&u.total>0&&T1(i)},[u.total,i,p]),W(()=>{$(a),E(S.syncPeerFeedbackById.get(i)??null),L(!1),V("Save name"),ie(!1),Re(!1),Ce("Remove device")},[a,e.actor_id,i]),W(()=>{!F||!O.current||queueMicrotask(()=>O.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[F]);async function re(){if(!i)return;const te=G.trim();if(!te){const Qe={message:"Enter a friendly name for this device.",tone:"warning"};E(Qe),S.syncPeerFeedbackById.set(i,Qe),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}L(!0),V("Saving…");try{const Qe=await n(i,te);E(Qe),S.syncPeerFeedbackById.set(i,Qe),V("Save name")}catch{V("Retry")}finally{L(!1)}}async function Pe(){if(m){const te=Ap();if(!await Xt({title:`Sync ${a} before advanced rule review?`,description:te?"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:te?"Review legacy Team/Space setup first":"Cancel"}))return}ie(!0);try{const te=await r(e,b);E(te),te&&S.syncPeerFeedbackById.set(i,te)}finally{ie(!1)}}async function ue(){if(!i||!await Xt({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;Re(!0),Ce("Removing…");let te=!1;try{await t(i,s),te=!0}catch{Ce("Retry remove")}finally{Re(!1),te&&Ce("Remove device")}}const H=uF()===i&&i!=="",fe=`device-drawer-${i||"unknown"}`,ae=dF(e),Te=j?`Sync: ${Ar(j)}`:"Sync: never",ce=Ap(),Be=`${H?"Collapse":"Expand"} device ${a}`;return o(ba,{asChild:!0,open:H,onOpenChange:te=>{te?Zw(i):Ec===i&&Zw(null)},children:o("div",{ref:O,className:"peer-card","data-peer-device-id":i||void 0,children:[o(bd,{asChild:!0,children:o("button",{"aria-label":Be,className:"device-row-head device-row-head--trigger",type:"button",children:[o(cF,{state:ae}),o("span",{className:"device-row-name",title:i||void 0,children:a}),l?o("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,o("span",{className:"device-row-chips",children:[o("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),m?o("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,o("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),y.badgeLabel?o("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:y.badgeLabel}):null,f.badgeLabel?o("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:f.badgeLabel}):null,e.discovered_via_group_id?o("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),o("span",{className:"device-row-meta",children:Te}),o("span",{"aria-hidden":"true",className:"device-row-chevron",children:o(lF,{})})]})}),o(_a,{"aria-label":`Device actions for ${a}`,className:"device-row-drawer",id:fe,children:[o("div",{className:"peer-actions",children:[o("button",{type:"button",className:"settings-button",disabled:de,onClick:()=>{Pe()},title:b?void 0:"Address details are hidden; sync will target this device by ID.",children:de?"Syncing…":"Sync now"}),o("div",{className:"sync-labeled-field",children:[o("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),o(_e,{"aria-label":`Friendly name for ${a}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:C,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:G,onInput:te=>$(te.currentTarget.value)})]}),o("button",{type:"button",className:"settings-button",disabled:C,onClick:()=>{re()},children:U}),o("button",{type:"button",className:"settings-button danger",disabled:ne,onClick:()=>{ue()},children:ye})]}),o("div",{className:"peer-scope",children:[F?o("div",{className:"peer-meta",children:ce?"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."}):m?o("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,o("div",{className:"peer-scope-summary",children:"Device details"}),o("div",{className:"peer-addresses",children:N}),P?o("div",{className:"peer-meta",children:P}):null,o("div",{className:"peer-meta",children:[j?`Sync: ${Ar(j)}`:"Sync: never",B?`Ping: ${Ar(B)}`:"Ping: never"].join(" · ")}),o("div",{className:"peer-scope-summary",children:"Space access"}),o("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?o("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(te=>o("li",{className:"peer-scope-chip",title:te.detail,children:te.label},te.scopeId))}):null,f.isVisible?o("div",{className:"settings-note",role:"status",children:[o("strong",{children:f.title}),o("div",{children:f.message}),o("div",{children:f.detail})]}):null,o("div",{className:"peer-meta",children:h.note}),o("div",{className:"peer-scope-summary",children:"Space sync progress"}),o("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?o("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:g.rows.map(te=>o("li",{title:te.detail,children:[o("span",{className:"peer-scope-rejection-label",children:te.label}),o("span",{className:`badge ${te.status==="received"?"badge-online":"actor-badge"}`,children:te.badgeLabel})]},te.scopeId))}):null,y.total>0?o("div",{className:"peer-scope-rejections","data-peer-rejection-count":y.total,children:[o("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),o("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),o("ul",{className:"peer-scope-rejections-list",children:y.reasons.map(te=>o("li",{children:[o("span",{className:"peer-scope-rejection-label",children:te.label}),o("span",{className:"peer-scope-rejection-count",children:te.count.toLocaleString()})]},te.reason))}),y.lastAt?o("div",{className:"peer-meta",children:["Last rejected ",Ar(y.lastAt)]}):null]}):null,o("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),o("div",{className:"peer-meta",children:x.summary}),o("div",{className:"peer-meta",children:x.detail}),e.claimed_local_actor?o("div",{className:"peer-meta",children:hF(e.claimed_local_actor_scope)}):null,o("div",{className:"peer-actor-row",children:o("button",{type:"button",className:"settings-button",onClick:()=>fF(T?.deviceId??i),children:x.actionLabel})}),o("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),o("div",{className:"peer-meta",children:[h.statusLabel,". ",h.summary," ",h.note]}),ce?o("div",{className:"peer-actions",children:o("button",{type:"button",className:"settings-button",onClick:gF,children:"Open Coordinator Administration"})}):o("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),o(Gr,{feedback:A})]})]})]})})}function yF(e){const t=S.syncPeersSectionFeedback,n=S.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?o(z,{children:[o(Gr,{feedback:t}),e.peers.map(i=>{const a=String(i.peer_device_id||i.name||"unknown-peer");return o(vF,{peer:i,...e},a)})]}):o(z,{children:[o(Gr,{feedback:t}),o(Xw,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function bF(e,t){at(e,o(yF,{...t}))}var tr=async()=>{},xc="";function Ep(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function _F(e){tr=e}function wF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;er("syncActorsSkeleton"),Ep(!1);const n=$w({actors:S.lastSyncActors,peers:S.lastSyncPeers,duplicatePeople:S.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.`)),tF(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,a)=>{await oN(i,a),await tr()},onMerge:async(i,a)=>{try{await xm(i,a),J("People combined. Assigned devices moved to the selected person."),await tr()}catch(s){throw J(lt(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await sN(i),J("Person removed. Assigned devices have been unassigned."),await tr()}catch(a){throw J(lt(a,"Failed to remove person."),"warning"),a}}})}function SF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Ep(!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&&Ur(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function CF(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;X1(e,{operations:S.lastShareOperations,onAdvance:n=>YC(n),onLoadOperation:n=>JC(n),onReload:tr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=S.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":S.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function xp(){const e=document.getElementById("syncPeers");if(!e)return;er("syncPeersSkeleton");const t=S.lastSyncPeers,n=Array.isArray(t)?t:[];D1(S.syncPeersSectionFeedback,n)&&(S.syncPeersSectionFeedback=null),bF(e,{peers:n,onRename:async(r,i)=>{try{return await ym(r,i),await tr(),{message:"Device name saved.",tone:"success"}}catch(a){return{message:lt(a,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const a=String(r?.peer_device_id||""),s=Tw(await Zc({address:i,peerDeviceId:a||void 0}));let c;s.ok?a&&_p(a)?c={message:`Triggered sync for ${r?.name||(a?a.slice(0,8):"unknown")}. ${Ap()?"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"}:c={message:s.message,tone:"success"}:c={message:s.message,tone:"warning"};try{await tr()}catch{c={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return c}catch(a){return{message:lt(a,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await vm(r);const a={message:`Removed peer ${i}.`,tone:"success"};return S.syncPeerFeedbackById.delete(r),S.syncPeersSectionFeedback={...a,relatedPeerDeviceId:r},await tr(),a}catch(a){return{message:lt(a,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function NF(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Ep(!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&&Ur(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&&Ur(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 tS(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");!e||!t||!n||oF({devices:Array.isArray(S.lastSyncLegacyDevices)?S.lastSyncLegacyDevices:[],meta:n,mount:t,onValueChange:r=>{r!==xc&&(xc=r,tS())},panel:e,value:xc})}function IF(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{ui(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){Fi(n,"Enter a name for the person.");return}lo(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await aN(i),J("Person created."),n.value="",await e()}catch(a){J(lt(a,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(xc||"").trim();if(!i||!r||!await Xt({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const a=r.textContent||"Attach device history";r.textContent="Attaching…";try{await cN(i),J("Old device history attached to you."),await e()}catch(s){J(lt(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=a,r.disabled=!1})}function kF(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function Dp(e=kF()){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 nS=!1;function TF(){nS||(nS=!0,window.addEventListener("hashchange",()=>{Dp()}))}var nn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function RF(e){nn.loadSyncData=e}var PF=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function AF(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=S.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 Lp(){const e=document.getElementById("syncAdminDisclosureMount");e&&$O(e,{open:Fw,onOpenChange:t=>{S1(t),Lp(),Lc(),$p()}})}function EF(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function $p(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(S.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(S.lastTeamInvite?.warnings)?S.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Dc(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=S.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 Lc(){const e=document.getElementById("syncInvitePolicyMount");e&&at(e,v(Hn,{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!==nn.invitePolicy&&(nn.invitePolicy=n,Lc())},options:PF,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:nn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function xF(e,t){Lp(),Lc();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),a=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),m=document.getElementById("syncProjectInviteReviewHeading"),f=document.getElementById("syncRecipientName"),y=document.getElementById("syncRecipientDeviceName");let g="",h,b=0;r?.addEventListener("click",()=>{Qo()||J("Project sharing is unavailable. Refresh Projects and try again.","warning")});const w=async(_,I)=>{if(!u||!f||!y)return"other";const N=await gm(_);if(I!==b||d?.value.trim()!==_)return"stale";if(h=N.kind,N.kind!=="project_share_invite")return"other";const T=(N.projects??[]).map(x=>`${x.display_name} (${x.existing_memory_count} existing ${x.existing_memory_count===1?"memory":"memories"})`).join(", ");return p&&(p.textContent=`${N.inviter_name||"A teammate"} invited you${N.team_name?` through ${N.team_name}`:""} to share ${T||"selected projects"}.`),f.value=ai(N.recipient_name),y.value=ai(N.device_name),u.hidden=!1,g=_,l&&(l.textContent="Accept and start syncing"),m?.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||!a||!s||!c||i.disabled)return;const _=a.value.trim(),I=Number(s.value);let N=!0;if(_?lo(a):N=Fi(a,"Team name is required."),!I||I<1?N=Fi(s,"Must be at least 1 hour."):lo(s),!!N){i.disabled=!0,i.textContent="Creating…";try{const T=await pm({group_id:_,policy:nn.invitePolicy,ttl_hours:I||24});S.lastTeamInvite=T,$p(),c.value=String(T.encoded||""),c.hidden=!1,c.focus(),c.select();const x=Array.isArray(T.warnings)?T.warnings:[];J(x.length?`Invite created. Copy it above and review ${x.length===1?"1 warning":`${x.length} warnings`}.`:"Invite created. Copy the text above and share it with your teammate.",x.length?"warning":"success")}catch(T){J(lt(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",_=>{ui(_,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d)return;const _=d.value.trim();if(!_){Fi(d,"Paste a team invite or pairing payload.");return}if(lo(d),g!==_){const N=b;try{const T=await w(_,N);if(T==="project"||T==="stale")return}catch{}if(N!==b||d.value.trim()!==_)return;g=_,l.textContent="Accept invite";return}const I=u&&!u.hidden?{recipient_name:f?.value.trim()??"",device_name:y?.value.trim()??""}:void 0;if(I){const N=T=>ai(T)==="";if(N(I.recipient_name)){f&&Fi(f,"Enter a human-readable name using 120 characters or fewer.");return}if(N(I.device_name)){y&&Fi(y,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const N=await Wc(_,I,h);S.lastTeamJoin=N;const T=N,x=typeof T.type=="string"?T.type:"team_join";let j;if(x==="pair"){const B=String(N.peer_device_id??"").trim();j={message:B?`Paired with device ${B.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}else if(x==="project_share"){const B=T.restart_required===!0||T.setup_state==="pending_inviter"||N.status==="pending_setup",P=typeof T.detail=="string"?T.detail.trim():"";j=B?{message:P||(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 j={message:N.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"};S.syncJoinFlowFeedback=j,Dc(),d.value="",g="",u&&(u.hidden=!0);try{await t()}catch(B){j={message:lt(B,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},S.syncJoinFlowFeedback=j,Dc()}}catch(N){S.syncJoinFlowFeedback={message:lt(N,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Dc(),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 _=Tw(await Zc());J(_.message,_.warning?"warning":void 0)}catch(_){J(lt(_,"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 Mp({element:e,hidden:t=!1,restoreParent:n=null}){const r=q(null);return gt(()=>{e&&(e.hidden=t)},[e,t]),gt(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),o("div",{ref:r})}function DF({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return o(z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Invite a teammate.",o("span",{className:"sync-action-command",children:"Generate an invite when you want someone else to join this team from their device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide invite form":"Invite a teammate"})]}),e?o(Mp,{element:e,hidden:!t,restoreParent:n}):null]})}function LF(){return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Pair another device.",o("span",{className:"sync-action-command",children:"Copy a pairing command when you want to connect another one of your own devices."})]}),o("button",{type:"button",className:"settings-button sync-action-copy",onClick:e=>ma("codemem sync pair --payload-only",e.currentTarget),children:"Copy pairing command"})]})}function $F({joinPanel:e,joinPanelOpen:t,joinRestoreParent:n,onToggle:r}){return o(z,{children:[o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:["Accept an invite or pairing.",o("span",{className:"sync-action-command",children:"Paste a team invite to join another team, or a pairing payload to connect another device."})]}),o("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide paste form":"Paste invite or pairing"})]}),e?o(Mp,{element:e,hidden:!t,restoreParent:n}):null]})}function MF({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggleInvitePanel:s,onToggleJoinPanel:c,pairedPeerCount:l,presenceStatus:d}){const u=d==="not_enrolled";return o(z,{children:[u?o(z,{children:[o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["Join this device.",o("span",{className:"sync-action-command",children:"Paste a team invite or pairing payload below to join an existing team or connect another of your devices."})]})}),r?o(Mp,{element:r,hidden:!1,restoreParent:a}):null,o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0}),o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:["This device is not on the team yet.",o("span",{className:"sync-action-command",children:"Use Join this device above, or ask an admin to enroll it first."})]})})]}):o(z,{children:[o($F,{joinPanel:r,joinPanelOpen:i,joinRestoreParent:a,onToggle:c}),o("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),u?null:o(DF,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:s}),!l&&d==="posted"?o(LF,{}):null]})}function $c({count:e,label:t}){return o("div",{className:"sync-section-heading",children:[o("div",{className:"sync-action-text sync-section-label",children:t}),e?o("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function Mc({children:e}){return o("div",{className:"section-meta sync-section-note",children:e})}function jF({item:e,onAction:t}){const[n,r]=D(!1);return o("div",{className:"sync-action",children:[o("div",{className:"sync-action-text",children:[e.title,o("span",{className:"sync-action-command",children:e.summary})]}),o("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function OF({request:e,onApprove:t,onDeny:n}){const[r,i]=D(null),[a,s]=D(null),[c,l]=D("Approve"),[d,u]=D("Deny");return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:o("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),o("div",{className:"actor-actions",children:[o("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),o("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),o(Gr,{feedback:a})]})}function FF({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){const[i,a]=D(null),[s,c]=D(null),l=e.actionLabel||"Pair with this device",[d,u]=D(l),[p,m]=D("Remove broken device record");return o("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[o("div",{className:"peer-title",children:[o("strong",{title:e.displayTitle||void 0,children:e.displayName}),o("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),o("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?o("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),o("div",{className:"peer-meta",children:e.note}),o("div",{className:"peer-actions",children:[e.mode==="accept"?o("button",{type:"button",className:"settings-button","aria-label":`${d} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("review"),u("Pairing…"),c({message:`Pairing ${e.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const f=await r(e)||null;c(f),u(f?.tone==="warning"?"Retry":e.actionLabel||l)}catch{c({message:`Pairing ${e.displayName} failed. Try again.`,tone:"warning"}),u("Retry")}finally{a(null)}},children:d}):null,(e.mode==="stale"||e.mode==="approval-pending"||e.mode==="ambiguous"||e.mode==="scope-pending"||e.mode==="setup-blocked")&&e.actionMessage?o("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?o("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?o(z,{children:[o("button",{type:"button",className:"settings-button","aria-label":`Open details for ${e.displayName}`,disabled:i!==null,onClick:()=>t(e),children:"Open device details"}),o("button",{type:"button",className:"settings-button danger","aria-label":`${p} for ${e.displayName}`,disabled:i!==null,onClick:async()=>{a("remove"),m("Removing…");try{c(await n(e)||null),m("Remove broken device record")}catch{m("Retry")}finally{a(null)}},children:p})]}):null]}),o(Gr,{feedback:s})]})}function BF(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return o(z,{children:[r?o($c,{label:"Needs attention"}):null,r?o(Mc,{children:"Start here when something needs review, re-pairing, or approval."}):null,e.primaryStatus.nextAction?o("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:o("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,o("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>o(jF,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null,!t&&n?o("div",{className:"sync-action",children:o("div",{className:"sync-action-text",children:"More team follow-up is listed below when you are ready."})}):null]})}function UF({children:e}){return e?o(z,{children:[o($c,{label:"Add devices & teammates"}),o(Mc,{children:"Use these flows when you are enrolling, inviting, or pairing something new."}),e]}):null}function qF({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!S.syncDiscoveredFeedback?null:dn(o(z,{children:[o($c,{count:t.length||void 0,label:"Devices waiting for review"}),o(Mc,{children:"Review team devices here when they still need trust, re-pairing, or approval on this machine."}),o(Gr,{feedback:S.syncDiscoveredFeedback}),t.map(a=>o(FF,{row:a,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${a.deviceId}:${a.incomingRequestId}:${a.fingerprint}`))]}),e)}function GF({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!S.syncJoinRequestsFeedback?null:dn(o(z,{children:[o($c,{count:t.length||void 0,label:"Join requests to review"}),o(Mc,{children:"Approve or deny requests here before those devices become part of the team."}),o(Gr,{feedback:S.syncJoinRequestsFeedback}),t.map(i=>o(OF,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function rS(e){return o(z,{children:[o(BF,{...e}),o(UF,{children:e.children}),o(GF,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),o(qF,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function iS(e){e&&(e.textContent="")}function jc(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 HF(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function uo(){return HF()?"auto":"smooth"}var jp="syncTeamActionsMount",KF="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function VF(e,t,n=!1){return e.length>1&&(!t||n)}function WF(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 zF(e,t){const n=document.createElement("div");n.id=jp,e.appendChild(n),at(n,v(rS,{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 aS(e,t){const n=document.getElementById(jp);n&&(Mi(n),n.remove()),iS(e),t.forEach(r=>{iS(r)})}function po(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Lp(),Lc(),$p(),Dc(),AF();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),a=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");er("syncTeamSkeleton"),EF();const p=S.lastSyncCoordinator,m=S.lastSyncViewModel||{primaryStatus:Mw({status:S.lastSyncStatus,coordinator:p,peers:S.lastSyncPeers,shareOperations:S.lastShareOperations,shareOperationsLoadError:S.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]},f=E=>{if(E.kind==="possible-duplicate-person"){const V=document.getElementById("syncActorsList");V instanceof HTMLElement&&(V.scrollIntoView({block:"center",behavior:uo()}),jc(V));return}const C=String(E.deviceId||"").trim();if(!C)return;if(E.kind==="name-device"){const V=document.querySelector(`[data-device-name-input="${CSS.escape(C)}"]`);if(V instanceof HTMLInputElement){V.scrollIntoView({block:"center",behavior:uo()}),V.focus(),V.select(),jc(V);return}}const L=document.querySelector(`[data-peer-device-id="${CSS.escape(C)}"]`);if(L instanceof HTMLElement){L.scrollIntoView({block:"center",behavior:uo()}),jc(L);return}const U=document.querySelector(`[data-discovered-device-id="${CSS.escape(C)}"]`);U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:uo()}),jc(U))},y=async E=>{const C=Array.isArray(E.actorIds)?E.actorIds.map(ie=>String(ie||"").trim()).filter(Boolean):[],L=(Array.isArray(S.lastSyncActors)?S.lastSyncActors:[]).filter(ie=>C.includes(String(ie?.actor_id||"").trim()));if(L.length<2){J("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const U=await PE({title:"Review possible duplicate people",summary:E.title.replace(/^Possible duplicate person:\s*/,""),actors:L.map(ie=>({actorId:String(ie?.actor_id||""),label:String(ie?.display_name||ie?.actor_id||"Unknown person"),isLocal:!!ie?.is_local}))});if(U.action==="different-people"){A1(C,"different-people"),J("Okay. I will keep these people separate on this device."),await nn.loadSyncData();return}if(U.action!=="merge")return;const V=L.find(ie=>String(ie?.actor_id||"")===U.primaryActorId),de=L.find(ie=>String(ie?.actor_id||"")===U.secondaryActorId);if(!V?.actor_id||!de?.actor_id){J("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await xm(String(V.actor_id),String(de.actor_id)),E1(C),J(`Combined duplicate people into ${String(V.display_name||V.actor_id)}.`),await nn.loadSyncData()}catch(ie){try{await nn.loadSyncData()}catch{}J(lt(ie,"Failed to combine these people."),"warning")}},g=async E=>await Qd({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:C=>C.trim()?null:"Enter a device name to pair this device."}),h=!!p?.configured,b=b1(p);e.title=h?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?WF(w,e,m.primaryStatus):e.textContent=m.primaryStatus.meta,!h){aS(n,[c,u]),t.hidden=!1,n.hidden=!1,zF(n,m.primaryStatus),c&&(c.hidden=!0),l&&(l.hidden=!0);return}t.hidden=!0,n.hidden=!1;const _=String(p.presence_status||""),I=Array.isArray(S.lastSyncPeers)?S.lastSyncPeers:[],N=Array.isArray(m.attentionItems)?m.attentionItems:[],T=Array.isArray(p.discovered_devices)?p.discovered_devices:[],x=String(p.coordinator_url||"").trim(),j=T.map(E=>{const C=String(E.device_id||"").trim(),L=Pw({coordinatorName:String(E.display_name||"").trim(),deviceId:C})||"Discovered device",U=C&&L!==C?C:null,V=String(E.fingerprint||"").trim(),de=String(E.incoming_reciprocal_request_id||"").trim(),ie=Array.isArray(E.groups)?E.groups.map($e=>String($e||"").trim()).filter(Boolean):[],ne=I.find($e=>String($e?.peer_device_id||"")===C),Re=VF(ie,!!ne,E.needs_local_approval===!0),ye=kw({device:E,pairedLocally:!!ne}),Ce=String(ne?.fingerprint||"").trim(),re=!!ne&&!!V&&!!Ce&&Ce!==V,Pe=S.pendingCoordinatorApprovalsByDeviceId.get(C),ue=E.needs_local_approval===!0&&Pe?.coordinatorUrl===x&&Pe?.incomingRequestId===de,H=ue?"approval-pending":E.needs_local_approval===!0?"needs-local-approval":"not-required",fe=!ue&&!b&&BO({device:E,hasAmbiguousCoordinatorGroup:Re,pairedLocally:!!ne}),ae=Array.isArray(E.addresses)?E.addresses:[],Te=Number(E.address_count??0),ce=Number.isFinite(Te)&&Te>0?Te:0,Be=[ae.length?ae.map($e=>ha()?Hw(String($e||"")):String($e||"")).filter(Boolean).join(" · "):ce>0?`${ce} ${E.stale?"last-known":"fresh"} ${ce===1?"address":"addresses"} hidden`:"No fresh addresses"];!ae.length&&U&&Be.push(`device id: ${C}`);let Z=null,te=fe?"accept":"none",Qe=null;return re?te="conflict":ue?(Z="Waiting for refreshed coordinator status. You do not need to approve again.",te="approval-pending"):b&&(!ne||ye.state==="needs-your-approval")?(Z=b.message,te="setup-blocked"):Re?(Z="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",te="ambiguous"):ne&&_p(C)?(Z="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",te="scope-pending"):ne?.last_error?(Be.push(`error: ${String(ne.last_error)}`),fe||(te="paired")):ne?.status?.peer_state?(Be.push(`status: ${String(ne.status.peer_state)}`),fe||(te="paired")):!ne&&E.stale?(Z="Wait for a fresh coordinator presence update, then review this device again here.",te="stale"):ne&&!fe&&(te="paired"),te==="paired"&&(Qe=ye.state==="waiting-for-other-device"?ye.description||"Waiting on the other device.":String(ne?.last_error||"").toLowerCase().includes("401")&&String(ne?.last_error||"").toLowerCase().includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null),{actionMessage:Z,actionLabel:ye.actionLabel||(ne?"Review device":"Pair with this device"),approvalBadgeLabel:ue?"Approval sent":ye.badgeLabel,approvalState:H,availabilityLabel:E.stale?"Offline":"Available",connectionLabel:re?Ow.conflicts:ne?Ow.pairedLocally:"Not connected on this device",coordinatorUrl:x,deviceId:C,displayName:L,displayTitle:U,fingerprint:V,groupId:ie[0]??"",incomingRequestId:de,mode:te,note:Be.join(" · "),pairedMessage:Qe}}),B=new Set(j.filter(E=>E.approvalState==="approval-pending").map(E=>E.deviceId)),P=N.filter(E=>!E.deviceId||!B.has(E.deviceId)),F=[],O=j.filter(E=>E.mode!=="paired"&&E.mode!=="none"&&E.mode!=="scope-pending"),G=j.filter(E=>E.mode==="accept"||E.mode==="scope-pending").length,$=P.length+F.length+G;l&&(l.hidden=O.length===0&&!S.syncDiscoveredFeedback),d&&(d.textContent=O.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=F.length===0&&!S.syncJoinRequestsFeedback),aS(n,[c,u]);const A=document.createElement("div");A.id=jp,n.appendChild(A),at(A,v(rS,{actionItems:P,actionableCount:$,children:v(MF,{invitePanel:r,invitePanelOpen:gp,inviteRestoreParent:i,joinPanel:a,joinPanelOpen:vp,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(C1(!gp),po())},onToggleJoinPanel:()=>{a&&(N1(!vp),po())},pairedPeerCount:Number(p.paired_peer_count||0),presenceStatus:_}),discoveredListMount:u,discoveredRows:O,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async E=>{if(E.kind==="possible-duplicate-person"){await y(E);return}f(E)},onDenyJoinRequest:async()=>null,onInspectConflict:E=>{const C=document.querySelector(`[data-peer-device-id="${CSS.escape(E.deviceId)}"]`);if(C instanceof HTMLElement){C.scrollIntoView({block:"center",behavior:uo()}),J(`Opened the conflicting local device record for ${E.displayName}.`,"warning");return}J("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async E=>{if(!await Xt({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 vm(E.deviceId);const C={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 S.syncDiscoveredFeedback=C,await nn.loadSyncData(),C}catch(C){return{message:lt(C,"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 C=await g(E.displayName);return C?await JF(E,C):null}catch(C){return{message:lt(C,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:F,presenceStatus:_,primaryStatus:m.primaryStatus}))}async function JF(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),a=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!a||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await wC(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:a||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&S.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s}),S.pendingAcceptedSyncPeers=[...Array.isArray(S.pendingAcceptedSyncPeers)?S.pendingAcceptedSyncPeers.filter(u=>String(u?.peer_device_id||"").trim()!==e.deviceId):[],{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],k1(e.deviceId);let d=n?{message:KF,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"};S.syncDiscoveredFeedback=d,n&&po();try{t.trim()!==l.trim()&&(await ym(e.deviceId,t.trim()),S.pendingAcceptedSyncPeers=S.pendingAcceptedSyncPeers.map(u=>String(u?.peer_device_id||"").trim()===e.deviceId?{...u,name:t.trim()}:u),n||(d={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(u){d={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":lt(u,"Device connected, but naming did not finish."),tone:"warning"}}S.syncDiscoveredFeedback=d;try{await nn.loadSyncData()}catch(u){d={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":lt(u,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},S.syncDiscoveredFeedback=d}return d}function YF(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 Bi(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function oS(e){return Bi(e)?"Unclear project identity":e.displayProject}function Et(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function XF(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function QF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ZF(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function eB(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function tB(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 nB(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function rB({group:e}){const t=e.memorySamples??[],n=t.length;return o("details",{className:"legacy-review-samples",children:[o("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),o("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?o("ul",{className:"legacy-review-sample-list",children:t.map(r=>o("li",{className:"legacy-review-sample",children:[o("div",{className:"legacy-review-sample-title",children:r.title}),o("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",tB(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?o("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,o("div",{className:"legacy-review-group-meta mono",children:nB(r)})]},r.id))}):o("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function sS(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${QF(t)}\\b`,"g"),ZF(t,n))),r}function iB(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 aB({item:e,onReview:t}){return o("div",{className:"actor-row",children:[o("div",{className:"actor-details",children:[o("div",{className:"actor-title",children:[o("strong",{children:e.peerName}),o("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),o("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function oB({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],a=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=D({}),[l,d]=D({}),[u,p]=D(a),[m,f]=D({}),[y,g]=D("all"),[h,b]=D(""),[w,_]=D(null),I=r.length,N=e.totalGroupCount??I,T=r.filter(Bi).length,x=r.filter(C=>C.suggestedScopeId&&!Bi(C)&&Et(C)).length,j=r.filter(C=>m[C.workspaceIdentity]&&Et(C)).length,B=r.filter(C=>m[C.workspaceIdentity]&&Et(C)&&!!u[C.workspaceIdentity]).length,P=r.filter(C=>{const L=Bi(C);return y==="suggested"&&(!C.suggestedScopeId||L)||y==="cleanup"&&!L||y==="no-suggestion"&&(C.suggestedScopeId||L)||y==="selected"&&!m[C.workspaceIdentity]?!1:!h.trim()||iB(C,i).includes(h.trim().toLowerCase())});async function F(C){const L=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!L||!t||w)){_(C.workspaceIdentity),d(U=>{const V={...U};return delete V[C.workspaceIdentity],V});try{const U=await t(C,L,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(U?V=>({...V,[C.workspaceIdentity]:U}):V=>{const de={...V};return delete de[C.workspaceIdentity],de})}catch(U){d(V=>({...V,[C.workspaceIdentity]:sS(U,L,i)}))}finally{_(null)}}}function O(C,L){p(U=>({...U,[C.workspaceIdentity]:L})),c(U=>{const V={...U};return delete V[C.workspaceIdentity],V}),d(U=>{const V={...U};return delete V[C.workspaceIdentity],V})}function G(C,L){f(U=>({...U,[C.workspaceIdentity]:L}))}function $(C){f(L=>({...L,...Object.fromEntries(P.filter(Et).map(U=>[U.workspaceIdentity,C]))}))}function A(){f(C=>({...C,...Object.fromEntries(r.filter(L=>L.suggestedScopeId&&!Bi(L)&&Et(L)).map(L=>[L.workspaceIdentity,!0]))}))}async function E(){if(!t||w||B===0)return;const C=r.filter(L=>m[L.workspaceIdentity]&&Et(L)&&!!u[L.workspaceIdentity]);if(!C.every(L=>s[L.workspaceIdentity])){_("bulk");try{for(const L of C){if(s[L.workspaceIdentity])continue;const U=u[L.workspaceIdentity]||L.suggestedScopeId||"";if(U)try{const V=await t(L,U,!1);d(de=>{const ie={...de};return delete ie[L.workspaceIdentity],ie}),V&&c(de=>({...de,[L.workspaceIdentity]:V}))}catch(V){d(de=>({...de,[L.workspaceIdentity]:sS(V,U,i)}))}}}finally{_(null)}}}return o("div",{className:"legacy-review-card",children:[o("div",{className:"legacy-review-header",children:[o("div",{children:[o("div",{className:"actor-title",children:[o("strong",{children:"Legacy shared review"}),o("span",{className:"badge badge-offline",children:"Needs project review"})]}),o("div",{className:"peer-meta legacy-review-summary",children:[N.toLocaleString()," older"," ",N===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",I<N?` Showing ${I.toLocaleString()} projects; open Projects to review the rest.`:""]}),o("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),o("div",{className:"actor-actions",children:o("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),o("div",{className:"legacy-review-toolbar",children:[o("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${I.toLocaleString()}`],["suggested",`Suggested ${x.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${B.toLocaleString()}`]].map(([C,L])=>o("button",{className:y===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>g(C),type:"button",children:L},C))}),o("div",{className:"legacy-review-bulk-row",children:[o("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>b(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:h}),o("button",{className:"settings-button",onClick:()=>$(!0),type:"button",children:"Select visible"}),o("button",{className:"settings-button",onClick:A,type:"button",children:"Select suggested"}),o("button",{className:"settings-button",onClick:()=>$(!1),type:"button",children:"Clear visible"}),t&&i.length>0?o("button",{className:"settings-save",disabled:w!=null||B===0||r.filter(C=>m[C.workspaceIdentity]&&Et(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{E()},type:"button",children:w==="bulk"?"Previewing…":`Preview ${B.toLocaleString()} selected`}):t&&j>0?o("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,B>0&&r.filter(C=>m[C.workspaceIdentity]&&Et(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?o("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?o("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:P.map(C=>o("li",{className:"legacy-review-group",children:[o("div",{className:"legacy-review-group-main",children:[o("div",{className:"legacy-review-title-wrap",children:[o("input",{"aria-label":`Select ${oS(C)}`,checked:!!m[C.workspaceIdentity],className:"cm-checkbox",disabled:!Et(C),onChange:L=>G(C,L.currentTarget.checked),type:"checkbox"}),o("div",{children:[o("div",{className:"legacy-review-group-title",children:oS(C)}),o("div",{className:"legacy-review-group-meta",children:[YF(C.identitySource),XF(C,i)]}),Et(C)?C.peerOwnedMemoryCount?o("div",{className:"legacy-review-cleanup-note",children:[(C.reassignableMemoryCount??C.memoryCount).toLocaleString()," ","local memor",(C.reassignableMemoryCount??C.memoryCount)===1?"y":"ies"," ","can be reassigned; ",C.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",C.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:o("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),Bi(C)?o("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),o("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?o("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?o("div",{className:"legacy-review-confirmation",role:"alert",children:[s[C.workspaceIdentity].warning," This will reassign"," ",s[C.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[C.workspaceIdentity].memory_count.toLocaleString()," memories",s[C.workspaceIdentity].skipped_memory_count?`; ${s[C.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,o(rB,{group:C}),i.length>0&&t&&Et(C)?o("label",{className:"legacy-review-target",children:[o("span",{children:"Destination Space"}),o("select",{className:"peer-scope-input",disabled:w!=null,onChange:L=>O(C,L.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[o("option",{value:"",children:"Choose Space…"}),i.map(L=>o("option",{value:L.scopeId,children:[L.label," · ",eB(L.authorityType),L.scopeId===C.suggestedScopeId?" · suggested":""]},L.scopeId))]})]}):null,i.length>0&&t&&Et(C)?o("div",{className:"legacy-review-actions",children:o("button",{type:"button",className:"settings-button",disabled:w!=null||!u[C.workspaceIdentity],onClick:()=>{F(C)},children:w===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function sB({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return o(z,{children:[t?o(oB,{item:t,onReassign:n,onReview:r??i}):null,e.map(a=>o(aB,{item:a,onReview:i},`${a.peerName}:${a.actorId}:${a.scopeLabel}`))]})}function cB(){Sg("mine"),S.feedQuery="",window.location.hash="feed"}function lB(){window.location.hash="projects"}async function dB(e,t,n,r){try{const i=await nN({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return S.lastSyncLegacySharedReview=i.legacy_shared_review??null,J(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),cS(),null}catch(i){if(i instanceof _m)return i.preview;const a=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw J(a,"warning"),new Error(a)}}function cS(){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(S.lastSyncSharingReview)?S.lastSyncSharingReview:[],a=S.lastSyncLegacySharedReview,s=Math.max(0,Number(a?.memory_count??0)),c=a?.has_data?{groups:Array.isArray(a.groups)?a.groups.map(d=>{const u=d;return{displayProject:String(u.display_project||u.project||"Unknown project"),identitySource:String(u.identity_source||"unknown"),lastUpdatedAt:typeof u.last_updated_at=="string"?u.last_updated_at:null,memoryCount:Number(u.memory_count||0),memorySamples:Array.isArray(u.memory_samples)?u.memory_samples.map(p=>{const m=p,f=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:f,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(u.peer_owned_memory_count||0),reassignableMemoryCount:Number(u.reassignable_memory_count||0),suggestedScopeId:typeof u.suggested_scope_id=="string"?u.suggested_scope_id:null,suggestionReason:typeof u.suggestion_reason=="string"?u.suggestion_reason:null,workspaceIdentity:String(u.workspace_identity||u.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(a.scope_id||"legacy-shared-review"),totalGroupCount:Number(a.total_group_count||a.groups?.length||0),targetScopes:Array.isArray(a.target_scopes)?a.target_scopes.map(d=>{const u=d;return{authorityType:String(u.authority_type||"unknown"),label:String(u.label||u.scope_id||"Unknown domain"),scopeId:String(u.scope_id||"")}}).filter(d=>d.scopeId):[]}:null;if(!i.length&&!c){Mi(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=S.currentProject?`current project (${S.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.`,at(n,v(sB,{items:i.map(d=>({actorDisplayName:String(d.actor_display_name||d.actor_id||"unknown"),actorId:String(d.actor_id||"unknown"),peerName:String(d.peer_name||d.peer_device_id||"Device"),privateCount:Number(d.private_count||0),scopeLabel:String(d.scope_label||"All allowed projects"),shareableCount:Number(d.shareable_count||0)})),legacyReview:c,onLegacyReassign:dB,onLegacyReview:lB,onReview:cB}))}var Oc="";function uB(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const a of r){const s=String(a.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],a])}for(const[a,s]of S.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){S.pendingCoordinatorApprovalsByDeviceId.delete(a);continue}if(n)continue;const c=i.get(a);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||S.pendingCoordinatorApprovalsByDeviceId.delete(a))}}function pB(){return[...S.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var mo=null,Op=0,mB=15e3;function lS(e){return`project:${e||""}|includeJoinRequests:false`}function fB(e){const t=lS(e);return!mo||mo.key!==t||Date.now()>=mo.expiresAtMs?null:mo.payload}function hB(e,t){mo={key:lS(e),expiresAtMs:Date.now()+mB,payload:t}}function gB(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function vB(){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 Ui(){const e=++Op;try{const t=S.currentProject||"",n=!1,r=S.activeTab==="health";let i=!1;const a=!ha();let s;r?(s=fB(t),s||(s=await Co(a,t,{includeJoinRequests:!1}),i=!0)):(s=await Co(a,t,{includeJoinRequests:n}),i=!0);let c=null,l=null,d=S.lastDeviceIdentityInventory,u=S.lastShareOperations,p=!1,m=!1,f=S.deviceIdentityInventoryLoadError,y=!1;const g=P1();try{c=await bC()}catch{p=!0}try{l=await Vc()}catch{m=!0}if(S.activeTab==="advanced"){f=!1;try{d=await Qc()}catch{f=!0}}try{const N=await Em();u=Array.isArray(N.items)?N.items:[]}catch{y=!0}if(e!==Op)return;i&&hB(t,gB(s)),uB(s.coordinator);const h=JSON.stringify([s,c,l,d,f,u,y,g,pB()]);if(h===Oc)return;Oc=h;const b=s.status&&typeof s.status=="object"?s.status:null;b&&(S.lastSyncStatus=b),Array.isArray(c?.items)?S.lastSyncActors=c.items:S.lastSyncActors=[];const w=Array.isArray(s.peers)?s.peers:[],_=new Set(w.map(N=>String(N?.peer_device_id||"").trim()).filter(Boolean)),I=Array.isArray(S.pendingAcceptedSyncPeers)?S.pendingAcceptedSyncPeers.filter(N=>{const T=String(N?.peer_device_id||"").trim();return T&&!_.has(T)}):[];S.pendingAcceptedSyncPeers=I,S.lastSyncPeers=[...w,...I],f||(S.lastDeviceIdentityInventory=d),S.deviceIdentityInventoryLoadError=f,S.lastShareOperations=u,S.shareOperationsLoadError=y,S.lastSyncSharingReview=s.sharing_review||[],S.lastSyncLegacySharedReview=s.legacy_shared_review&&typeof s.legacy_shared_review=="object"?s.legacy_shared_review:null,S.lastSyncCoordinator=s.coordinator||null,S.lastSyncCoordinatorAdminStatus=l&&typeof l=="object"?l:null,S.lastSyncJoinRequests=Array.isArray(s.join_requests)?s.join_requests:[],S.lastSyncAttempts=s.attempts||[],S.lastSyncLegacyDevices=s.legacy_devices||[],S.lastSyncDuplicatePersonDecisions=g,S.lastSyncViewModel=w1({actors:S.lastSyncActors,peers:S.lastSyncPeers,coordinator:S.lastSyncCoordinator,status:b,shareOperations:S.lastShareOperations,shareOperationsLoadError:y,reconciliation:s.recipient_policy_reconciliation,duplicatePersonDecisions:S.lastSyncDuplicatePersonDecisions}),zw(),po(),wF(),CF(),cS(),xp(),tS(),Ww(),D_(),p&&SF(),m&&(S.lastSyncCoordinatorAdminStatus=null,po())}catch{if(e!==Op)return;Oc="",S.deviceIdentityInventoryLoadError=!0,er("syncTeamSkeleton"),er("syncActorsSkeleton"),er("syncPeersSkeleton"),er("syncDiagSkeleton"),vB(),NF(),j1()}}function yB(){Oc="",S.lastSyncPeers?.length&&xp()}async function bB(){try{S.pairingPayloadRaw=await _C()||null,kp()}catch{S.pairingPayloadRaw=null,kp()}}function _B(e){yO(),Fs(),RF(Ui),_F(Ui),U1(xp),xF(e,Ui),IF(Ui),q1(e),Dp(),TF()}function wB(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 SB(){try{const e=await uC();if(!e?.version)return;wB(e.version,"504b452")}catch{}}var Fp=null,dS=1500,uS="codemem-legacy-upgrade-notice-dismissed",nr=null,rn=!1,Bp=!1,fo=null;function pS(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function mS(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=pS(n.total_group_count,r.length),a=pS(n.memory_count);return i<=0||a<=0?null:{groupCount:i,memoryCount:a}}function fS(){try{return localStorage.getItem(uS)==="1"}catch{return!1}}function Fc(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(uS,"1")}catch{}}function hS(){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 CB(){const e=hS(),t=Le("legacyUpgradeReviewGroups");(t&&e.includes(t)?t:e[0])?.focus()}function gS(e){const t=Le("legacyUpgradeModal");if(!t||t.hidden)return;if(e.key==="Escape"){e.preventDefault(),Fc(),ho(!1);return}if(e.key==="Enter"){const a=Le("legacyUpgradeReviewGroups");ui(e,{onSubmit:()=>a?.click(),disabled:!a||a.disabled});return}if(e.key!=="Tab")return;const n=hS();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 vS(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 ho(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){fo=document.activeElement,document.addEventListener("keydown",gS),CB(),vS(!0);return}vS(!1),document.removeEventListener("keydown",gS),fo&&document.contains(fo)&&fo.focus(),fo=null}}function yS(e){!e||Bp||fS()||(Bp=!0,ho(!0,e))}async function NB(){if(!(Bp||fS()))try{yS(mS(await Co(!1,"",{includeJoinRequests:!1})))}catch{}}function Hr(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 Up(){try{return await dC(),!0}catch{return!1}}function IB(){return document.visibilityState!=="hidden"&&!gw()}function bS(){if(rn)return;rn=!0,qp(),Kr("error","(reconnecting)"),Hr(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await Up()){if(nr&&(clearTimeout(nr),nr=null),rn=!1,Hr(!0,"Viewer responded. Restoring your session…"),IB()){Kr("refreshing"),go();try{await Bc()}catch{}}else Kr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");rn||Hr(!1);return}Hr(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),nr=setTimeout(e,dS)};nr=setTimeout(e,dS)}function Kr(e,t){S.refreshState=e;const n=Le("refreshStatus");if(!n)return;const r=a=>{const s=Le("refreshAnnouncer");!s||Fp===e||(s.textContent=a,Fp=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}`,Fp=null}function qp(){S.refreshTimer&&(clearInterval(S.refreshTimer),S.refreshTimer=null)}function go(){S.refreshTimer||(S.refreshTimer=setInterval(()=>rr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(qp(),Kr("paused","(tab hidden)")):!gw()&&!rn&&(go(),rr())});function _S(){const e=S.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 a=window.location.hash.replace(/^#/,"");Dp(a==="sync/diagnostics"||a==="advanced/sync/diagnostics"?"diagnostics":"main")})}function wS(e){const t=new Set(aR(S.lastCoordinatorAdminStatus));_r.forEach(n=>{const r=Le(`tab-${n}`);r&&(r.hidden=n!==e||!t.has(n))}),_r.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")}),_S()}function Vr(e,t={}){const n=fa(e,S.lastCoordinatorAdminStatus);n==="advanced"&&ad(t.advancedSection??id()??S.advancedSection),wg(n,t.canonicalHash?{canonicalHash:!0}:{}),wS(n),rr()}function kB(){_r.forEach(e=>{Le(`tabBtn-${e}`)?.addEventListener("click",()=>Vr(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Le("advancedSyncButton")?.addEventListener("click",()=>ad("sync",!0)),Le("advancedTeamsButton")?.addEventListener("click",()=>{ad("teams",!0),_S(),queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}),Le("coordinatorAdminOpenSharing")?.addEventListener("click",()=>{Vr("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=rd();if(e){const t=id();Vr(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminLegacyNoticeTitle")?.focus())}}),Vr(S.activeTab)}async function TB(){try{const e=await wo();S.knownProjects=e,yB();const t=ed("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 RB(e){S.pendingDeviceIdentityFocus=e?.trim()||null,Vr("devices",{canonicalHash:!0})}var vo=lT({},{onOpenTeamSetup:K_,onReviewDevices:RB}),SS={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Gp=0,Hp=null,xt=null;async function PB(){const e=[];let t=0;for(;;){const n=await Wi({limit:250,offset:t});if(e.push(...n.projects),!n.has_more)break;t+=n.limit}return Yo(e)}function AB(){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 S.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"offline":"available");for(const r of S.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),a=co(r);n(i,a==="connected"||a==="available"?"available":a==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function EB(){return S.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 CS(e){if(e==="advanced_sync"){Vr("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}Vr(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function Kp(){const e=document.getElementById("devicesMount");if(!e)return Promise.resolve(!0);const t=xB(e,++Gp);return Hp=t,t}async function xB(e,t){xt||Ks(e,SS,{version:1,items:[]},[],[],{loading:!0});try{const[n,r,i,a]=await Promise.all([PB(),Xc(),BC(),Qc().then(d=>({inventory:d,unavailable:!1})).catch(()=>({inventory:xt?.inventory,unavailable:!0})),Ui()]);if(t!==Gp)return Hp??!1;const s=AB(),c=EB(),l=Dm(S.lastSyncStatus);return!a.unavailable&&a.inventory&&(S.lastDeviceIdentityInventory=a.inventory),S.deviceIdentityInventoryLoadError=a.unavailable,Ks(e,r,i,n,s,{inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l,onCommitted:async()=>{const[d,u]=await Promise.all([Kp(),vo()]);return d&&u},onNavigate:CS,peerRuntimeMetadata:c}),xt={projects:n,intent:r,reconciliation:i,availability:s,peerRuntimeMetadata:c,inventory:a.inventory,inventoryUnavailable:a.unavailable,coordinatorEnrollmentIssueCount:l},!0}catch{return t!==Gp?Hp??!1:(xt?Ks(e,xt.intent,xt.reconciliation,xt.projects,xt.availability,{coordinatorEnrollmentIssueCount:xt.coordinatorEnrollmentIssueCount,inventory:xt.inventory,inventoryUnavailable:xt.inventoryUnavailable,onCommitted:async()=>{const[n,r]=await Promise.all([Kp(),vo()]);return n&&r},onNavigate:CS,peerRuntimeMetadata:xt.peerRuntimeMetadata,refreshError:!0}):Ks(e,SS,{version:1,items:[]},[],[],{loadError:!0}),!1)}}ed("projectFilter")?.addEventListener("change",()=>{S.currentProject=ed("projectFilter")?.value||"",Mr(!0),rr()});var Vp=null;async function rr(){rn||(Vp&&clearTimeout(Vp),Vp=setTimeout(()=>Bc(),80))}async function Bc(){if(!rn){if(S.refreshInFlight){S.refreshQueued=!0;return}S.refreshInFlight=!0;try{Kr("refreshing");const e=S.activeTab,t=[O$(),Fj()];let n=!0;if(e==="feed"){const i=ox();t.push(By(i))}e==="feed"&&t.push(Ku()),e==="projects"&&t.push(ao()),e==="sharing"&&t.push(vo()),e==="devices"&&t.push(Kp().then(i=>{n=i})),(e==="advanced"&&S.advancedSection==="sync"||e==="health")&&t.push(Ui()),e==="advanced"&&S.advancedSection==="teams"&&t.push(qs()),S.syncPairingOpen&&t.push(bB()),await Promise.all(t),yS(mS(S.lastSyncLegacySharedReview));const r=fa(S.activeTab,S.lastCoordinatorAdminStatus);r!==S.activeTab&&wg(r),wS(S.activeTab),Kr(n?"idle":"error")}catch{await Up()?Kr("error"):bS()}finally{S.refreshInFlight=!1,S.refreshQueued&&!rn&&(S.refreshQueued=!1,Bc())}}}fR();var NS=document.getElementById("toastRoot");NS&&JT(NS);var IS=document.getElementById("legacyTeamSetupMount");IS&&kM(IS,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(S.activeTab==="sharing"?(t=await ao(n),e=await vo(n)):(e=await vo(n),t=await ao(n)),!e||!t)throw new Error("team_setup_refresh_failed")}}),hR(td("themeToggle")),Ig(sd()),kB(),N$(),lj(()=>rr(),{onOpenTeamSetup:K_}),_B(()=>rr()),mx(),gO(qp,go,()=>rr()),TB(),Le("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Hr(!0,"Checking whether the viewer server is back…"),!await Up()){bS();return}nr&&(clearTimeout(nr),nr=null),rn=!1,Hr(!0,"Viewer responded. Restoring your session…"),go();try{await Bc()}catch{}rn||Hr(!1)}),Le("legacyUpgradeReviewGroups")?.addEventListener("click",()=>{Fc(),ho(!1),window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)}),Le("legacyUpgradeReviewProjects")?.addEventListener("click",()=>{Fc(),ho(!1),window.location.hash="projects"}),Le("legacyUpgradeNotNow")?.addEventListener("click",()=>{Fc(),ho(!1)}),SB(),NB(),rr(),go()})();
|