@codemem/server 0.49.0-beta.5 → 0.49.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +58 -34
- package/dist/index.js.map +1 -1
- package/dist/routes/device-rename.d.ts +7 -7
- package/dist/routes/device-rename.d.ts.map +1 -1
- package/dist/routes/sync.d.ts.map +1 -1
- package/package.json +2 -2
- package/static/app.js +2 -2
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +1 -1
package/static/app.js
CHANGED
|
@@ -117,5 +117,5 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
117
117
|
${t}
|
|
118
118
|
`:t}function VV(e){const[t,n]=R(!1);return Ge(()=>{const r=Lo(y.feedQuery);if(!r){n(!1);return}const i=e.current?.querySelector(".feed-detail"),o=()=>{const l=i?sk(i):"";n(!!(r&&l.toLowerCase().includes(r)))};o();const s=new MutationObserver(o);i&&s.observe(i,{childList:!0,subtree:!0,characterData:!0});const c=i?.querySelectorAll(".feed-observation-context");return c?.forEach(l=>{l.addEventListener("toggle",o)}),()=>{s.disconnect(),c?.forEach(l=>{l.removeEventListener("toggle",o)})}}),t}function ck(e){return e==="shared"?"shared":e==="private"?"private":"unknown"}function KV(e,t,n){const r=String(e.visibility||n.visibility||"").trim(),i=Om(e),o=String(e.trust_state||n.trust_state||"").trim(),s=String(e.workspace_kind||n.workspace_kind||"").trim(),c=LG(e.origin_source||n.origin_source),l=["Observer","Session summary"].includes(c)?"":c,d=MG(e,n);let u="";return!i&&o!=="trusted"&&(u=o?jG(o):"Trust unknown"),{actor:$G(e),createdAtRaw:e.created_at||e.created_at_utc,device:d,detailId:`feed-detail-${t.rowKey.replace(/[^a-zA-Z0-9_-]/g,"-")}`,hasSupplementalDetail:!!(t.files.length||s||l||d),memoryId:Number(e.id||e.memory_id||0),originSource:l,ownedBySelf:i,project:String(e.project||"").trim(),relative:Ip(e.created_at||e.created_at_utc),trustLabel:u,visibility:r,workspaceKind:s}}function WV(e){const[t,n]=R(y.newItemKeys.has(e));return q(()=>{if(!t)return;const r=window.setTimeout(()=>{y.newItemKeys.delete(e),n(!1)},700);return()=>window.clearTimeout(r)},[t,e]),t}function zV(e){const[t,n]=R(y.itemExpandState.get(e)!==!1);return{cardRef:x(null),expanded:t,isNew:WV(e),setExpanded:n}}function JV(e,t){const n=e.current?.querySelector(".feed-disclosure")===document.activeElement;Ge(()=>{n&&!t&&document.activeElement===document.body&&e.current?.focus()},[e,n,t])}async function YV(e){e.setSelectedVisibility(e.nextVisibility),e.setSavingVisibility(!0);try{const t=await pN(e.memoryId,e.nextVisibility);t?.item&&(e.onReplace(t.item),e.onViewRefresh()),Y(e.nextVisibility==="shared"?"Shared with synced peers":"Only you can see this")}catch(t){e.setSelectedVisibility(e.previousVisibility),Y(t instanceof Error?t.message:"Failed to save visibility.","warning")}finally{e.setSavingVisibility(!1)}}async function XV(e){try{return(await rc()).filter(t=>t&&t!==e)}catch{return[]}}function QV(e,t){const n=t.length>80?`${t.slice(0,79).trimEnd()}…`:t;return e?`Move "${n}" from "${e}" 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 "${n}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`}async function lk(e){try{await e.onReload(),e.onViewRefresh()}catch{Y("The change was applied, but the feed could not refresh. Refresh to try again.","warning")}}async function ZV(e){const t=await mm({title:"Assign to project",description:QV(e.currentProject,e.title),initialValue:e.currentProject,placeholder:"Pick one or type a new project name",suggestions:e.suggestions,confirmLabel:"Move",cancelLabel:"Cancel",validate:r=>{const i=r.trim();return i?i===e.currentProject?"Already assigned to this project.":null:"Enter a project name."}});if(t==null)return;const n=t.trim();if(!(!n||n===e.currentProject)){e.setMovingProject(!0);try{const r=await fN(e.memoryId,n),i=Number(r.moved_memory_count||1);Y(i>1?`Moved ${i} memories from this session to "${r.project}".`:`Moved to "${r.project}".`),await lk(e)}catch(r){Y(r instanceof Error?r.message:"Failed to move memory.","warning")}finally{e.setMovingProject(!1)}}}async function eK(e){const t=e.title.length>80?`${e.title.slice(0,79).trimEnd()}…`:e.title;if(await Dn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${t}". 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"})){e.setDeletingMemory(!0);try{await mN(e.memoryId),e.onRemove(e.memoryId),e.onViewRefresh(),Y("Memory forgotten and removed from the active feed."),await lk(e)}catch(n){Y(n instanceof Error?n.message:"Failed to forget memory.","warning")}finally{e.setDeletingMemory(!1)}}}function tK(e){const[t,n]=R(!1),[r,i]=R(!1),[o,s]=R(!1),c=String(e.item.project||"").trim(),l=String(e.model.displayTitle||"this memory").trim();return{deletingMemory:r,movingProject:o,savingVisibility:t,forget:()=>eK({memoryId:e.memoryId,onReload:e.onReload,onRemove:e.onRemove,onViewRefresh:e.onViewRefresh,setDeletingMemory:i,title:l}),moveProject:async()=>ZV({currentProject:c,memoryId:e.memoryId,onReload:e.onReload,onViewRefresh:e.onViewRefresh,setMovingProject:s,suggestions:await XV(c),title:l}),saveVisibility:d=>YV({memoryId:e.memoryId,nextVisibility:d,onReplace:e.onReplace,onViewRefresh:e.onViewRefresh,previousVisibility:e.selectedVisibility,setSavingVisibility:n,setSelectedVisibility:e.setSelectedVisibility})}}function nK(e){return h("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:vC(e.model.displayTitle,y.feedQuery)}})}function rK(e){return!e.searchMatch||e.renderedSearchMatch?null:h("div",{className:"feed-search-match"},h("span",{className:"feed-search-match-label"},`${e.searchMatch.label} match`),h("span",{dangerouslySetInnerHTML:{__html:vC(e.searchMatch.excerpt,y.feedQuery)}}))}function iK(e){const{details:t}=e,n=t.memoryId>0?h(Oo,{label:`Memory database id ${t.memoryId}`,side:"top"},h(zn,{label:`#${t.memoryId}`,variant:"memory-id"})):null;return h("div",{className:"feed-meta-line"},t.project?h("span",{className:"feed-project"},t.project):h("span",null,"No project"),h(Oo,{label:dx(t.createdAtRaw),side:"top"},h("span",{className:"feed-age mono"},t.relative)),h(zn,{label:t.actor,variant:t.ownedBySelf?"mine":"author"}),h(zn,{label:e.visibilityKnown?e.selectedVisibility:"Visibility unknown",variant:e.visibilityKnown?e.selectedVisibility:"unknown"}),n,t.trustLabel?h(zn,{label:t.trustLabel,variant:"trust"}):null)}function oK(e){return e.length?h("div",{className:"feed-files"},e.map((t,n)=>h("span",{className:"feed-file",key:`${String(t)}-${n}`},String(t)))):null}function aK(e){const t=[e.workspaceKind?h(zn,{label:`Workspace ${e.workspaceKind}`,variant:"workspace"}):null,e.originSource?h(zn,{label:e.originSource,variant:"source"}):null,e.device?h(zn,{label:e.device,variant:"device"}):null].filter(Boolean);return t.length?h("div",{className:"feed-expanded-provenance"},t):null}function dk(e,t,n="feed-pack-facts"){return e.length?h("div",{className:n},h("div",{className:"feed-pack-facts-label"},t),FV(e)):null}function sK(e){const{body:t,facts:n,narrative:r}=e.model.content;if(!e.model.isSessionSummary&&n.length){const i=r||t;return h(U,null,dk(n,"Key points","feed-pack-facts feed-observation-points"),i||e.model.projection?.full_context?h(HV,{id:e.details.memoryId,inline:i,revision:e.model.projection?.full_context?.revision,title:e.model.displayTitle,onReload:e.onContextReload}):null)}return h(U,null,r?cd(r,"feed-body narrative"):null,t?cd(t,"feed-body narrative"):null,dk(n,"Facts included in pack"))}function cK(e){return!e.expanded||!e.hasDisclosure?null:h("section",{"aria-label":`${e.model.displayTitle} content`,className:"feed-detail",id:e.details.detailId},sK(e),oK(e.model.files),aK(e.details))}function lK(e){return h("div",{className:"feed-card-body"},nK(e),!e.expanded&&e.hasDisclosure?h("div",{className:"feed-collapsed-note"},"Memory content collapsed"):null,rK(e),iK(e),cK(e),uK(e))}function dK(e){if(!e.details.ownedBySelf||e.details.memoryId<=0)return null;const t=`feed-visibility-${e.details.memoryId}`,n=[...e.visibilityKnown?[]:[{disabled:!0,label:"Unknown",value:"unknown"}],{label:"Only me",value:"private"},{label:"Synced peers",value:"shared"}];return h("label",{className:"feed-visibility-label",htmlFor:t},h("span",{className:"sr-only"},"Visible to"),h(En,{ariaLabel:`Who can see ${e.model.displayTitle}`,disabled:e.savingVisibility||!e.visibilityKnown,id:t,onValueChange:r=>{const i=r==="shared"?"shared":"private";e.onSaveVisibility(i)},options:n,triggerClassName:"feed-visibility-select",value:e.visibilityKnown?e.selectedVisibility:"unknown"}))}function uK(e){return e.model.tags.length?h("footer",{className:"feed-card-footer"},h("div",{"aria-label":"Tags",className:"feed-tags"},e.model.tags.map((t,n)=>h(bb,{key:`${String(t)}-${n}`,tag:t})))):null}function pK(e){const t=dK(e),n=e.details.ownedBySelf&&e.details.memoryId>0?h(BV,{assignProjectDisabled:e.movingProject,disabled:e.deletingMemory,onAssignProject:()=>{e.onMoveProject()},onForget:()=>{e.onForget()},title:e.model.displayTitle}):null;return h("div",{className:"feed-card-side"},h("div",{className:"feed-card-side-top"},t,e.hasDisclosure?h(Oo,{label:e.expanded?"Collapse memory":"Expand memory",side:"top"},h("button",{"aria-controls":e.details.detailId,"aria-expanded":e.expanded,"aria-label":e.expanded?"Collapse memory":"Expand memory",className:"feed-disclosure",onClick:e.onToggleDetail,type:"button"},h("svg",{"aria-hidden":"true",className:"feed-disclosure-icon",viewBox:"0 0 16 16"},h("path",{d:"m3.5 6 4.5 4 4.5-4",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"1.7"})))):null,n))}function fK(e){return h("article",{className:`feed-item ${e.model.displayKind}${e.isNew?" new-item":""}`.trim(),"data-key":e.model.rowKey,ref:e.cardRef,tabIndex:-1},h("div",{className:"feed-kind-rail"},h(Ne,{variant:"kind",tone:e.model.displayKind},e.model.displayKind.replace(/_/g," "))),lK(e),pK(e))}function mK(e){return Lo(y.feedQuery)&&e.displayTitle.toLowerCase().includes(Lo(y.feedQuery))?null:HG(e,y.feedQuery)}function hK(e){const[t,n]=R(ck(e));return q(()=>{n(ck(e))},[e]),{selectedVisibility:t,setSelectedVisibility:n,visibilityKnown:e==="private"||e==="shared"}}function gK({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i,onContextReload:o=i}){const s=hC(e),c=KV(e,s,Zl(e.metadata_json)),l=zV(s.rowKey),d=mK(s),u=VV(l.cardRef),f=hK(c.visibility),p=tK({item:e,memoryId:c.memoryId,model:s,onReload:i,onRemove:n,onReplace:t,onViewRefresh:r,selectedVisibility:f.selectedVisibility,setSelectedVisibility:f.setSelectedVisibility}),m=!!(s.content.searchText||c.hasSupplementalDetail);JV(l.cardRef,m);const g=()=>{if(!m)return;const b=!l.expanded;y.itemExpandState.set(s.rowKey,b),l.setExpanded(b)};return fK({cardRef:l.cardRef,deletingMemory:p.deletingMemory,details:c,expanded:l.expanded,hasDisclosure:m,isNew:l.isNew,model:s,movingProject:p.movingProject,onForget:p.forget,onContextReload:o,onMoveProject:p.moveProject,onSaveVisibility:p.saveVisibility,onToggleDetail:g,savingVisibility:p.savingVisibility,searchMatch:d,renderedSearchMatch:u,selectedVisibility:f.selectedVisibility,visibilityKnown:f.visibilityKnown})}function vK({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return h("div",{className:"feed-skeleton-item","aria-hidden":"true"},h("div",{className:"feed-skeleton-banner"}),h("div",{className:"feed-skeleton-body"},h("div",{className:`feed-skeleton-line ${n}`}),h("div",{className:`feed-skeleton-line ${r}`}),h("div",{className:"feed-skeleton-footer"},h("div",{className:"feed-skeleton-chip w-36"}),h("div",{className:"feed-skeleton-chip w-56"}),h("div",{className:"feed-skeleton-chip"}))))}function uk(e){document.getElementById(e)?.click()}function ld(){uk("tabBtn-health"),queueMicrotask(()=>document.getElementById("healthSystemCard")?.focus())}function yK(e){if(Mw("all"),xf("all"),_w("")){queueMicrotask(()=>document.getElementById("projectFilter")?.focus());return}y.currentProject="",e.updateFeedView(!0),e.loadFeedData().catch(()=>{})}function bK(){const e=y.feedProcessingStatus;if(e.kind==="pending"){const t=e.count===1?"event":"events";return{actions:[{label:"Open Health",run:ld}],detail:"Captured work is queued. Memories will appear after processing finishes.",status:!0,title:`Processing ${e.count} ${t}.`}}return e.kind==="paused"?{actions:[{label:"Open Health",run:ld}],detail:"New activity will not be captured until raw-event capture is enabled.",status:!0,title:"Capture is paused."}:e.kind==="unavailable"?{actions:[{label:"Open Health",run:ld}],detail:"The Feed is connected, but processing status could not be checked.",status:!0,title:"Processing status is unavailable."}:{actions:[{label:"Open Settings",run:()=>uk("settingsButton")},{label:"Open Health",run:ld}],detail:"Use codemem while you work. Captured memories and session summaries will appear here.",title:"No memories yet."}}function _K(e){const t=y.feedQuery.trim();return t?{actions:[{label:"Clear search",run:()=>{e.updateFeedQuery(""),queueMicrotask(()=>document.getElementById("feedSearch")?.focus())}}],detail:"Try a broader search or clear the search to see all memories.",title:`No memories match “${t}”.`}:y.feedTypeFilter!=="all"||y.feedScopeFilter!=="all"||y.currentProject?{actions:[{label:"Clear filters",run:()=>yK(e)}],detail:"Clear the Feed and project filters to see memories from every scope.",title:"No memories match the current filters."}:bK()}function wK({ops:e}){const t=_K(e);return h("div",{className:"small feed-empty-state",role:t.status?"status":void 0},h("strong",null,t.title),h("div",null,t.detail),h("div",{className:"feed-empty-actions"},t.actions.map(n=>h("button",{className:"settings-button",key:n.label,onClick:n.run,type:"button"},n.label))))}function SK({items:e,loadingText:t,ops:n}){return t?h("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>h(vK,{index:r,key:`skeleton-${r}`}))):e.length?h(U,null,e.map(r=>h(gK,{item:r,key:At(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData,onContextReload:()=>n.loadFeedData({restart:!0})}))):h(wK,{ops:n})}function pk({id:e,active:t,options:n,onSelect:r}){return h("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{const s=i===t;return h("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},o)}))}function fk(e){document.getElementById(e)?.click()}function oh(e){document.querySelector(e)?.focus()}function CK(){fk("tabBtn-health"),queueMicrotask(()=>oh("#healthSystemCard"))}function kK(){const e=document.querySelector(".feed-item button.feed-title");e?.getAttribute("aria-expanded")!=="true"&&e?.click(),e?.focus(),e&&Pi("inspect")}function IK(){oh("#feedSearch")}function RK(e){return[{id:"capture",label:"Capture a memory",actionLabel:"Check capture health",action:CK},{id:"inspect",label:"Inspect its details",actionLabel:"Inspect first memory",action:kK,actionAvailable:e},{id:"find",label:"Find it again",actionLabel:"Search memories",action:IK},{id:"scope",label:"Choose project scope",actionLabel:"Choose a project",action:()=>oh("#projectFilter")},{id:"settings-health",label:"Check settings or health",actionLabel:"Open Settings",action:()=>fk("settingsButton")}]}function PK({completed:e,hasMemories:t,onAction:n}){return a("ol",{className:"first-run-guide-list",children:RK(t).map(r=>{const i=e.has(r.id);return a("li",{className:i?"is-complete":void 0,children:[a("span",{className:"first-run-guide-status",children:[a("span",{"aria-hidden":"true",children:i?"✓":"○"}),a("span",{children:[a("strong",{children:r.label}),a("span",{className:"small",children:i?"Completed":"Pending"})]})]}),!i&&r.actionAvailable!==!1?a("button",{className:"settings-button",onClick:()=>n(r),type:"button",children:r.actionLabel}):null]},r.id)})})}function NK({hasMemories:e,hasQueuedEvents:t}){const[n,r]=R(ps),[i,o]=R(""),[s,c]=R(!1);if(Ge(()=>{c(document.querySelector(".feed-item button.feed-title")!==null)}),q(()=>{const d=()=>{const f=ps();r(f),o(`${f.completed.length} of 5 getting started steps completed.`)},u=f=>{f.key==="codemem-first-run-guide-v1"&&d()};return window.addEventListener($m,d),window.addEventListener("storage",u),()=>{window.removeEventListener($m,d),window.removeEventListener("storage",u)}},[]),q(()=>{(e||t)&&Pi("capture")},[e,t]),!zG(n))return null;const l=new Set(n.completed);return a("section",{"aria-labelledby":"firstRunGuideTitle",className:"first-run-guide",id:"firstRunGuide",tabIndex:-1,children:[a("div",{className:"first-run-guide-header",children:[a("div",{children:[a("h2",{id:"firstRunGuideTitle",children:"Getting started"}),a("p",{children:"Confirm capture works, then learn where to inspect and find memories."})]}),a("button",{className:"settings-button",onClick:()=>KG(),type:"button",children:"Skip getting started"})]}),a(PK,{completed:l,hasMemories:s,onAction:d=>{d.action(),o(`Ready: ${d.actionLabel}.`)}}),a("div",{"aria-live":"polite",className:"sr-only",role:"status",children:i})]})}function TK({text:e}){return h("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function AK({query:e,onQuery:t}){return h("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 EK(e,t){return!e&&!t}function xK({inspectorOpen:e,items:t,loadingText:n,onInspectorToggle:r,ops:i}){return h("div",{className:"feed-controls"},h(TK,{text:n||oH(t.length,i.hasMorePages())}),h("div",{className:"feed-controls-right"},h(AK,{query:y.feedQuery,onQuery:i.updateFeedQuery}),h(pk,{active:y.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==y.feedScopeFilter&&(xf(o),i.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),h(pk,{active:y.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==y.feedTypeFilter&&(Mw(o),i.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),h("button",{"aria-controls":"contextInspectorPanel","aria-expanded":e,className:"settings-button feed-inspector-button",id:"contextInspectorToggle",onClick:r,type:"button"},e?"Hide Context Inspector":"Context Inspector")))}function DK({errorText:e,items:t,loadingText:n,ops:r}){const i=e?h("div",{className:"small feed-empty-state",role:"alert"},h("strong",null,e),h("div",null,"Check the viewer connection, then retry the Feed."),h("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null;return t.length===0&&i?i:h(U,null,i,h(SK,{items:t,loadingText:n,ops:r}))}function jK({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=R(!1);return h(U,null,h(xK,{inspectorOpen:i,items:t,loadingText:n,onInspectorToggle:()=>{o(c=>!c)},ops:r}),h(aH,{open:i}),EK(n,y.viewerReconnectOpen)?h(NK,{hasMemories:t.length>0,hasQueuedEvents:y.feedProcessingStatus.kind==="pending"}):null,h("div",{className:"feed-list",id:"feedList"},h(DK,{errorText:e,items:t,loadingText:n,ops:r})))}function mk(e){return y.feedTypeFilter==="observations"?e.filter(t=>!ed(t,Zl(t?.metadata_json))):y.feedTypeFilter==="summaries"?e.filter(t=>ed(t,Zl(t?.metadata_json))):e}function OK(e){const t=e.map(n=>`${fC(n)}:${JSON.stringify(n)}`);return`${y.feedTypeFilter}|${y.feedScopeFilter}|${y.currentProject}|${y.viewerActorId??""}|${Ea(y.feedQuery)}|${t.join("|")}`}var hk="",ur=Mo(),pr=Mo(),LK=0,Go=null,$K=0,Ho=null,gk=!1,vk=!1,ah=0,yk="all",sh="",ws=y.viewerActorId,Ss=null,Ur="",eQ=250;function ch(e){hk=e,yk=y.feedScopeFilter,sh=y.feedQuery.trim(),ws=y.viewerActorId,Ur="",ah+=1,ur=Mo(),pr=Mo(),y.lastFeedItems=[],y.pendingFeedItems=null,y.lastFeedFilteredCount=0,y.lastFeedSignature="",y.newItemKeys.clear()}function lh(){return ur.hasMore||pr.hasMore}function bk(e,t){return e!==null&&t!==null&&e!==t}function dh(){ws===null&&y.viewerActorId!==null&&(ws=y.viewerActorId)}function MK(e){const t=At(e);y.lastFeedItems=y.lastFeedItems.map(n=>At(n)===t?e:n)}function FK(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(At(r)),i};y.lastFeedItems=y.lastFeedItems.filter(n),Array.isArray(y.pendingFeedItems)&&(y.pendingFeedItems=y.pendingFeedItems.filter(n));for(const r of t){y.newItemKeys.delete(r),y.itemExpandState.delete(r);for(const i of Array.from(y.itemExpandState.keys()))i.startsWith(`${r}:`)&&y.itemExpandState.delete(i)}}function _k(e,t){return mk(e).some(n=>GG(n,t))&&Pi("find"),e.sort((n,r)=>new Date(r.created_at||0).getTime()-new Date(n.created_at||0).getTime())}function wk(){return{generation:ah,project:y.currentProject||"",query:y.feedQuery.trim(),scope:y.feedScopeFilter,actor:y.viewerActorId}}function dd(e){return e.generation===ah&&e.project===(y.currentProject||"")&&e.query===y.feedQuery.trim()&&e.scope===y.feedScopeFilter&&!bk(e.actor??ws,y.viewerActorId)}async function Sk(e,t){const n={view:"feed",scope:e.scope,q:e.query||void 0,signal:t.signal},r=t.head||ur.hasMore,i=t.head||pr.hasMore,[o,s]=await Promise.all([r?uN(e.project,{...n,limit:20,...wC(ur,t)}):Promise.resolve({items:[]}),i?hN(e.project,{...n,limit:50,...wC(pr,t)}):Promise.resolve({items:[]})]);return{observations:o,summaries:s,observationsRequested:r,summariesRequested:i}}function Ck(e,t){const n=e.observationsRequested?SC({previous:ur,payload:e.observations,limit:20,...t}):ur,r=e.summariesRequested?SC({previous:pr,payload:e.summaries,limit:50,...t}):pr;dh(),ur=n,pr=r}async function kk(e,t={}){!dd(e)||t.signal?.aborted||(ch(e.project),ur=Mo("offset"),pr=Mo("offset"),ud(),await Cs({signal:t.signal}))}function Ik(e){return e instanceof yu&&(ur.mode!=="offset"||pr.mode!=="offset")}function Rk(){Ur="Feed unavailable. Refresh and try again.",Ln(!0)}function BK(e,t){Ck(e,{head:!1});const n=e.summaries.items||[],r=e.observations.items||[],i=t?r:r.filter(s=>!pC(s));y.lastFeedFilteredCount+=r.length-i.length;const o=_k([...n,...i],t);y.lastFeedItems=mC(y.lastFeedItems,o),Ln()}async function qK(){if(!lh()||Ur)return;const e=wk();if(Tk(e.project,e.query,{})||Go?.generation===e.generation)return;const t=++LK;Go={generation:e.generation,requestId:t};try{const n=await Sk(e,{head:!1});if(!dd(e)||Go?.requestId!==t)return;BK(n,e.query)}catch(n){if(!dd(e)||Go?.requestId!==t)return;if(Ik(n)){await kk(e).catch(()=>{});return}Rk()}finally{Go?.requestId===t&&(Go=null)}}function Pk(){y.activeTab==="feed"&&(Ss||Ur||Ho||lh()&&YG()&&qK())}var UK={replaceFeedItem:MK,removeFeedItem:FK,updateFeedView:e=>Ln(e),loadFeedData:e=>Cs(e),updateFeedQuery:e=>HK(e),hasMorePages:lh};function uh(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;nH(n,h(jK,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:UK}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function ud(e="Loading selected project..."){uh([],{loadingText:e})}function GK(){tH(),uh(y.lastFeedItems,y.lastFeedItems.length||y.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),gk||(window.addEventListener("scroll",()=>{Pk()},{passive:!0}),gk=!0),vk||(document.getElementById("tab-feed")?.addEventListener("click",e=>{e.target?.closest(".feed-item button.feed-title")&&Pi("inspect")}),vk=!0)}function HK(e){if(e===y.feedQuery)return;const t=y.feedQuery.trim();y.feedQuery=e,e.trim()!==t&&(ch(y.currentProject||""),ud("Searching memories…"),Ss&&clearTimeout(Ss),Ss=setTimeout(()=>{Ss=null,Cs().catch(()=>{})},250))}function Ln(e=!1){if(dh(),!document.getElementById("tab-feed"))return;const t=window.scrollY,n=mk(y.lastFeedItems),r=OK(n),i=e||r!==y.lastFeedSignature;y.lastFeedSignature=r,i&&uh(n,{errorText:Ur||void 0}),window.scrollTo({top:t}),y.viewerReconnectOpen||Pk()}function Nk(e,t){return ph(e.generation,t)&&dd(e)}function ph(e,t){return Ho?.generation===e&&Ho.requestId===t}function Tk(e,t,n){return!!(n.restart||e!==hk||y.feedScopeFilter!==yk||bk(ws,y.viewerActorId)||t!==sh)}function VK(e,t){Ck(e,{head:!0});const n=e.summaries.items||[],r=e.observations.items||[],i=t?r:r.filter(d=>!pC(d)),o=r.length-i.length,s=_k([...n,...i],t),c=y.lastFeedItems,l=FG(c,s);if(ZG(l,c)&&c.length>0){const d=new Set(c.map(At));l.forEach(u=>{d.has(At(u))||y.newItemKeys.add(At(u))})}y.pendingFeedItems=null,y.lastFeedItems=l,Ur="",y.lastFeedFilteredCount=Math.max(y.lastFeedFilteredCount,o)}function KK(e){const t=y.currentProject||"",n=y.feedQuery.trim(),r=n!==sh;return Tk(t,n,e)&&(ch(t),ud(r?"Searching memories…":void 0)),dh(),wk()}function WK(){return Ur?(Ur="",y.lastFeedItems.length>0?Ln(!0):ud(y.feedQuery.trim()?"Searching memories…":void 0),!0):!1}async function zK(e){const{error:t,context:n,requestId:r,requestOptions:i}=e;if(!i.signal?.aborted){if(!Nk(n,r))throw t;if(Ik(t)){await kk(n,i);return}throw Rk(),t}}async function Cs(e={}){const t=KK(e),n=++$K;Ho={generation:t.generation,requestId:n};const r=WK();try{const i=await Sk(t,{head:!0,signal:e.signal});if(e.signal?.aborted||!Nk(t,n))return;VK(i,t.query),ph(t.generation,n)&&(Ho=null),Ln(r)}catch(i){await zK({error:i,context:t,requestId:n,requestOptions:e})}finally{ph(t.generation,n)&&(Ho=null)}}function tQ(e){return e}function JK(e){const t=new Date(e.periodStart),n=new Date(e.periodEnd),r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),i=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});return t.getFullYear()===n.getFullYear()?[r.format(t),i.format(n)]:[i.format(t),i.format(n)]}function YK(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function XK(e){if(e.freshEvaluations===0)return[{label:"Recalls checked",value:0,tooltip:"No automatic recalls were checked for repeated memories in this period.",icon:"activity"},{label:"Not checked",value:e.unmeasuredAttempts,tooltip:`Codemem could not check ${e.unmeasuredAttempts.toLocaleString()} automatic recalls for repeated memories, so savings are unknown.`,icon:"circle-help"}];const t=YK(e.evaluationsWithDuplicates,e.freshEvaluations),n=e.missingRetainedMetadata>0||e.invalidRetainedMetadata>0||e.packMetadataGaps>0;return[{label:"Recalls with repeats",value:t,tooltip:`Codemem removed repeated memories from ${e.evaluationsWithDuplicates.toLocaleString()} of ${e.freshEvaluations.toLocaleString()} automatic recalls.`,icon:"filter"},{label:"Memories skipped",value:e.duplicatesOmitted,tooltip:`Codemem left out ${e.duplicatesOmitted.toLocaleString()} memories that were already in your conversation, out of ${e.candidateItems.toLocaleString()} considered.`,icon:"minus-circle"},{label:"Repeated tokens removed",value:`~${Aa(e.estimatedTokensAvoided)}`,tooltip:`About ${e.estimatedTokensAvoided.toLocaleString()} tokens were left out because they repeated information already in your conversation.`,icon:"trending-down"},{label:"Recalls checked",value:e.freshEvaluations,tooltip:`Codemem checked ${e.freshEvaluations.toLocaleString()} automatic recalls for repeated memories. ${e.unmeasuredAttempts.toLocaleString()} more could not be checked.${n?" Some results may be incomplete.":""}`,icon:"activity"}]}function QK(e){if(!e||e.availability==="unavailable")return h("p",{class:"section-meta"},"Automatic recall details aren’t available. Update Codemem and refresh this page.");const[t,n]=JK(e);return h(U,null,h("div",{class:"grid-2 automatic-recall-grid"},XK(e).map(r=>h(Ak,{...r,key:`${r.label}-${r.icon}`}))),h("p",{class:"automatic-recall-meta"},h("time",{dateTime:e.periodStart},t),"–",h("time",{dateTime:e.periodEnd},n),` · Based on up to ${e.windowLimit.toLocaleString()} recent automatic recalls across all projects.${e.freshEvaluations===0?" No recalls were checked, so savings are unknown.":""}`))}function ZK(e,t){e&&(ke(h(ls,null,h("details",{class:"automatic-recall"},h("summary",null,"Automatic recall"),h("section",{"aria-label":"Automatic recall measurements"},QK(Wg(t))))),e),ks())}function Vo(e,t){return t.error?`${e} ${t.error}`:e}function pd(e,t){return t.recommended_action?`${e} ${t.recommended_action}`:e}function e3(e){return e.unavailable?{label:"Update check unavailable",title:pd(Vo("Could not check for updates.",e),e),tone:"badge-offline"}:e.install_kind==="repo-dev"?{label:`Source build · ${e.current_version}`,title:pd(Vo(`Running from repository source. Package metadata version: ${e.current_version}. Registry releases do not describe the checked-out source revision.`,e),e),tone:"health-update-source"}:e.channel?e.latest_version?e.update_available?{label:`Update available · ${e.latest_version}`,title:Vo(`Codemem ${e.latest_version} is available. Installed version: ${e.current_version}.`,e),tone:"badge-online",showCopy:!!e.recommended_action}:{label:`Up to date · ${e.current_version}`,title:Vo(`Codemem ${e.current_version} is up to date. You are running the latest ${e.channel==="latest"?"stable":e.channel} release.`,e),tone:"badge-online"}:{label:"Update check unavailable",title:pd(Vo("Could not check for updates.",e),e),tone:"badge-offline"}:{label:"Unsupported channel",title:pd(Vo("The installed version is not on a supported release channel.",e),e),tone:"badge-offline"}}function t3({command:e}){return h("code",{class:"health-update-command",id:"healthUpdateCommand"},e)}function n3({status:e}){const t=e3(e),n=t.tone!=="badge-online"||e.stale||!!e.error,r=e.stale?`${t.title} ${e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale."}`:t.title;let i=null;function o(){!e.recommended_action||!i||Po(e.recommended_action,i)}return h("section",{class:"health-update-banner",role:"status","aria-atomic":"true","aria-label":"Codemem update status"},h("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),h(Ne,{variant:"badge",tone:t.tone,title:t.title},t.label),n?h("span",{class:"health-update-detail"},r):null,t.showCopy&&e.recommended_action?h(t3,{command:e.recommended_action}):null,e.stale?h(Ne,{variant:"badge",title:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale."},"Cached"):null,t.showCopy&&e.recommended_action?h("button",{"aria-describedby":"healthUpdateCommand",class:"settings-button health-update-copy-button",onClick:o,ref:s=>{i=s},title:e.recommended_action,type:"button"},"Copy command"):null)}function r3(e,t){e&&(e.hidden=!t,ke(t?h(n3,{status:t}):null,e))}function i3({label:e,value:t,detail:n,icon:r,className:i,title:o,loading:s}){const c=h("div",{class:`stat${i?` ${i}`:""}${o?" has-tooltip":""}`},r?h("span",{class:"health-icon-slot",key:`${r}-${s?"loading":"static"}`},h("i",{"aria-hidden":"true","data-lucide":r,class:`stat-icon${s?" health-loading-icon":""}`})):null,h("div",{class:"stat-content"},h("div",{class:"value"},t),h("div",{class:"label"},e),n?h("div",{class:"small"},n):null));return o?h(Oo,{label:o},c):c}function o3({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action(t)}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Po(e.command,n)}return h("div",{class:"health-action"},h("div",{class:"health-action-text"},e.label,e.command?h("span",{class:"health-action-command"},e.command):null),h("div",{class:"health-action-buttons"},e.action?h("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?h("button",{class:"settings-button health-action-copy",onClick:o,ref:s=>{n=s}},"Copy"):null))}function a3(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function Ak({label:e,value:t,icon:n,tooltip:r}){const i=h("div",{class:`stat${r?" has-tooltip":""}`,tabIndex:r?0:void 0},h("i",{"data-lucide":n,class:"stat-icon"}),h("div",{class:"stat-content"},h("div",{class:"value"},a3(t)),h("div",{class:"label"},e)));return r?h(Oo,{label:r},i):i}function Ek(e,t){e&&ke(h(ls,null,t.map(n=>h(Ak,{...n,key:`${n.label}-${n.icon}`}))),e)}function fd(e,t){e&&ke(h(U,null,t),e)}function ks(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function s3({label:e,value:t,state:n,title:r}){return h("div",{class:"health-tile",title:r},h("span",{class:"health-tile-label"},e),h("span",{class:"health-tile-value"},h(jn,{state:n,size:6}),t))}function xk(e,t,n){e&&ke(h(ls,null,h("div",{class:"health-tile-grid"},t.map(r=>h(s3,{...r,key:r.key}))),n.length?h("div",{class:"grid-2 health-maintenance-grid"},n.map(r=>h(i3,{...r,key:r.key??r.label}))):null),e)}function c3({label:e,message:t,stale:n,state:r,statusClass:i}){return h("div",{class:"health-status-summary"},h(jn,{state:r,size:8}),h("div",{class:"health-status-copy"},h("strong",{class:`health-status-word ${i}`},e),h("div",{class:"health-status-meta"},h("div",{class:"section-meta",id:"healthMeta",role:"status","aria-live":"polite","aria-atomic":"true"},h("span",{class:"sr-only"},`${e} · `),t,n?h("span",{class:"sr-only"}," · Stale data"):null),n?h(Ne,{variant:"badge"},"Stale data"):null)))}function Dk(e,t){e&&ke(h(c3,t),e)}function jk(e,t){if(e){if(!t.length){e.hidden=!0,ke(null,e);return}e.hidden=!1,ke(h(U,null,t.slice(0,3).map((n,r)=>h(o3,{item:n,key:`${n.label}-${r}`}))),e)}}var Ok="codemem-settings-advanced",fh="gpt-6-luna",Lk="claude-4.5-haiku",l3=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],md={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"},d3=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),u3={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 mh(e){return String(e||"").replace(/_/g," ")}function hd(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 p3(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"api_direct":return"Direct API key";case"opencode_v2":return"OpenCode account";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 f3(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 m3(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var h3=["opencode","claude","codex","pi"];function $k(){return hd([...h3])}function g3(){try{return globalThis.localStorage?.getItem(Ok)==="1"}catch{return!1}}function v3(e){try{globalThis.localStorage?.setItem(Ok,e?"1":"0")}catch{}}function Kt(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ie(e,t,n){if(Kt(t,n))return t[n];if(Kt(e,n))return e[n]}function Ae(e){return e==null?"":String(e)}function gd(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 y3(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function b3(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Ze(e){const t=e.trim();return t===""?"":t}function _3(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:Lk,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:fh,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:Lk,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:`opencode/${fh}`,source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:fh,source:"Recommended (direct API)"}}function w3(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return Ze(Ae(n[t]));case"observer_runtime":return Ze(Ae(n.observer_runtime));case"observer_auth_source":return Ze(Ae(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([o,s])=>{typeof o=="string"&&o.trim()&&typeof s=="string"&&(i[o.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Kt(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(!Kt(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Kt(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 gd(n[t]);default:return Kt(n,t)?n[t]:""}}function S3(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Kt(r,i)&&(r[i]=w3(t,i))}),r}function hh(e,t){let n=e.events_global;return t&&(n=e.events_filtered??e.events),n.find(r=>r.event==="pack")??null}var Mk="scope_id_backfill",C3={"offline-peers":"Offline peers",needs_attention:"Needs attention",rebootstrapping:"Rebootstrapping"};function Fk(){const e=document.getElementById("healthDot");e&&(e.className="health-dot status-unknown",e.title="Open Health to check status");const t=document.getElementById("metaLine");t&&fd(t,"")}function k3(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthStatus");return!e||!t?null:{healthGrid:e,healthStatus:t,healthActions:document.getElementById("healthActions"),healthDot:document.getElementById("healthDot")}}function I3(e,t){const n=[`${e} ${e===1?"issue":"issues"}`];return e>0&&t.length>0&&n.push(t.join(", ")),n.join(" · ")}function R3(e){return e==="status-healthy"?"online":e==="status-degraded"?"degraded":e==="status-attention"?"attention":"unknown"}function P3(e,t){return e>=60?{label:"Attention",className:"status-attention"}:e>=25?{label:"Degraded",className:"status-degraded"}:t?{label:"Stale",className:"status-unknown"}:{label:"Healthy",className:"status-healthy"}}function N3(e){return C3[e]??yb(e)}function T3(e){const t=new Map,n=new Set(e.map(r=>r.peer_device_id));for(const r of y.lastSyncAttempts){if(!r||typeof r!="object")continue;const i=r,o=i.peer_device_id;if(typeof o!="string"||!n.has(o)||t.has(o))continue;const s=typeof i.finished_at=="string"?Date.parse(i.finished_at):NaN,c=Date.now()-s;!Number.isFinite(c)||c<0||c>6e5||t.set(o,i.status==="error")}return new Set([...t].filter(([,r])=>r).map(([r])=>r))}function Bk(e,t){return[...new Set(e.filter(t).map(n=>n.name||n.peer_name||n.display_name||"").map(n=>n.trim().slice(0,60)).filter(Boolean))].sort((n,r)=>n.localeCompare(r))}function A3(e,t){return e.status?.recent_failed_attempt===!0||e.status?.peer_state==="degraded"||!!e.has_error||!!(e.peer_device_id&&t.has(e.peer_device_id))}function E3(e,t){return t.size>0||e.some(n=>n.status?.recent_failed_attempt===!0)}function x3(){const e=y.lastSyncStatus??{},t=String(e.daemon_state||"unknown"),n=t==="disabled"||e.enabled===!1,r=Array.isArray(y.lastSyncPeers)?y.lastSyncPeers:[],i=T3(r),o=po(e.last_sync_at||e.last_sync_at_utc||null);return{syncState:t,syncIssueCode:e.daemon_issue_code??null,syncStateLabel:N3(t),syncDisabled:n,syncOfflinePeers:t==="offline-peers",syncNoPeers:!n&&r.length===0,syncAgeSeconds:o,syncLooksStale:o!==null&&o>7200,syncRecentlyOk:o!==null&&o<=300,syncHasRecentFailedAttempt:E3(r,i),syncProblemPeers:Bk(r,s=>A3(s,i)),syncOfflinePeersNames:Bk(r,s=>s.status?.peer_state==="offline")}}function D3(e,t,n){const r=hh(t,t.events_filtered!=null),i=t.recent_packs[0]?.created_at??null,o=r?Rp(r.total_tokens_saved,r.total_tokens_read):"n/a",s=e.maintenance_jobs;return{maintenanceJobs:s,scopeBackfillJob:s.find(c=>c.kind===Mk),hasFailedMaintenance:s.some(c=>c.status==="failed"),hasLowTagCoverage:e.database.active_memory_items>0&&e.database.tags_coverage<.7,rawPending:n.pending,erroredBatches:e.reliability?.counts.errored_batches??0,hasReliability:e.reliability!==void 0,flushSuccessRate:e.reliability?.rates.flush_success_rate??1,droppedRate:e.reliability?.rates.dropped_event_rate??0,reductionLabel:o,reductionPercent:px(o),hasPackUsage:r!==null,lastPackAt:i,packAgeSeconds:po(i),...x3(),hasBacklog:n.pending>=200}}function We(e,t,n){e.score+=t,e.drivers.push(n)}function j3(e,t){t.rawPending>=1e3?We(e,40,"high raw-event backlog"):t.rawPending>=200&&We(e,24,"growing raw-event backlog"),t.erroredBatches>0&&t.rawPending>=200&&We(e,t.erroredBatches>=5?10:6,"batch errors during backlog pressure"),t.flushSuccessRate<.95&&We(e,20,"lower flush success"),t.droppedRate>.02?We(e,24,"high dropped-event rate"):t.droppedRate>.005&&We(e,10,"non-trivial dropped-event rate")}function O3(e,t){t.syncState==="error"&&We(e,36,t.syncIssueCode==="coordinator_timeout"?"coordinator sync requests timed out":"background sync failed"),t.syncState==="needs_attention"&&We(e,40,"sync needs manual attention"),t.syncState==="stopped"&&We(e,22,"sync daemon stopped"),t.syncState==="stale"&&We(e,20,"sync daemon stale"),t.syncState==="rebootstrapping"&&We(e,20,"sync daemon rebootstrapping"),t.syncState==="degraded"&&(!t.syncRecentlyOk||t.syncHasRecentFailedAttempt||t.syncProblemPeers.length>0)&&We(e,t.syncRecentlyOk?26:20,"sync with paired devices failed"),t.syncState==="ok"&&t.syncHasRecentFailedAttempt&&We(e,26,"sync with paired devices failed")}function L3(e,t){if(t.syncOfflinePeers){We(e,4,"all peers currently offline"),t.syncLooksStale&&We(e,4,"offline peers and sync not recent");return}if(t.syncLooksStale){We(e,26,"sync looks stale");return}t.syncAgeSeconds!==null&&t.syncAgeSeconds>1800&&We(e,12,"sync not recent")}function $3(e){const t={score:0,drivers:[]};return y.lastSyncStatus?.sync_health?.state==="needs_attention"&&We(t,26,"device sync needs attention"),j3(t,e),e.hasLowTagCoverage&&We(t,8,"low tag coverage"),e.hasFailedMaintenance&&We(t,30,"maintenance job failed"),!e.syncDisabled&&(!e.syncNoPeers||e.syncState==="error")&&(O3(t,e),L3(t,e)),e.reductionPercent!==null&&e.reductionPercent<10&&We(t,8,"low retrieval reduction"),e.packAgeSeconds!==null&&e.packAgeSeconds>86400&&We(t,12,"memory pack activity is old"),t}function M3(e){const t=Number(e.progress?.current||0),n=typeof e.progress?.total=="number"?e.progress.total:null,r=String(e.progress?.unit||"items");if(!n||n<=0)return`${t.toLocaleString()} ${r}`;const i=Math.round(100*t/n);return`${t.toLocaleString()}/${n.toLocaleString()} ${r} (${i}%)`}function F3(e){const t=M3(e),n=String(e.title||"Maintenance"),r=e.kind===Mk;let i=t,o=r?"One-time upgrade backfill; totals include memories and replication ops":void 0,s="loader",c=r?`${n} in progress; inspect with codemem maintenance status`:`${n} in progress`;return e.status==="failed"?(i="Failed",o=String(e.error||"unknown error").trim(),s="alert-triangle",c=`Error: ${e.error||"unknown"}`):e.status==="completed"&&(i="Complete",o=r?`${t} · one-time Sharing-domain upgrade finished`:t,s="check-circle",c=`${n} finished`),{key:String(e.kind||e.title||"background-maintenance"),label:String(e.title||e.kind||"Background maintenance"),value:i,detail:o,icon:s,className:e.status==="failed"?"status-attention":void 0,title:c}}function B3(e){if(!e.hasReliability)return Wt("pipeline","Pipeline",`${e.rawPending>0?`${e.rawPending.toLocaleString()} pending · `:""}Reliability unknown`,e.rawPending>0?"degraded":"unknown","Raw-event queue pressure and flush reliability");const t=e.flushSuccessRate<.95||e.droppedRate>.005;if(e.rawPending===0&&!t)return Wt("pipeline","Pipeline","Queue clear","online","Raw-event queue pressure and flush reliability");const n=e.rawPending>0?`${e.rawPending.toLocaleString()} pending · `:"";return e.droppedRate>.02?Wt("pipeline","Pipeline",`${n}Events dropped`,"attention","Raw-event queue pressure and flush reliability"):t?Wt("pipeline","Pipeline",`${n}Reliability degraded`,"degraded","Raw-event queue pressure and flush reliability"):Wt("pipeline","Pipeline",`${e.rawPending.toLocaleString()} pending`,"degraded","Raw-event queue pressure and flush reliability")}function q3(e){const t=y.lastSyncStatus?.sync_health;if(!e.syncDisabled){let n="unknown";return t?.state==="exchange_succeeded"&&(n="online"),t?.state==="needs_attention"&&(n="attention"),t?.state==="stale"&&(n="degraded"),Wt("sync","Sync",jo(t),n,Rm(t))}return Wt("sync","Sync","Off","unknown","Sync is disabled")}function U3(e){if(!e.hasPackUsage)return Wt("retrieval","Retrieval","No packs yet","unknown","Reduction from memory reuse across recent usage");if(e.reductionPercent===null)return Wt("retrieval","Retrieval","Unknown","unknown","Reduction is unavailable for the recorded pack usage");const t=e.reductionPercent!==null&&e.reductionPercent<10;return Wt("retrieval","Retrieval",e.reductionLabel,t?"degraded":"online","Reduction from memory reuse across recent usage")}function G3(e){if(!e.lastPackAt)return Wt("freshness","Data freshness",e.hasPackUsage?"Unknown":"No packs yet","unknown","Recency is unknown when pack usage exists outside the recent activity window");if(e.packAgeSeconds===null)return Wt("freshness","Data freshness","Unknown","unknown","The last memory pack timestamp is unavailable");const t=e.packAgeSeconds!==null&&e.packAgeSeconds>86400;return Wt("freshness","Data freshness",Ta(e.packAgeSeconds),t?"degraded":"online","Recency of last memory pack activity")}function Wt(e,t,n,r,i){return{key:e,label:t,value:n,state:r,title:i}}function H3(e){return[B3(e),q3(e),U3(e),G3(e)]}function V3(e){return e.hasBacklog?[{label:"Pipeline needs attention. Check queue health first.",command:"codemem diagnostics capture status",action:t=>Tr({subsystem:"capture",trigger:t}),actionLabel:"View diagnostics"},{label:`Then retry failed batches for impacted sessions (${$k()}).`,command:"codemem diagnostics capture retry"}]:e.syncState==="stopped"?[{label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}]:e.syncDisabled||e.syncNoPeers&&e.syncState!=="error"?[]:e.syncState==="degraded"&&e.syncRecentlyOk&&!e.syncHasRecentFailedAttempt&&e.syncProblemPeers.length===0?[]:["error","degraded","offline-peers","stale","needs_attention"].includes(e.syncState)||e.syncState==="ok"&&e.syncHasRecentFailedAttempt||e.syncLooksStale?z3(e):[]}function qk(e){const t=e.slice(0,2).join(", ");return e.length>2?`${t} +${e.length-2} more`:t}function K3(e,t){return e.syncIssueCode==="coordinator_timeout"?"Coordinator sync requests timed out. Check the coordinator connection.":e.syncIssueCode==="coordinator_error"?"Coordinator enrollment failed. Review sync diagnostics before retrying.":`Background sync reported an unresolved error.${t?` Check sync with ${t}.`:""}`}function W3(e){const t=qk(e.syncProblemPeers);if(e.syncState==="error")return K3(e,t);if(e.syncState==="offline-peers"){const n=qk(e.syncOfflinePeersNames);return`All paired devices are offline${n?`: ${n}`:""}. Check those devices' connections.`}return e.syncState==="degraded"||e.syncState==="ok"&&e.syncHasRecentFailedAttempt?t?`Sync with ${t} is failing. Other devices may still sync.`:"Some device sync attempts are failing.":e.syncState==="needs_attention"?"Sync requires manual attention.":"Paired devices have not synced recently."}function z3(e){return[{label:W3(e),command:"codemem sync doctor",action:t=>Tr({subsystem:"sync",trigger:t}),actionLabel:"View diagnostics"}]}function J3(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>Tr({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function Y3(e){const t=V3(e);J3(t,e.hasFailedMaintenance),e.hasLowTagCoverage&&t.length<2&&t.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem maintenance backfill tags --dry-run"});const n=e.scopeBackfillJob?.status!=="completed";return e.scopeBackfillJob&&n&&t.length<3&&t.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),t}function Uk(e,t){e&&(e.className=`health-dot ${t.className}`,e.title=t.label)}function X3(e,t,n,r,i){const o=Y3(t),s=t.maintenanceJobs.map(F3);Uk(e.healthDot,r),xk(e.healthGrid,H3(t),s),jk(e.healthActions,o),Dk(e.healthStatus,{label:r.label,message:I3(n.drivers.length,n.drivers),stale:i,state:R3(r.className),statusClass:r.className}),ks()}function gh(){const e=k3();if(!e)return;r3(document.getElementById("healthUpdateBanner"),y.lastUpdateStatus);const t=ir(y.healthStats),n=ir(y.healthUsage,y.currentProject),r=ir(y.healthRawEvents);if(!t||!n||!r){Q3(e);return}const i=D3(t,n,r),o=$3(i),s=y.lastSyncStatus?.sync_health,c=!i.syncDisabled&&(!s||["not_verified","stale"].includes(s.state))||[y.healthStats,y.healthUsage,y.healthRawEvents].some(l=>kl(l));X3(e,i,o,P3(o.score,c),c)}function Q3(e){const t=[y.healthStats,y.healthUsage,y.healthRawEvents],n=t.some(c=>c.status==="failed"),r=t.some(c=>c.status==="loading"),i=r&&!n;let o="Not loaded",s="Open or refresh Health to load status.";n?(o="Unavailable",s="Some health data failed to load. Refresh Health to try again."):r&&(o="Loading",s="Loading health data…"),xk(e.healthGrid,[],[]),jk(e.healthActions,[]),Dk(e.healthStatus,{label:o,message:s,stale:!1,state:i?"syncing":"unknown",statusClass:"status-unknown"}),Uk(e.healthDot,{label:o,className:"status-unknown"}),ks()}function Z3(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=ir(y.healthUsage,y.currentProject),r=ir(y.healthSession,y.currentProject),{latestPack:i,packCount:o,packLine:s}=eW(n),c=i?.created_at||"",l=c?`Last pack: ${sn(c)}`:"",d=y.currentProject?"Project":"All projects",u=tW(r,y.healthSession.status==="failed"),f=rW(i,o),p=nW(n,r)?"Showing stale data":"";fd(t,[d,s,l,u,p].filter(Boolean).join(" · ")),Ek(e,f),ks()}function eW(e){if(!e)return{latestPack:null,packCount:null,packLine:"Pack totals unavailable"};const t=e.events.find(n=>n.event==="pack")?.count??0;return{latestPack:e.recent_packs[0]??null,packCount:t,packLine:t?`${t} packs`:"No packs yet"}}function tW(e,t){return e?`${e.total.toLocaleString()} stored items`:t?"Stored-item totals unavailable":""}function nW(e,t){return!!e&&kl(y.healthUsage,y.currentProject)||!!t&&kl(y.healthSession,y.currentProject)}function rW(e,t){const n=e?.metadata_json||{},r=e?.tokens_read??0,i=e?.tokens_saved??0,o=n.exact_duplicates_collapsed??0,s=Rp(i,r);let c="n/a";return e&&(c=n.exact_dedupe_enabled?"On":"Off"),[{label:"Last pack savings",value:e?`${Aa(i)} (${s})`:"n/a",tooltip:e?`Estimate: ${i.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:e?Aa(r):"n/a",tooltip:e?`Estimate: ${r.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:e?o.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:c,icon:"shield-check"},{label:"Packs",value:t??"n/a",icon:"archive"}]}function iW(e,t,n){if(t>0){e.push({label:"Raw events pending",value:t,tooltip:"Pending raw events waiting to be flushed",icon:"activity"});return}n>0&&e.push({label:"Raw sessions",value:n,tooltip:"Sessions with pending raw events",icon:"inbox"})}function oW(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=ir(y.healthStats),r=ir(y.healthUsage,y.currentProject),i=ir(y.healthRawEvents),o=n?.database,s=y.currentProject,c=r?.totals_filtered??null,l=!!(s&&c),d=r?hh(r,!1):null,u=r?hh(r,l):null,f=i?.sessions??0,p=i?.pending??0,m=l&&d?`
|
|
119
119
|
Global: ${d.total_tokens_read.toLocaleString()} estimated injected`:"",g=l&&d?`
|
|
120
|
-
Global: ${d.total_tokens_saved.toLocaleString()} estimated saved`:"",b=[{label:l?"Savings (project)":"Savings",value:u?Aa(u.total_tokens_saved):"n/a",tooltip:u?`Estimated tokens saved by reusing compressed memories: ${u.total_tokens_saved.toLocaleString()}${g}`:"Usage data is unavailable",icon:"trending-up"},{label:l?"Injected (project)":"Injected",value:u?Aa(u.total_tokens_read):"n/a",tooltip:u?`Estimated tokens injected into context (pack size): ${u.total_tokens_read.toLocaleString()}${m}`:"Usage data is unavailable",icon:"book-open"},{label:l?"Reduction (project)":"Reduction",value:u?Rp(u.total_tokens_saved,u.total_tokens_read):"n/a",tooltip:u?`Estimated percent reduction from reuse. Factor: ${ux(u.total_tokens_saved,u.total_tokens_read)}.${m}${g}`:"Usage data is unavailable",icon:"percent"},{label:l?"Work investment (project)":"Work investment",value:"n/a",tooltip:"Work-investment data is unavailable",icon:"pencil"},{label:"Active memories",value:o?.active_memory_items??"n/a",icon:"check-circle"},{label:"Embedding coverage",value:o?vb(o.vector_coverage):"n/a",tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:o?vb(o.tags_coverage):"n/a",tooltip:"Share of active memories with tags",icon:"tag"}];i&&iW(b,p,f),Ek(e,b),t&&aW(t,o,s),ks()}function aW(e,t,n){if(!t){fd(e,sW(y.healthStats,"Database metrics"));return}const r=n?` · project: ${n}`:"",i=kl(y.healthStats)?" · showing stale data":"",o=mx(t.path);fd(e,`DB: ${o} · ${hx(t.size_bytes)}${r}${i}`)}function sW(e,t){return e.status==="loading"?`Loading ${t.toLowerCase()}…`:e.status==="failed"?`${t} failed to load`:`${t} not loaded`}var Gk=0,Di=null;function vd(){Di?.cancel()}function cW(e){if(y.activeTab!=="health"||y.lastUpdateStatus&&!y.lastUpdateStatus.unavailable||Di||e.signal?.aborted)return;const t=nc(),n={cancel:()=>{Di===n&&(Di=null,t.abort(),t.dispose(),e.signal?.removeEventListener("abort",n.cancel))}};Di=n,e.signal?.addEventListener("abort",n.cancel,{once:!0}),Un($T({signal:t.signal}),t.signal).then(i=>r(i),i=>r(MT(i)));function r(i){Di===n&&(Di=null,t.dispose(),e.signal?.removeEventListener("abort",n.cancel),y.activeTab==="health"&&(y.lastUpdateStatus=i,gh()))}}async function lW(e={}){const t=y.viewerActorId,n=await _N(e);if(e.signal?.aborted)return;y.viewerActorId=n.identity.actor_id;const r=document.getElementById("syncNowButton");if(r&&(r.disabled=y.viewerActorId===null||r.getAttribute("aria-busy")==="true"),t!==y.viewerActorId){if(t!==null&&y.activeTab==="feed"){await Cs({restart:!0,signal:e.signal}).catch(()=>{});return}Ln(!0)}}async function dW(e={}){const t=++Gk,n=y.currentProject;y.healthStats=Cl(y.healthStats),y.healthUsage=Cl(y.healthUsage,n),y.healthSession=Cl(y.healthSession,n),y.healthRawEvents=Cl(y.healthRawEvents),Is();const r=()=>!e.signal?.aborted&&t===Gk;cW(e),await Promise.all([yd(EN(e)).then(i=>{r()&&(y.healthStats=bd(y.healthStats,i),Is())}),yd(xN(n,e)).then(i=>{r()&&(y.healthUsage=bd(y.healthUsage,i,n),Is())}),yd(DN(n,e)).then(i=>{r()&&(y.healthSession=bd(y.healthSession,i,n),Is())}),yd(jN(n,e)).then(i=>{r()&&(y.healthRawEvents=bd(y.healthRawEvents,i),Is())})])}function Is(){oW(),ZK(document.getElementById("automaticRecallStats"),ir(y.healthStats)?.automatic_recall),Z3(),gh()}async function yd(e){try{return{ok:!0,data:await e}}catch(t){return{ok:!1,error:t instanceof Error?t.message:"Health request failed"}}}function bd(e,t,n=""){return"data"in t?K1(t.data,Date.now(),n):W1(e,t.error)}function vh(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function Hk(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function Vk(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var uW={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function Kk(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function pW(e){return e.targetIdentityRef?e.targetIdentityRef:e.identityEvidence==="label"?"":e.existingIdentityRef??""}function fW(e,t){return e.identityEvidence==="label"?`This computer lists it as ${t}. Confirm the person who uses that device.`:e.verifiedEvidenceKind==="active_assignment"?`Current assignment: ${t} · verified active assignment`:`Current assignment: ${t}`}function mW({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=ht(),f=`${u}-identity`,p=`${u}-evidence`,m=`${u}-assignment-help`,g=pW(o),b=o.targetIdentityRef??"",[_,v]=R(g);q(()=>v(g),[g]);const S=i.identityChoices.some(O=>O.identityRef===_),w=Kk(i,o.existingIdentityRef),k=Kk(i,o.suggestedIdentityRef),P=n?.has(o.deviceRef)??!1,T=e||P||r,E=T||!o.actions.assignIdentity.enabled,$=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!_&&!S,A=!o.actions.include.enabled||$||F||!b||_!==b,j=T||A,D=E||!_||$||F||_===b,H=!o.enabled||A,V=e?t:P?vh("device",o.deviceRef):void 0,z=[p,H?m:void 0,V].filter(Boolean).join(" "),M=[p,V].filter(Boolean).join(" "),C=o.decision==="unresolved";return a("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:[a("legend",{children:o.displayName}),C?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,a("div",{className:"small legacy-team-device-evidence",id:p,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),w?a("span",{children:fW(o,w)}):null,!w&&k?a("span",{children:["Suggested person: ",k]}):null,a("span",{children:["Decision: ",uW[o.decision]]})]}),a("label",{htmlFor:f,children:"Person using this device"}),a(Pn,{"aria-describedby":z,className:"legacy-team-device-select",disabled:E,id:f,onChange:O=>v(O.currentTarget.value),value:_,children:[a("option",{value:"",children:"Choose a person"}),_&&!S?a("option",{value:_,children:"Current server assignment"}):null,i.identityChoices.map(O=>a("option",{value:O.identityRef,children:O.displayName},O.identityRef))]}),o.enabled?F?a("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):$?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!_||!b||_!==b?a("p",{className:"small",id:m,children:_?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:a("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),a("div",{className:"legacy-team-device-actions",children:[a("button",{"aria-describedby":z,"aria-disabled":D?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{D||c(o,_)},type:"button",children:"Save assignment"}),o.enabled?a(U,{children:[a("button",{"aria-describedby":z,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{j||d(o,"included",b)},type:"button",children:"Include"}),a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function hW(e){const t=Hk(e.detail.devices);return a("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[a("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),a("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),a("div",{className:"legacy-team-device-list",children:t.map((n,r)=>h(mW,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function gW(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function vW({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=ht(),d=`${l}-mapping`,u=`${l}-help`,f=c.resolvedProjectRef??"",p=di(c.mappingChoices.map(z=>({canonicalId:z.resolvedProjectRef,displayName:z.displayName}))),m=[...new Set(c.mappingChoices.map(z=>z.resolvedProjectRef))],g=[...m].sort((z,M)=>z<M?-1:z>M?1:0),b=new Map(g.map((z,M)=>[z,`project-choice-${M+1}`])),_=new Map(c.mappingChoices.map(z=>[z.resolvedProjectRef,z])),v=m.flatMap(z=>{const M=_.get(z);return M?[{...M,label:p.get(z)??M.displayName,token:b.get(z)??""}]:[]}),S=v.find(z=>z.resolvedProjectRef===f)?.token??"",w=JSON.stringify(g),[k,P]=R(S);q(()=>P(S),[S,w]);const T=v.find(z=>z.token===k)?.resolvedProjectRef,E=n?.has(c.projectRef)??!1,$=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!k,A=e||E||r||!c.actions.map.enabled,j=A||!T||T===f,D=gW(c,p),H=[$||F?u:void 0,e?t:E?vh("project",c.projectRef):void 0].filter(Boolean).join(" "),V=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${V?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:V?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[V?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?a("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):a(U,{children:[a("p",{className:"small",children:D?`Saved mapping: ${D}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a(Pn,{"aria-describedby":H||void 0,className:"legacy-team-project-select",disabled:A,id:d,onChange:z=>P(z.currentTarget.value),value:k,children:[a("option",{value:"",children:"Choose a Project"}),v.map(z=>a("option",{value:z.token,children:z.label},z.resolvedProjectRef))]}),$?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":H||void 0,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!j&&T&&o(c,T)},type:"button",children:"Save mapping"})]})]})]})}function yW(e){const t=Vk(e.detail.projects),n=di(t.map(o=>({canonicalId:o.projectRef,displayName:o.displayName}))),r=e.detail.projects.filter(o=>o.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return a("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[a("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),a("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?a("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,a("div",{className:"legacy-team-project-list",children:t.map((o,s)=>a(vW,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(o.projectRef),index:s,onMap:e.onMap,presentationName:n.get(o.projectRef)??o.displayName,project:o},o.projectRef))}),e.detail.unresolvedProjectCount===0?a("div",{className:"legacy-team-setup-next-action",children:[a("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),a("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var Rs={add:"Add",update:"Update",remove:"Remove"},bW=10;function mt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function yh(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${kn(s)}`,d=n(o),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function bh(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${mt(e.projectRefs.size,t)}`:e.displayName}function Ps({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>bW;return a("section",{children:[a("h4",{children:i}),n.length>0?a(U,{children:[o&&r?a("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>a("li",{children:c},`${i}-summary-${l}`))}):null,s?a("details",{children:[a("summary",{children:["Show all ",mt(n.length,`exact ${t}`)]}),a(Wk,{items:n,title:i})]}):a(Wk,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function Wk({items:e,title:t}){return a("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>a("li",{children:n},`${t}-${r}`))})}function _W({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const o=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=R(null),d=c===s,u=e||!d,f=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),p=o.teamChanges.map(C=>{const O=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Rs[C.change]} ${C.teamDisplayName}: change device access from ${O} to the reviewed device list.`}),m=o.membershipChanges.map(C=>`${Rs[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),g=di([...n.projects.map(C=>({canonicalId:C.projectRef,displayName:C.displayName})),...o.projectChanges.map(C=>({canonicalId:C.projectRef,displayName:C.projectDisplayName}))]),b=o.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}]:[]]),_=di(b.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),v=new Map(b.map(C=>[C.resolvedProjectRef,_.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),S=di([...n.projects.flatMap(C=>C.canonicalProjectRef?[{canonicalId:C.canonicalProjectRef,displayName:C.displayName}]:[]),...[...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.canonicalProjectKind==="project").map(C=>({canonicalId:C.canonicalProjectRef,displayName:C.canonicalProjectDisplayName}))]),w=o.projectChanges.map(C=>`${Rs[C.change]} ${g.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?v.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?v.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),k=o.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${Rs[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),P=o.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${Rs[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),T=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,E=yh(o.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),$=yh(o.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),F=yh(o.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),A=n.devices.filter(C=>C.decision==="included").length,j=[mt(o.teamChanges.length,"Team policy change"),mt(o.membershipChanges.length,"membership change"),mt(o.projectChanges.length,"Project change"),mt(o.recipientChanges.length,"recipient change"),mt(o.deviceAccessChanges.length,"device-access change")],D=`${mt(n.projects.length,"Project")} included; ${mt(A,"included device")}.`,H=Math.max(n.candidate.projectCount,n.projects.length),V=new Set(o.deviceAccessChanges.map(C=>C.deviceRef)).size,z=[...o.teamChanges,...o.membershipChanges,...o.projectChanges,...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.change==="remove").length,M=o.teamChanges.length===0&&o.membershipChanges.length===0&&o.projectChanges.length===0&&o.recipientChanges.length>0&&o.recipientChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")&&o.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}.${V>0?` ${mt(V,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${mt(H,"reviewed Project")}.`:`${mt(T,"server-confirmed access change")} will be applied atomically; ${mt(z,"removal")} ${z===1?"is":"are"} included.`;return a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:"Review every server-confirmed access change before activating this Team."}),a("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[a("p",{className:"legacy-team-setup-net-effect",children:[a("strong",{children:"Net effect:"})," ",M]}),a("p",{children:[a("strong",{children:mt(T,"exact access change")})," to review."]}),a("ul",{children:j.map(C=>a("li",{children:C},C))}),a("p",{className:"small",children:["Scope: ",D]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(Ps,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:p,title:"Team policy"}),a(Ps,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(Ps,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:w,summaryItems:E.map(C=>`${bh(C,"reviewed Project")}, ${mt(C.changeCount,"Project change")}`),title:"Projects"}),a(Ps,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:k,summaryItems:$.map(C=>`${bh(C,"canonical Project")}, ${mt(C.changeCount,"recipient change")}`),title:"Recipients"}),a(Ps,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:P,summaryItems:F.map(C=>`${bh(C,"canonical Project")}, ${mt(C.changeCount,"device-access change")}`),title:"Device access"})]}),a("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[a("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:C=>{e&&C.preventDefault()},onChange:C=>{if(e){C.currentTarget.checked=d;return}l(C.currentTarget.checked?s:null)},type:"checkbox"}),a("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?a("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[a("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,a("button",{"aria-describedby":f||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"})]})}var _h=class extends Error{constructor(e){super("initial_setup_refresh_failed",{cause:e})}};function wW(e,t,n){return!(t instanceof _h)&&e.kind==="load"&&!e.refresh&&!e.completionOnly&&t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale"&&n!==void 0&&n.state!=="unavailable"}function SW(e){let t=null;return async n=>{try{const r=await IW(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){return CW(n,e,r)}}}async function CW(e,t,n){const r=n instanceof _h?n.cause:n;let i,o;try{i=await RW(e,t,r)}catch(s){o=s}return wW(e,n,i)?{status:"success",generation:e.generation,id:e.id,kind:e.kind,view:i}:{status:"failure",generation:e.generation,id:e.id,kind:e.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}async function kW(e,t){if(e.refresh)return t.refreshCandidate(e.candidateRef);const n=await t.loadDetail(e.candidateRef);if(e.completionOnly||e.readOnlyRecovery||n.state!=="unavailable"||n.unavailableReason!=="team_setup_confirmation_stale")return n;try{return await t.refreshCandidate(e.candidateRef)}catch(r){throw new _h(r)}}async function IW(e,t,n,r){switch(e.kind){case"load":return kW(e,t);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function RW(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Fe)||!ji(n.errorCode))){if(e.kind==="load"&&!e.refresh&&!e.completionOnly&&n.errorCode==="team_setup_confirmation_stale")return t.loadDetail(e.candidateRef);if(e.kind!=="load")return t.loadDetail(e.candidateRef)}}function ji(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function zk(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function PW(e,t,n){return Yk(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function Jk(e,t){return Yk(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function Yk(e,t){return{id:e,targetId:t}}var wh="Team setup changed since it was last reviewed. Reload the latest details to continue.",Xk="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",Qk="Team device details are temporarily unavailable. Check the coordinator connection and settings, then retry loading.",NW="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",TW="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",Zk="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",eI="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",AW="Another device completed this Team with different reviewed details. Retry to load the completed setup.",EW="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function xW(){return{status:"closed",generation:0}}function Sh(e,t){switch(t.type){case"open":return e.status==="open"&&fr(e)?e:DW(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&fr(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 jW(e,t.step);case"blocked_navigation":return _d(e,t.step,t.message);case"retry":return OW(e);case"refresh":return $W(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Ch(e,t,"assign_device");case"decide_device":return Ch(e,t,"decide_device");case"clear_device":return Ch(e,t,"clear_device");case"map_project":return LW(e,t);case"finish":return MW(e);case"command_started":return oz(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return FW(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function DW(e,t){return Gr({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 jW(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return _d(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return _d(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return _d(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:zk(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function _d(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?Hk(e.view.devices).findIndex(i=>i.decision==="unresolved"):Vk(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:PW(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function OW(e){if(e.status!=="open"||e.step==="completed"||Ns(e)||fr(e))return e;const t=wd(e)??e.errors.find(r=>r.retry),n=t?.retry??"load";return Gr(e,{kind:"load",candidateRef:e.candidateRef,refresh:n==="refresh",completionOnly:n==="completion",readOnlyRecovery:n==="load"&&t?.readOnlyRetry===!0,focusOnOutcome:!0})}function Ch(e,t,n){if(e.status!=="open"||e.step==="completed"||!kh(e.view)||wd(e)||Ns(e)||fr(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return Gr(Oi(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function LW(e,t){if(e.status!=="open"||e.step==="completed"||!kh(e.view)||wd(e)||Ns(e)||fr(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:Gr(Oi(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 $W(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Ns(e)||fr(e)?e:Gr(Oi(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function MW(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:Gr(Oi(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 Gr(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 FW(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return n.kind==="load"&&(n.completionOnly||n.readOnlyRecovery)&&t.status==="success"&&t.view?.state!=="completed"?tI(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new Fe(409,"team_setup_confirmation_stale")}):t.status==="failure"?tI(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?qW(r,n.attemptId):t.view?nI({...iz(r,n),message:BW(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function BW(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 tI(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?nI(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=t.kind==="load"&&!t.refresh&&n.recoveredView?.state==="unavailable",o=UW(t,i&&n.recoveredView?.state==="unavailable"?new Fe(409,n.recoveredView.unavailableReason):n.cause,i?void 0:n.recoveryCause),s={...r,errors:[...Oi(r,o.scope).errors,o],message:""};return t.kind!=="load"||!t.focusOnOutcome?s:{...s,focus:Jk(s.nextFocusId,{hasError:!0,recovery:s.view?.state==="unavailable",step:s.step}),nextFocusId:s.nextFocusId+1}}function nI(e,t,n){const r=nz(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:rz(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:o,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=o.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:Jk(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!oI(s,t.attemptId)&&(s=Gr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function qW(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:zk(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return oI(n,t)||(n=Gr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function UW(e,t,n){const r=t instanceof Fe&&ji(t.errorCode),i=t instanceof Fe&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=XW({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i}),l=c?null:JW(e,t,n),d=r||i||o!==null,u=WW(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null}),f=GW(e,t,n,u);return{scope:HW(e,{globalError:d}),message:l??s,hideStaleView:!!l||e.kind==="load"&&e.completionOnly||f,readOnlyRetry:f,retry:u}}function GW(e,t,n,r){return e.kind!=="load"||r!=="load"?!1:e.readOnlyRecovery?!0:t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale"&&!!n}function HW(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function VW(e,t,n){const r=n instanceof Fe&&n.errorCode==="team_setup_confirmation_stale",i=t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale";return!i&&!r?null:e.kind==="load"&&!e.refresh&&i&&n&&(!(n instanceof Fe)||!ji(n.errorCode))?"load":e.kind==="load"&&e.refresh?"completion":"refresh"}function KW(e,t){return e.kind!=="load"||!e.readOnlyRecovery||e.refresh||e.completionOnly?null:t instanceof Fe&&ji(t.errorCode)?"refresh":"load"}function WW(e,t,n,r){if(e.kind==="load"&&n instanceof Fe&&Sd(n.errorCode)!==null)return"completion";if(r.terminalRecovery)return e.kind==="load"?"completion":"load";const i=VW(e,t,n);if(i)return i;if(e.kind==="load"&&e.completionOnly)return zW(t);const o=KW(e,t);return o||(r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load")}function zW(e){return e instanceof Fe&&ji(e.errorCode)?"refresh":"completion"}function JW(e,t,n){return e.kind!=="load"||e.refresh||!(t instanceof Fe)||t.errorCode!=="team_setup_confirmation_stale"||!n?null:n instanceof Fe&&n.errorCode==="team_setup_roster_unavailable"?Qk:n instanceof Fe&&n.errorCode==="team_setup_completion_unavailable"?Zk:n instanceof Fe&&ji(n.errorCode)?wh:"The current Team setup could not be loaded. Retry to check the latest details."}function YW(e,t){return e.kind==="load"&&e.readOnlyRecovery?Qk:e.kind!=="finish"?Xk:t instanceof Fe&&t.reason==="local_candidate_scan_budget_exceeded"?TW:NW}function XW(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Fe?Sd(n.errorCode):null,c=tz(r instanceof Fe?Sd(r.errorCode):null),l=c??s,d=ZW(t.kind,l,n);return c?{completionCode:l,message:d??rI(t.kind),terminalRecoveryCode:c}:i?{completionCode:l,message:wh,terminalRecoveryCode:c}:o?{completionCode:l,message:YW(t,n),terminalRecoveryCode:c}:{completionCode:l,message:d??rI(t.kind),terminalRecoveryCode:c}}var QW="The coordinator needs an update before this Team setup can finish. No changes were applied. Ask the person who runs it to update it, then retry.";function ZW(e,t,n){return e!=="finish"?Ih(t):t==="team_setup_completion_unavailable"?ez(n):t==="team_setup_completion_invalid"&&n instanceof Fe&&n.reason==="coordinator_rejected_manifest"?QW:Ih(t)}function ez(e){return e instanceof Fe&&e.reason==="coordinator_route_missing"?`${eI} The coordinator may be running an older version.`:eI}function tz(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function rI(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 nz(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function kh(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function fr(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 Ns(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function wd(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function rz(e){if(ji(e))return wh;if(e==="team_setup_roster_unavailable")return Xk;const t=Ih(Sd(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function Sd(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function Ih(e){return e==="team_setup_completion_unavailable"?Zk:e==="team_setup_completion_conflict"?AW:e==="team_setup_completion_invalid"?EW:null}function iI(e){return e.kind==="global"||e.kind==="load"}function Oi(e,t){const n=iI(t);return{...e,errors:e.errors.filter(r=>n?!iI(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function iz(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?Oi(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?Oi(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function oz(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function oI(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var az={role:"list"},sz={role:"listitem"};function cz(e,t){return e?.state==="unavailable"||t?.retry==="refresh"||(t?.scope.kind==="load"||t?.hideStaleView===!0)&&!!e}function lz(e){const t=e.session,n=t.view,r=wd(t),i=t.commands.some(w=>w.kind==="load"),o=Ns(t)||fr(t),s=t.commands.some(w=>w.kind==="finish"),c=cz(n,r),l=r!=null&&(!n||c),d=!kh(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,f=n?`Set up ${n.candidate.displayName}`:"Set up Team",p=t.errors.filter(w=>w.scope.kind==="device"||w.scope.kind==="project"),m=p.length>0,g=p.some(w=>w.retry==="refresh"),b=new Set(p.flatMap(w=>w.scope.kind==="device"?[w.scope.itemRef]:[])),_=new Set(p.flatMap(w=>w.scope.kind==="project"?[w.scope.itemRef]:[])),v=new Set(t.commands.flatMap(w=>"deviceRef"in w?[w.deviceRef]:[])),S=new Set(t.commands.flatMap(w=>"projectRef"in w?[w.projectRef]:[]));return a(Zt,{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:w=>{w||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:a("div",{"aria-busy":o?"true":"false",className:"modal-card legacy-team-setup-card",children:[a("div",{className:"modal-header",children:[a("div",{id:"legacy-team-setup-title",tabIndex:-1,children:a(lo,{children:f})}),a(kr,{ariaDisabled:o,ariaLabel:`Close ${f}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[p.map(w=>a("p",{"aria-live":"assertive",id:"itemRef"in w.scope?vh(w.scope.kind,w.scope.itemRef):void 0,role:"alert",children:w.message},"itemRef"in w.scope?`${w.scope.kind}:${w.scope.itemRef}`:w.scope.kind)),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?g?"Refreshing…":"Retrying…":g?"Refresh Team setup":"Retry"})]}):null,n?a(U,{children:[t.step!=="completed"&&!l?a(dz,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?a(hW,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:b,busyDeviceRefs:v,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(yW,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:_,busyProjectRefs:S,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(_W,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(uz,{busy:o,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),a("div",{className:"modal-footer legacy-team-setup-actions",children:a("button",{"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function dz(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(U,{children:[a("ol",{...az,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,o)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return h("li",{...sz,className:"legacy-team-setup-step",key:i.step},a("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:o+1}),a("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${o+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?a("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?a("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function uz(e){return e.step==="completed"?a("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[a("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),a("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),a("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?a("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var pz={clearDecision:cT,finish:uT,loadDetail:oT,onCompleted:()=>{},refreshCandidate:dT,saveAssignment:aT,saveDecision:sT,saveProjectMapping:lT},Rh="codemem:open-legacy-team-setup";function aI(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(Rh,{detail:t})),t.handled}function fz(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 mz({dependencies:e}){const[t,n]=R(xW),r=x(null),i=ye(()=>SW(e),[e]),o=l=>{n(d=>Sh(d,l))};return Ge(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(f=>f.status==="open"&&fr(f)?Sh(f,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Sh(f,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(Rh,l),()=>{window.removeEventListener(Rh,l)}},[]),q(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))o({type:"command_started",id:l.id}),i(l).then(d=>o({type:"effect_outcome",outcome:d}))},[i,t]),q(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),o({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:a(lz,{session:t,onAssign:(l,d)=>o({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>o({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(fr(t)){o({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}o({type:"close"})},onCloseAutoFocus:l=>gz(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){o({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}o({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>o({type:"finish"}),onMap:(l,d)=>o({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>o({type:"navigate",step:l}),onOpenAutoFocus:hz,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var hz=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function gz(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(fz(t.current)?t.current:n)?.focus(),t.current=null}function vz(e,t={}){const n={...pz,...t};ke(a(mz,{dependencies:n}),e)}function Cd(e,t){return`${e}-${Array.from(t,n=>(n.codePointAt(0)??0).toString(16).padStart(6,"0")).join("")||"empty"}`}function kd(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Ko(e){return e.identity_source!=="unmapped"&&!kd(e)}function Ph(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function yz(e){return e.git_remote||e.repository_identity||e.cwd||""}function sI(e){return e==="git_repository"?"git repository":e.replaceAll("_"," ")}function Nh(e,t){const n=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space";return t.some(r=>r.scope_id!==e.scope_id&&(r.label||"Untitled Space")===(e.label||"Untitled Space"))?`${n} · Space ID ${e.scope_id}`:n}function Id(e,t){if(!e)return"—";if(t.scopeLabels[e])return t.scopeLabels[e];for(const n of t.scopeGroups){const r=n.scopes.find(i=>i.scope_id===e);if(r)return`${Nh(r,n.scopes)} · ${n.label}`}return"Unknown Space"}function cI(e,t){return e?t.scopeGroups.some(n=>n.scopes.some(r=>r.scope_id===e)):!1}function lI(e,t,n){for(const r of[t,e.suggested_scope_id,e.resolved_scope_id])if(cI(r,n))return r??"";return e.resolved_scope_id||""}function dI(e,t){return kd(e)?"From other devices":Id(e.resolved_scope_id,t)}function bz(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 _z(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 Th(e){return(e.guardrail_warnings??[]).filter(t=>t.severity==="warning").length}function wz(e){const t=[];return(Th(e)>0||e.statuses.includes("needs_attention"))&&t.push({label:"Needs attention",tone:"badge-offline"}),e.statuses.includes("suggested")&&t.push({label:"Suggested"}),e.statuses.includes("legacy_review")&&t.push({label:"Older shared data",tone:"badge-offline"}),kd(e)&&t.push({label:"From another device"}),e.identity_source==="unmapped"&&t.push({label:"No stable identity",tone:"badge-offline"}),t}function Sz(e,t){return[["Workspace identity",e.workspace_identity],["Repository identity",e.repository_identity],["Project",e.project],["Project match source",sI(e.identity_source)],["Recorded workspace path",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",dI(e,t)],["Suggested Space",e.suggested_scope_id?Id(e.suggested_scope_id,t):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Recorded sessions",e.session_count],["Active memories",e.memory_count??"count unavailable"],["Latest recorded session",e.latest_session_at?Ph(e.latest_session_at):"Unknown"]]}function Cz({code:e}){return a("strong",{children:[{basename_collision_review:"Name collision",broad_org_domain_pattern:"Broad mapping",home_directory_org_domain_pattern:"Broad mapping",scope_reassignment_old_copies:"Previous copies",unknown_project_local_only:"Current behavior"}[e]??"Review item",": "]})}function kz({model:e}){const{project:t}=e;return t.sharing?.length?a("div",{className:"settings-note project-sharing-summary",children:[a("strong",{children:"Project sharing"}),a("ul",{"aria-label":`People sharing ${t.display_project}`,children:t.sharing.map(n=>a("li",{children:[a("strong",{children:_z(n)})," — ",n.lifecycle.label,"."," ",n.lifecycle.explanation]},n.person.actor_id))})]}):null}function Iz({model:e}){const t=e.project.worktrees??[];return t.length<2?null:a("div",{className:"settings-note",children:[a("strong",{children:"Worktrees"}),a("ul",{"aria-label":`Worktrees for ${e.project.display_project}`,children:t.map(n=>a("li",{children:n.cwd},n.cwd))})]})}function Rz({model:e,view:t}){const{project:n}=e,r=kd(n),i=(n.guardrail_warnings??[]).filter(o=>o.severity==="warning");return a(U,{children:[a("div",{className:"project-inventory-domain",children:dI(n,t)}),a("div",{className:"project-inventory-meta",children:[r?"source-owned project":bz(n.resolution_reason)," ·"," ","Project match source: ",sI(n.identity_source)," · Latest recorded session: ",n.latest_session_at?Ph(n.latest_session_at):"Unknown"]}),a("div",{className:"settings-note",children:"Projects can appear from recorded sessions or saved mappings even with no active memories. A project name alone does not identify who created it or why it was recorded."}),a(kz,{model:e}),a(Iz,{model:e}),r?a("div",{className:"settings-note",children:"Read-only here. Change it on the source device."}):null,n.identity_source==="unmapped"?a("div",{className:"settings-note",children:"Stays on this device until it has a path, git remote, or workspace id."}):null,n.suggested_scope_id&&n.suggested_scope_id!==n.resolved_scope_id?a("div",{className:"settings-note project-suggestion-note",children:n.suggestion_reason?`Suggestion: ${n.suggestion_reason}`:`Suggestion: assign this project to ${Id(n.suggested_scope_id,t)}.`}):null,i.length>0?a("div",{className:"settings-note project-attention-note",children:["Needs attention: ",i.map(o=>o.message).join(" ")]}):null,a("dl",{className:"project-detail-grid",children:Sz(n,t).map(([o,s])=>a("div",{className:"project-detail-pair",children:[a("dt",{children:o}),a("dd",{children:s==null||s===""?"—":String(s)})]},o))})]})}function Pz(e){const{callbacks:t,currentAssignable:n,model:r,scopeId:i,selectRef:o,setScopeId:s,view:c}=e,{project:l}=r,d=Cd("project-domain",r.key),u=!i||i===l.resolved_scope_id&&!n,f=l.suggested_scope_id&&i===l.suggested_scope_id?"Confirm suggestion":"Save Space";return a(U,{children:[a("label",{className:"sr-only",htmlFor:d,children:["Space for ",l.display_project]}),a(Pn,{className:"project-domain-select",id:d,onBlur:t.onSpaceSelectBlur,onChange:p=>{s(p.currentTarget.value),t.setProjectScopeDraft(l.workspace_identity,p.currentTarget.value)},ref:o,value:i,children:[!n&&l.resolved_scope_id?a("option",{disabled:!0,value:l.resolved_scope_id,children:[Id(l.resolved_scope_id,c)," — not assignable"]}):null,c.scopeGroups.map(p=>a("optgroup",{label:p.label,children:p.scopes.map(m=>a("option",{value:m.scope_id,children:Nh(m,p.scopes)},m.scope_id))},p.key))]}),a("button",{className:"settings-button",disabled:u,onClick:()=>{t.saveProjectScope(l.workspace_identity,i)},type:"button",children:f})]})}function Nz({callbacks:e,model:t}){const{project:n}=t;return a(U,{children:[a("button",{className:"settings-button",onClick:()=>{e.keepProjectLocal(n.workspace_identity)},type:"button",children:"Keep local-only"}),a("button",{className:"settings-button",disabled:n.mapping_id==null||n.resolution_reason!=="exact_mapping",onClick:()=>{e.removeProjectScope(n.workspace_identity)},type:"button",children:"Remove mapping"}),a("button",{className:"settings-button",disabled:n.session_count===0,title:n.session_count===0?"No sessions are available to reassign for this saved mapping.":void 0,onClick:()=>{e.reassignProject(n.workspace_identity)},type:"button",children:"Change project…"}),a("button",{className:"settings-button danger",disabled:(n.memory_count??0)===0,onClick:()=>{e.forgetProject(n.workspace_identity)},type:"button",children:"Forget local memories…"})]})}function Tz({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingConfirmation;return r?a("div",{className:"settings-note project-guardrail-confirmation project-space-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirmation required before saving this Space."}),a("p",{children:"Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save."}),a("ul",{children:r.warnings.map(i=>a("li",{children:[a(Cz,{code:i.code}),a("span",{children:i.message})]},`${i.code}:${i.message}`))}),a("button",{className:"settings-button",onClick:()=>{e.confirmProjectScope(n.project.workspace_identity)},ref:t,type:"button",children:"I understand, save Space"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectScopeConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]}):null}function Az({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingForgetConfirmation;if(!r)return null;const i=r.localOwnedMemoryCount===1?"memory":"memories",o=r.peerOwnedMemoryCount===1?"memory":"memories";return a("div",{className:"settings-note project-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirm project memory cleanup."}),a("p",{children:[r.localOwnedMemoryCount.toLocaleString()," locally owned ",i," will be forgotten. ",r.peerOwnedMemoryCount.toLocaleString()," peer-owned ",o," will be left unchanged."]}),a("p",{children:"Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device."}),a("button",{className:"settings-button danger",onClick:()=>{e.forgetProject(n.project.workspace_identity,{confirmed:!0})},ref:t,type:"button",children:"I understand, forget local memories"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectForgetConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]})}function Ez(e){const{callbacks:t,model:n,view:r}=e,{project:i}=n,o=Ko(i),s=o&&i.memory_count!=null&&!i.guardrail_warnings.some(c=>c.requires_confirmation);return a("div",{className:"project-inventory-actions",children:[s?a("button",{className:"settings-button",disabled:!r.shareInventoryReady,onClick:()=>t.shareProject(i.workspace_identity),title:r.shareInventoryReady?void 0:"The complete project list is unavailable.",type:"button",children:"Share"}):null,o?a(U,{children:[a(Pz,{...e}),a(Nz,{callbacks:t,model:n}),a(Tz,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n}),a(Az,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n})]}):null]})}function xz(e){const{model:t,onOpenChange:n,open:r,view:i}=e,{project:o}=t,s=Ko(o),[c,l]=R(()=>lI(o,t.draftScopeId,i));q(()=>{l(lI(o,t.draftScopeId,i))},[t.draftScopeId,o,i]);const d=i.scopeGroups.some(u=>u.scopes.some(f=>f.scope_id===o.resolved_scope_id));return a("tr",{className:"project-inventory-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:u=>n(u.currentTarget.open),open:r,children:[a("summary",{"data-project-focus-key":`admin:${s}:${o.workspace_identity}`,children:[a("span",{children:"Details"}),Th(o)>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",Th(o)]}):null]}),a("div",{className:"project-inventory-details-body",children:[a(Rz,{model:t,view:i}),a(Ez,{...e,currentAssignable:d,scopeId:c,setScopeId:l})]})]})})})}function Dz(e){const t=[{disabled:!e.canAssign,label:"Space assignment…",onSelect:e.onOpenSpaceAssignment},{disabled:!e.canChangeProject,label:"Change project…",onSelect:e.onChangeProject},{disabled:!e.canAssign,label:"Keep local-only",onSelect:e.onKeepLocal},...e.canRemoveMapping?[{label:"Remove mapping",onSelect:e.onRemoveMapping}]:[],{danger:!0,disabled:!e.canForget,label:"Forget local memories…",onSelect:e.onForget}];return a("div",{className:"project-row-menu",children:a(Vl,{actions:t,label:`More actions for ${e.label}`})})}function jz({label:e,onOpenSpaceAssignment:t}){return a("div",{className:"project-row-menu",children:a(Vl,{actions:[{label:"Space assignment for all…",onSelect:t}],label:`More actions for ${e}`})})}function Oz(e){return e.coveredProjectCount==null||e.knownProjectCount==null?" · Coverage unavailable":` · ${e.coveredProjectCount} of ${e.knownProjectCount} known Project entries`}function uI({available:e,cluster:t=!1,recipients:n}){if(!e)return a("span",{className:"project-recipient-status tertiary",children:"Unavailable"});if(n.length===0)return a("span",{className:"project-recipient-status tertiary",children:"No Teams or Identities added"});const r=t?n:n.slice(0,2),i=n.length-r.length,o=t&&n.some(c=>c.coveredProjectCount!==c.knownProjectCount);let s="Sharing across known entries";return o&&(s="Different sharing across entries"),n.some(c=>c.coveredProjectCount==null||c.knownProjectCount==null)&&(s="Coverage unavailable"),a("div",{className:"project-recipient-summary",children:[a("ul",{"aria-label":"Active recipients",className:"project-recipient-chips",children:[r.map(c=>a("li",{className:`project-recipient-chip project-recipient-chip-${c.kind.toLowerCase()}`,children:[c.kind,": ",c.displayName,t?Oz(c):""]},c.key)),i>0?a("li",{className:"project-recipient-chip",children:["+",i]}):null]}),t?a("span",{className:"project-recipient-status",children:s}):null]})}function Lz({model:e,view:t}){const{project:n}=e;return a(U,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:(n.memory_count??0).toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:n.session_count.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:Ph(n.latest_session_at)}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(uI,{available:t.recipientPolicyReady,recipients:e.recipients})})]})}function $z({callbacks:e,model:t,onOpenDetails:n,view:r}){const{project:i}=t;return!Ko(i)&&!t.manageable?a("td",{className:"project-inventory-cell project-inventory-row-actions"}):a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.manageable?a("button",{"aria-label":`Update sharing for ${i.display_project}`,className:"settings-button project-recipient-action project-selection-target","data-project-focus-key":`manage:${i.workspace_identity}`,disabled:!r.selection.ready,onClick:()=>e.manageRecipients([i.workspace_identity]),type:"button",children:"Update sharing"}):null,Ko(i)?a(Dz,{canAssign:!0,canChangeProject:i.session_count>0,canForget:(i.memory_count??0)>0,canRemoveMapping:i.mapping_id!=null&&i.resolution_reason==="exact_mapping",label:i.display_project,onChangeProject:()=>{e.reassignProject(i.workspace_identity)},onForget:()=>{e.forgetProject(i.workspace_identity)},onKeepLocal:()=>{e.keepProjectLocal(i.workspace_identity)},onOpenSpaceAssignment:n,onRemoveMapping:()=>{e.removeProjectScope(i.workspace_identity)}}):null]})}function Mz(e){const{callbacks:t,child:n,model:r,titleId:i,view:o}=e,{project:s}=r,c=yz(s);return a("tr",{className:`project-inventory-row-header project-inventory-table-row${n?" project-inventory-child-row":""}`,children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:r.manageable?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select ${s.display_project} for recipient sharing`,checked:r.selected,className:"project-selection-checkbox","data-project-focus-key":`select:${s.workspace_identity}`,onChange:()=>t.toggleSelection([s.workspace_identity]),type:"checkbox"}),a("span",{className:"sr-only",children:["Select ",s.display_project," for recipient sharing"]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:i,children:s.display_project}),c?a("span",{className:"project-inventory-signal mono small tertiary",children:c}):null,a("div",{className:"project-inventory-badges",children:wz(s).map(l=>a(Ne,{tone:l.tone,variant:"badge",children:l.label},l.label))})]}),a(Lz,{model:r,view:o}),a($z,{...e})]})}function pI({callbacks:e,child:t=!1,clusterKey:n,model:r,view:i}){const{project:o}=r,[s,c]=R(r.detailsOpen),l=x(null),d=x(null),u=g=>{c(g),e.setProjectDetailsOpen(r.detailKey,g)};q(()=>{r.detailsOpen&&c(!0)},[r.detailsOpen]);const f=!!(r.pendingConfirmation||r.pendingForgetConfirmation);q(()=>{f&&(u(!0),queueMicrotask(()=>d.current?.focus()))},[f]);const p=()=>{u(!0),queueMicrotask(()=>l.current?.focus())},m=Cd("project-title",r.detailKey);return a("tbody",{"aria-labelledby":m,className:`project-inventory-row${t?" project-inventory-child":""}`,"data-project-cluster-key":n,"data-project-repairable":String(Ko(o)),"data-project-workspace-identity":o.workspace_identity,children:[a(Mz,{callbacks:e,child:t,model:r,onOpenDetails:p,titleId:m,view:i}),a(xz,{callbacks:e,confirmationActionRef:d,model:r,onOpenChange:u,open:s,selectRef:l,view:i})]})}function Fz(e){const t=e.projects.filter(o=>Ko(o.project)),n=t.flatMap(o=>(o.project.guardrail_warnings??[]).filter(s=>s.requires_confirmation).map(s=>({project:o,warning:s}))),r=new Set(t.map(o=>o.project.suggested_scope_id).filter(o=>!!o)),i=new Set(t.map(o=>o.project.resolved_scope_id));return{assignable:t,blocking:n,hasMixed:r.size>1||i.size>1,memoryCount:e.projects.reduce((o,s)=>o+(s.project.memory_count??0),0),sessionCount:e.projects.reduce((o,s)=>o+s.project.session_count,0),warningTotal:e.projects.reduce((o,s)=>o+(s.project.guardrail_warnings??[]).filter(c=>c.severity==="warning").length,0)}}function Bz(e){const t=x(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedProjectIds.length>0&&e.selectedProjectIds.length<e.projectIds.length)},[e.projectIds.length,e.selectedProjectIds.length]),t}function qz({model:e,summary:t,view:n}){return a(U,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:t.memoryCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:t.sessionCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:"—"}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(uI,{available:n.recipientPolicyReady,cluster:!0,recipients:e.recipients})})]})}function Uz({callbacks:e,model:t,onOpenAssignment:n,summary:r,view:i}){return a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.projectIds.length>0?a("button",{"aria-label":`Manage sharing for ${t.label}`,className:"settings-button project-recipient-action project-selection-target",disabled:!i.selection.ready,onClick:()=>e.manageRecipients(t.projectIds),type:"button",children:"Manage sharing"}):null,r.assignable.length>0?a(jz,{label:t.label,onOpenSpaceAssignment:n}):null]})}function Gz(e){const{callbacks:t,model:n,onToggleWorktrees:r,summary:i,titleId:o,worktreesOpen:s}=e,c=Bz(n),l=e.view.rows.filter(f=>f.kind==="cluster"&&f.label===n.label),d=l.length>1?` (group ${l.findIndex(f=>f.key===n.key)+1} of ${l.length})`:"",u=n.projectIds.length>0&&n.selectedProjectIds.length===n.projectIds.length;return a("tr",{className:"project-inventory-row-header project-inventory-table-row",children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:n.projectIds.length>0?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select all Project entries for ${n.label}`,checked:u,className:"project-selection-checkbox",onChange:()=>t.toggleSelection(n.projectIds),ref:c,type:"checkbox"}),a("span",{className:"sr-only",children:["Select all Project entries for ",n.label]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:o,children:n.label}),a("div",{className:"project-inventory-badges",children:[a(Ne,{variant:"badge",children:[n.projects.length," Project entries"]}),a("button",{"aria-controls":e.entriesId,"aria-expanded":s,"aria-label":`${s?"Hide":"Show"} entries for ${n.label}${d}`,className:"settings-button project-worktrees-toggle",onClick:f=>{s&&f.currentTarget.focus(),r()},type:"button",children:s?"Hide entries":"Show entries"}),i.warningTotal>0?a(Ne,{tone:"badge-offline",variant:"badge",children:["Needs attention · ",i.warningTotal]}):null]})]}),a(qz,{...e}),a(Uz,{...e})]})}function Hz(e){const{callbacks:t,model:n,scopeId:r,selectRef:i,setScopeId:o,summary:s,view:c}=e;if(s.assignable.length===0){const d=n.projects.every(u=>u.project.read_only)?"These Project entries were received from other devices. Change Project or Space assignments on their source devices.":"These Project entries cannot be bulk assigned until they have stable local identities. Expand each entry for details.";return a("div",{className:"settings-note",children:d})}const l=cI(r,c);return a(U,{children:[a(Pn,{"aria-label":`Space for ${n.label} group`,className:"project-domain-select",onBlur:t.onSpaceSelectBlur,onChange:d=>{o(d.currentTarget.value),t.setClusterScopeDraft(n.key,d.currentTarget.value)},ref:i,value:r,children:[a("option",{value:"",children:"Choose Space…"}),c.scopeGroups.map(d=>a("optgroup",{label:d.label,children:d.scopes.map(u=>a("option",{value:u.scope_id,children:Nh(u,d.scopes)},u.scope_id))},d.key))]}),a("button",{className:"settings-button",disabled:!l||s.blocking.length>0,onClick:()=>{t.saveClusterScope(n.key,r)},type:"button",children:["Save Space for ",s.assignable.length," ",s.assignable.length===1?"Project entry":"Project entries"]})]})}function Vz({summary:e,onReviewEntries:t,entriesId:n}){return e.blocking.length>0?a("div",{className:"settings-note project-attention-note",children:[a("strong",{children:"Project match needs review."})," One or more Project entries need individual review before bulk assignment. Review the remote or recorded path before assigning a Space.",a("button",{"aria-controls":n,className:"settings-button project-review-entries",onClick:t,type:"button",children:"Review entries"})]}):e.hasMixed?a("div",{className:"settings-note project-attention-note",children:"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment."}):null}function Kz(e){const{onOpenChange:t,open:n,summary:r}=e;return a("tr",{className:"project-inventory-details-row project-inventory-cluster-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:i=>t(i.currentTarget.open),open:n,children:[a("summary",{children:[a("span",{children:"Advanced Space assignment"}),r.warningTotal>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",r.warningTotal]}):null]}),a("div",{className:"project-inventory-details-body",children:a("div",{className:"project-inventory-actions",children:[a(Hz,{...e}),a(Vz,{...e})]})})]})})})}function Wz({callbacks:e,model:t,view:n,entriesId:r,regionRef:i,summary:o}){return a("tr",{className:"project-cluster-entries-row",hidden:!t.worktreesOpen,children:a("td",{colSpan:7,children:a("section",{"aria-label":`Project entries for ${t.label}`,className:"project-cluster-entries",id:r,ref:i,tabIndex:-1,children:[a("table",{className:"project-inventory-table project-entries-table",children:[a("caption",{className:"sr-only",children:["Project entries for ",t.label]}),a("thead",{className:"sr-only",children:a("tr",{children:["Select","Project entry","Memories","Sessions","Last activity","Shared with","Actions"].map(s=>a("th",{scope:"col",children:s},s))})}),t.worktreesOpen?t.projects.map(s=>a(pI,{callbacks:e,child:!0,clusterKey:t.key,model:s,view:n},`${s.project.read_only?"received":"local"}:${s.key}`)):null]}),o.blocking.length>0?a("details",{className:"project-entry-review-details",children:[a("summary",{children:["Project matches needing review · ",o.blocking.length]}),a("ul",{children:o.blocking.map(({project:s,warning:c})=>a("li",{children:[a("strong",{children:["Project entry: ",s.project.workspace_identity]})," —"," ",c.message]},`${s.key}:${c.code}`))})]}):null]})})})}function zz(e){const{callbacks:t,model:n}=e,[r,i]=R(n.detailsOpen),[o,s]=R(n.draftScopeId??""),c=x(null),l=x(null);q(()=>{n.detailsOpen&&i(!0)},[n.detailsOpen]),q(()=>s(n.draftScopeId??""),[n.draftScopeId]);const d=Fz(n),u=b=>{i(b),t.setClusterDetailsOpen(n.key,b)},f=()=>{u(!0),queueMicrotask(()=>c.current?.focus())},p=Cd("project-cluster-title",n.key),m=Cd("project-cluster-entries",n.key),g=()=>{t.setClusterWorktreesOpen(n.key,!0),queueMicrotask(()=>l.current?.focus())};return a("tbody",{"aria-labelledby":p,className:"project-inventory-row project-inventory-cluster","data-project-cluster-key":n.key,children:[a(Gz,{...e,entriesId:m,onOpenAssignment:f,onToggleWorktrees:()=>t.setClusterWorktreesOpen(n.key,!n.worktreesOpen),summary:d,titleId:p,worktreesOpen:n.worktreesOpen}),a(Wz,{...e,entriesId:m,regionRef:l,summary:d}),a(Kz,{...e,entriesId:m,onReviewEntries:g,onOpenChange:u,open:r,scopeId:o,selectRef:c,setScopeId:s,summary:d})]})}function Jz({callbacks:e,error:t,view:n}){return t?a("div",{className:"settings-note",role:"status",children:t}):n.rows.length===0?a("div",{className:"settings-note",children:"No matching projects"}):a("table",{className:"project-inventory-table",children:[a("caption",{className:"sr-only",children:"Projects"}),a("thead",{children:a("tr",{className:"project-inventory-table-header project-inventory-table-row",children:[a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Select"})}),a("th",{scope:"col",children:"Project"}),a("th",{scope:"col",children:"Memories"}),a("th",{scope:"col",children:"Sessions"}),a("th",{scope:"col",children:"Last activity"}),a("th",{scope:"col",children:"Shared with"}),a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Actions"})})]})}),n.rows.map(r=>r.kind==="cluster"?a(zz,{callbacks:e,model:r,view:n},r.key):a(pI,{callbacks:e,model:r,view:n},r.detailKey))]})}function Yz(e,t,n,r){ke(a(Jz,{callbacks:n,error:r,view:t}),e)}function Xz(e){if(e?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement)return document.activeElement.dataset.teamSetupCandidateRef}function Qz(e,t,n){if(t){for(const r of e.querySelectorAll("button"))if(r.dataset.teamSetupCandidateRef===t){r.focus();return}n()}}function Zz(e,t){const n=document.createElement("div");n.className="project-inventory-actions";const r=document.createElement("strong");if(r.textContent=e.displayName,n.appendChild(r),!t)return n;const i=document.createElement("button");return i.setAttribute("aria-label",`Finish setting up ${e.displayName}`),i.className="settings-button",i.type="button",i.textContent="Finish setting up this Team",i.dataset.teamSetupCandidateRef=e.candidateRef,i.addEventListener("click",()=>t(e.candidateRef)),n.appendChild(i),n}function e4(e,t){const n=document.createElement("section");n.className="card project-team-setup-entry",n.dataset.teamSetupSignature=JSON.stringify(e.candidates.map(o=>[o.candidateRef,o.displayName]));const r=document.createElement("h2");r.textContent="Finish setting up this Team";const i=document.createElement("p");i.className="section-meta",i.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",n.append(r,i);for(const o of e.candidates)n.appendChild(Zz(o,t.onOpenTeamSetup));return n}function t4(e,t,n){const r=t?.candidates??[],i=e.querySelector(":scope > .project-team-setup-entry");i?.querySelector(".project-team-setup-status")?.remove();const o=Xz(i);if(r.length===0){i?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,o&&n.onFocusFallback();return}if(!t)return;const s=JSON.stringify(r.map(l=>[l.candidateRef,l.displayName]));if(i?.dataset.teamSetupSignature===s){e.hidden=!1;return}i?.remove(),e.hidden=!1;const c=e4(t,n);e.appendChild(c),Qz(c,o,n.onFocusFallback)}function fI(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}var mr=new Set,Rd=new Set,Ts=new EventTarget,As=new Set,mI=100,xt="";function Wo(e,t,n){n?e.add(t):e.delete(t),Ts.dispatchEvent(new Event("change"))}function hI(e,t){const[n,r]=R(e.has(t));return q(()=>{const i=()=>r(e.has(t));return Ts.addEventListener("change",i),i(),()=>Ts.removeEventListener("change",i)},[e,t]),n}function n4(){const[e,t]=R(()=>new Set(mr));return q(()=>{const n=()=>t(new Set(mr));return Ts.addEventListener("change",n),n(),()=>Ts.removeEventListener("change",n)},[]),e}function r4(e){const t=new Map;for(const n of e){const r=`${n.projectGroup.identity}\0${n.conditionCode}`,i=t.get(r);if(i){i.items.push(n);continue}t.set(r,{key:r,displayName:n.projectGroup.displayName,items:[n]})}return[...t.values()]}function gI(e,t){return e.options.find(n=>n.decision===t)}function i4(e){const t=e.items[0];if(Li(e,t.recommendedDecision))return"Choose a review response";const n=gI(t,t.recommendedDecision);return n?vI(n):t.recommendedDecision.replaceAll("_"," ")}function vI(e){switch(e.decision){case"apply_recommendation":return"Acknowledge local Identity suggestion";case"keep_project_local":return"Record local preference (access unchanged)";case"reject_suggestion":return"Dismiss suggestion (setup unchanged)";default:return e.label}}function yI(e){return[...new Map(e.map(t=>[t.id,t.label])).values()]}function Ah(e,t){return e.items.flatMap(n=>{const r=gI(n,t);return r?[r]:[]})}function o4(e){const t=new Map;for(const n of e)for(const r of n.preview.projects){const i=t.get(r.canonicalIdentity)??0;t.set(r.canonicalIdentity,Math.max(i,n.preview.affectedMemoryCount))}return[...t.values()].reduce((n,r)=>n+r,0)}function bI(e){const t=yI(e.flatMap(n=>n.preview.projects.map(r=>({id:r.canonicalIdentity,label:`${r.displayName} — ${r.canonicalIdentity}`}))));return{devices:yI(e.flatMap(n=>n.preview.effectiveDevices.map(r=>({id:r.deviceId,label:`${r.displayName} (${r.assignment})`})))),memoryCount:o4(e),projects:t}}function Hr(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function a4(e){return e==="unassigned_effective_device"?"Set up Identity or devices first":"Choose recipients first (Update sharing, below)"}async function s4(e){try{return await yT(e),{stale:!1,failed:!1}}catch(t){if(!(t instanceof ev))throw t;return As.add(e.reviewItemId),{stale:!0,failed:!1}}}function c4(e,t){if(t.status==="stale"){As.add(t.reviewItemId),e.stale=!0;return}t.status!=="applied"&&(e.failed=!0)}async function _I(e){const t={failed:!1,stale:!1};for(let n=0;n<e.length;n+=mI){const r=e.slice(n,n+mI),i=await bT(r);for(const o of i.results)c4(t,o)}return t}async function l4(e,t){const n=wI(e,t),r=n[0];return n.length===1&&r?s4(r):_I(n)}function wI(e,t){return e.items.map(n=>({decision:t,reviewItemId:n.reviewItemId,sourceFingerprint:n.sourceFingerprint}))}function d4(e,t){if(t.failed)return"Some items did not update. Try again.";if(t.stale)return"Changed since loaded. Check the refreshed choices.";for(const n of e.items)As.delete(n.reviewItemId);return"Applied"}function Pd(e,t){return e instanceof Error?e.message:t}function Li(e,t){const n=Ah(e,t);return n.length!==e.items.length||n.some(r=>r.preview.requiresDecisionInput)}function u4({options:e}){const{devices:t,memoryCount:n,projects:r}=bI(e);return a("div",{className:"recipient-policy-preview",children:[a("strong",{children:["Review context: ",Hr(r.length,"Project")," ·"," ",Hr(n,"memory","memories")," · ",Hr(t.length,"device")]}),a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Projects and paths"}),a("ul",{children:r.map(i=>a("li",{children:i},i))})]}),t.length>0?a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Devices"}),a("ul",{children:t.map(i=>a("li",{children:i},i))})]}):null]})}async function SI(e,t){try{await e.onRefresh?.()}catch(n){const r=Pd(n,"Unable to refresh review items.");xt=`${xt} Refresh failed: ${r}`,t(xt)}}function p4(e,t,n,r){const i=hI(mr,e.key);async function o(){const s=t.current;if(!(i||Li(e,s)||mr.has(e.key))){Wo(mr,e.key,!0),xt="Applying…",n(xt);try{try{xt=d4(e,await l4(e,s))}catch(c){xt=Pd(c,"Unable to apply decision. Try again.")}n(xt),await SI(r,n)}finally{Wo(mr,e.key,!1)}}}return{apply:o,pending:i}}function f4(e){const t=e.items[0],n=bI(Ah(e,t.recommendedDecision)),r=[`Suggested: ${i4(e)}`,Hr(n.memoryCount,"memory","memories"),Hr(n.devices.length,"device")];return e.items.length>1&&r.push(Hr(e.items.length,"worktree")),r.join(" · ")}function m4({blocked:e,group:t,onSelectedChange:n,pending:r,selected:i,stale:o}){const s=t.items[0],c=`Select ${t.displayName}: ${s.finding} (${s.projectGroup.identity})`;return a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("label",{className:"recipient-policy-review-selection",children:a("input",{"aria-label":c,checked:i,disabled:r||e,onChange:l=>n(l.currentTarget.checked),type:"checkbox"})}),a("strong",{children:t.displayName}),s.projectGroup.identity!==t.displayName?a("span",{className:"mono small recipient-policy-review-identity",children:s.projectGroup.identity}):null]}),a("div",{className:"small recipient-policy-review-meta",children:[s.conditionCode==="suggest_local_identity"?"Optional review · No action needed · ":null,f4(t),o?a(Ne,{variant:"badge",tone:"badge-offline",children:"Changed since loaded"}):null]})]})}function h4(e){return a(U,{children:[a(Pn,{"aria-label":`Review decision for ${e.group.displayName}`,className:"recipient-policy-review-select","data-review-control":"decision",disabled:e.pending,onChange:t=>e.onDecisionChange(t.currentTarget.value),value:e.blocked?"":e.decision,children:[e.blocked?a("option",{disabled:!0,value:"",children:"Choose a review response"}):null,e.group.items[0].options.filter(t=>!Li(e.group,t.decision)).map(t=>a("option",{value:t.decision,children:vI(t)},t.decision))]}),a("div",{className:"recipient-policy-review-actions",children:[a("button",{className:"settings-save","data-review-control":"apply",disabled:e.pending||e.blocked,onClick:e.onApply,ref:e.applyButtonRef,type:"button",children:e.pending?"Applying…":"Apply"}),a("button",{"aria-controls":e.detailsId,"aria-expanded":e.detailsOpen,className:"settings-button",onClick:e.onDetailsToggle,type:"button",children:"Review this suggestion"})]})]})}function g4({detailsId:e,group:t,open:n,requiresInput:r,selected:i,stale:o}){const s=t.items[0];return a("div",{className:"settings-note recipient-policy-review-details",hidden:!n,id:e,children:[a("div",{children:[s.finding," — ",s.reason]}),o?a("div",{children:"Changed since loaded. Check the refreshed choices."}):null,a("div",{className:"recipient-policy-deferred",hidden:!r,children:a4(s.conditionCode)}),a(u4,{options:i})]})}function v4({decision:e,group:t,onDecisionChange:n,onSelectedChange:r,onStatus:i,options:o,selected:s}){const c=`recipient-policy-details-${ht()}`,[l,d]=R(!1),u=x(e),f=x(null);u.current=e;const p=Ah(t,e),{apply:m,pending:g}=p4(t,u,i,o),b=Li(t,e),_=p.some(S=>S.preview.requiresDecisionInput),v=t.items.some(S=>As.has(S.reviewItemId));return a("article",{className:"recipient-policy-review-item","data-review-group":t.key,children:[a(m4,{blocked:b,group:t,onSelectedChange:r,pending:g,selected:s,stale:v}),a(h4,{applyButtonRef:f,blocked:b,decision:e,detailsId:c,detailsOpen:l,group:t,onApply:()=>{m()},onDecisionChange:S=>{u.current=S,f.current&&(f.current.disabled=Li(t,S)),n(S)},onDetailsToggle:()=>d(S=>!S),pending:g}),a("div",{className:"settings-note recipient-policy-review-details",children:"Apply records the selected review decision only. It does not grant or revoke access, assign an Identity, or change project mappings. Doing nothing preserves your current setup. To change recipients, use Update sharing in the project list below. For Identity or device setup, open Devices."}),a(g4,{detailsId:c,group:t,open:l,requiresInput:_,selected:p,stale:v})]})}function y4(e){const t=x(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedCount>0&&!e.allSelected)},[e.allSelected,e.selectedCount]),a("div",{className:"recipient-policy-review-bulk",children:[a("label",{className:"recipient-policy-review-select-all",children:[a("input",{"aria-label":"Select all ready review decisions",checked:e.allSelected,disabled:e.applying||e.actionableCount===0,onChange:n=>e.onSelectAll(n.currentTarget.checked),ref:t,type:"checkbox"}),a("span",{children:"Select all ready decisions"})]}),a("span",{className:"small recipient-policy-review-selection-count",children:[e.selectedCount," selected · ",e.actionableCount," ready to record"]}),a("div",{className:"recipient-policy-review-bulk-actions",children:[a("button",{className:"settings-button",disabled:e.applying||e.applySelectedBlocked||e.selectedCount===0,onClick:e.onApplySelected,type:"button",children:e.applying?"Applying…":`Apply selected (${e.selectedCount})`}),a("button",{className:"settings-save",disabled:e.applying||e.applyAllBlocked||e.actionableCount===0,onClick:e.onApplyAll,type:"button",children:e.applying?"Applying…":`Apply all (${e.actionableCount})`})]})]})}function b4(e){return Object.fromEntries(e.map(t=>[t.key,t.items[0].recommendedDecision]))}function _4(e,t){if(t.failed)return"Some decisions did not update. Check the refreshed list and try again.";if(t.stale)return"Some decisions changed since loaded. Check the refreshed choices.";for(const n of e)for(const r of n.items)As.delete(r.reviewItemId);return`Applied ${Hr(e.length,"decision")}`}async function w4(e,t){return _I(e.flatMap(n=>wI(n,t[n.key]??n.items[0].recommendedDecision)))}function S4({item:e,options:t}){const n=`recipient-policy-blocked-details-${ht()}`,r=`recipient-policy-repair-help-${ht()}`,[i,o]=R(!1),s=hI(Rd,e.blockedItemId),c=!!(t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0));async function l(){if(!(!t.onRepair||Rd.has(e.blockedItemId))){Wo(Rd,e.blockedItemId,!0);try{await t.onRepair(e.repair)}finally{Wo(Rd,e.blockedItemId,!1)}}}return a("article",{className:"recipient-policy-review-item recipient-policy-blocked-item",children:[a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("strong",{children:e.finding}),a(Ne,{variant:"badge",tone:"badge-offline",children:"Blocked"})]}),a("div",{className:"small recipient-policy-review-meta",children:["Owner: ",e.ownerLabel]})]}),a("div",{"aria-hidden":"true"}),a("div",{className:"recipient-policy-review-actions",children:[c?a("button",{"aria-describedby":r,className:"settings-button",disabled:s,onClick:()=>{l()},type:"button",children:e.repair.label}):a("span",{className:"small",children:"Repair in Projects"}),a("button",{"aria-controls":n,"aria-expanded":i,className:"settings-button",onClick:()=>o(d=>!d),type:"button",children:"Details"})]}),a("div",{className:"settings-note recipient-policy-review-details",hidden:!i,id:n,children:[a("div",{children:e.reason}),a("div",{id:r,children:e.repairAction})]})]})}function C4(e){const[t,n]=R(()=>b4(e)),r=x(t),[i,o]=R(()=>new Set),s=m=>t[m.key]??m.items[0].recommendedDecision,c=e.filter(m=>!Li(m,s(m))),l=c.filter(m=>i.has(m.key));function d(m,g){r.current={...r.current,[m.key]:g},n(r.current),Li(m,g)&&u(m.key,!1)}function u(m,g){o(b=>{const _=new Set(b);return g?_.add(m):_.delete(m),_})}function f(m){o(m?new Set(c.map(g=>g.key)):new Set)}function p(m){o(g=>{const b=new Set(g);for(const _ of m)b.delete(_.key);return b})}return{actionableGroups:c,allSelected:c.length>0&&l.length===c.length,clearSelected:p,decisionFor:s,decisionsRef:r,selectAll:f,selectedGroups:l,selectedKeys:i,setDecision:d,setGroupSelected:u}}function k4(e,t,n,r){const[i,o]=R(!1),s=x(!1);async function c(l){if(!(s.current||l.length===0||l.some(d=>mr.has(d.key)))){s.current=!0,o(!0);for(const d of l)Wo(mr,d.key,!0);xt=`Applying ${Hr(l.length,"decision")}…`,n(xt);try{try{const d=await w4(l,e.current);xt=_4(l,d),!d.failed&&!d.stale&&r(l)}catch(d){xt=Pd(d,"Unable to apply decisions. Try again.")}n(xt),await SI(t,n)}finally{for(const d of l)Wo(mr,d.key,!1);s.current=!1,o(!1)}}}return{apply:c,applying:i}}function I4({options:e,review:t}){const n=r4(t.reviewItems),[r,i]=R(xt),o=C4(n),s=n4(),c=k4(o.decisionsRef,e,i,o.clearSelected);return a("section",{className:"card recipient-policy-review","aria-labelledby":"recipientPolicyReviewTitle",children:[a("div",{className:"recipient-policy-review-header",children:[a("h2",{id:"recipientPolicyReviewTitle",children:["Sharing review ",a("span",{className:"recipient-policy-review-count",children:n.length})]}),a(Ne,{variant:"badge",tone:"badge-offline",children:"Not recorded"})]}),a("div",{className:"section-meta recipient-policy-review-status",role:"status","aria-live":"polite",children:r}),n.length>0?a(U,{children:[a(y4,{actionableCount:o.actionableGroups.length,allSelected:o.allSelected,applyAllBlocked:o.actionableGroups.some(l=>s.has(l.key)),applySelectedBlocked:o.selectedGroups.some(l=>s.has(l.key)),applying:c.applying,onApplyAll:()=>{c.apply(o.actionableGroups)},onApplySelected:()=>{c.apply(o.selectedGroups)},onSelectAll:o.selectAll,selectedCount:o.selectedGroups.length}),a("div",{className:"recipient-policy-review-list recipient-policy-review-decisions",children:n.map(l=>a(v4,{decision:o.decisionFor(l),group:l,onDecisionChange:d=>o.setDecision(l,d),onSelectedChange:d=>o.setGroupSelected(l.key,d),onStatus:i,options:e,selected:o.selectedKeys.has(l.key)},l.key))})]}):null,t.blockedItems.length>0?a("section",{className:"recipient-policy-review-section recipient-policy-review-blocked",children:[a("h3",{children:["Blocked repairs"," ",a("span",{className:"recipient-policy-review-count",children:t.blockedItems.length})]}),a("div",{className:"recipient-policy-review-list",children:t.blockedItems.map(l=>a(S4,{item:l,options:e},l.blockedItemId))})]}):null]})}function R4(e,t,n={}){if(t.reviewItems.length===0&&t.blockedItems.length===0){ke(null,e),e.hidden=!0;return}e.hidden=!1,ke(a(I4,{options:n,review:t}),e)}function P4(e,t){e.hidden=!1,ke(a("section",{className:"card recipient-policy-review",children:[a("h2",{children:"Sharing review"}),a("p",{className:"settings-note project-attention-note",role:"status",children:Pd(t,"Unable to load sharing decisions. Try again.")})]}),e)}var CI=[["","All projects"],["needs_attention","Needs attention"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","From other devices"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],wt=null,nn=0,zo=250,N4=100,Eh=[],Es=new Set,xs=new Set,Ds=new Set,js=new Map,Os=new Map,Vr=new Map,Ls=new Map,Jo=new Map,Nd=!1,Yo=new Map,$s=!1,$i=!1,xh=0,kI=null,hr=0,Ms=0,Xo=null,Fs=null,Dt=new Set,Td={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Qo=Td,Ad=!1,Dh=!1,Zo=!1,II,Kr={projects:[],total:0,offset:0,has_more:!1},RI=new Set;function et(){if(RI.size===0)return;const e=OI();for(const t of RI)t(e)}function T4(e=!1,t={}){if(!e&&Fs)return Fs;const n=rv(t).then(r=>({ok:!0,summary:r})).catch(()=>({ok:!1}));return Fs=n,n.then(()=>{Fs===n&&(Fs=null)}),n}function jh(e){return T4(e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0,e)}function xe(e){return document.getElementById(e)}function ea(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Ed(e){return e.identity_source!=="unmapped"&&!ea(e)}function PI(e){return Ed(e)&&e.memory_count!=null&&e.guardrail_warnings.every(t=>!t.requires_confirmation)}function A4(e){return`${ea(e)?"peer-received":"local"}:${e.workspace_identity}`}function E4(e){const t=Yo.get(e.workspace_identity);(!t||ea(t)&&!ea(e))&&Yo.set(e.workspace_identity,e)}function NI(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Mi(){const e=Dt.size,t=xe("projectsShareSelected");t&&(t.textContent=e===0?"Add Teams or Identities":`Add Teams or Identities (${e})`,t.disabled=e===0||!$i||!Ad,t.classList.add("project-selection-target"));const n=xe("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`),Wr()}function x4(e){const t=e.every(n=>Dt.has(n));for(const n of e)t?Dt.delete(n):Dt.add(n);Mi(),et()}function TI(e,t,n){const r=[...new Set(e)].filter(i=>!t.has(i)).sort();return new Map(r.map((i,o)=>[i,r.length===1?`Unavailable ${n}`:`Unavailable ${n} ${o+1} of ${r.length}`]))}function AI(e){const t=new Set(e),n=Qo.projectRecipients.filter(d=>d.status==="active"&&t.has(d.canonicalProjectIdentity)),r=new Map(Qo.teams.map(d=>[d.teamId,d.status==="archived"?`${d.displayName} (archived)`:d.displayName])),i=new Map(Qo.identities.map(d=>[d.identityId,d.status==="merged"?`${d.displayName} (merged)`:d.displayName])),o=TI(n.flatMap(d=>d.recipientKind==="team"?[d.teamId]:[]),new Set(r.keys()),"Team"),s=TI(n.flatMap(d=>d.recipientKind==="identity"?[d.identityId]:[]),new Set(i.keys()),"Identity"),c=new Map,l=new Map;for(const d of n){const u=d.recipientKind==="team",f=u?`team:${d.teamId}`:`identity:${d.identityId}`,p=u?r.get(d.teamId)??o.get(d.teamId):i.get(d.identityId)??s.get(d.identityId),m=l.get(f)??new Set;m.add(d.canonicalProjectIdentity),l.set(f,m),c.set(f,{key:f,kind:u?"Team":"Identity",displayName:p??(u?"Unavailable Team":"Unavailable Identity"),coveredProjectCount:m.size,knownProjectCount:t.size})}return[...c.values()].sort((d,u)=>`${d.kind}:${d.displayName}`.localeCompare(`${u.kind}:${u.displayName}`))}function Bs(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function D4(e){return e.project||e.display_project||"Unnamed Project"}function EI(e){const t=String(e||"").trim();return t?y.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function j4(){return new Set(y.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function O4(e){return!$s||e.authority_type!=="coordinator"||!e.group_id?!1:!j4().has(String(e.group_id).trim())}function xd(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function L4(){Nd&&(Nd=!1,wt?.())}async function $4(){let e;try{const t=await vu();e=t&&typeof t=="object"?t:null}catch{y.lastProjectCoordinatorAdminGroups=[],$s=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){y.lastProjectCoordinatorAdminGroups=[],$s=!1;return}try{const t=await Ug(!1);y.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],$s=!0}catch{y.lastProjectCoordinatorAdminGroups=[],$s=!1}}function M4(e){const t=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space",n=EI(e.group_id);return n?`${t} · Team: ${n}`:e.authority_type==="local"?`${t} · Local device`:e.authority_type==="coordinator"?`${t} · Coordinator Space`:`${t} · ${e.authority_type||"Other"} Space`}function F4(){return Eh.filter(e=>e.scope_id!=="legacy-shared-review"&&!O4(e))}function B4(e){const t=EI(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function q4(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function U4(){const e=new Map;for(const t of F4()){const n=q4(t),r=B4(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.entries()].map(([t,n])=>({key:t,...n}))}async function Oh(e,t,n=[]){try{await IT({...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}),Vr.delete(e.workspace_identity),js.delete(e.workspace_identity),et(),Y("Space assignment updated. Device access unchanged."),wt?.()}catch(r){if(r instanceof zi){Vr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),Wr(),et(),wt?.();return}Y(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function G4(e,t){const n=e.filter(Ed);if(n.length!==0)try{await RT({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}))}),Y(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access unchanged.`),Os.delete(Bs(n[0])),et(),wt?.()}catch(r){Y(H4(r),"warning")}}function H4(e){return e instanceof zi?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":e instanceof Error?e.message:"Unable to update project Spaces."}async function V4(e){if(e.mapping_id!=null)try{await PT(e.mapping_id,Ls.get(e.mapping_id)??[]),Ls.delete(e.mapping_id),Vr.delete(e.workspace_identity),js.delete(e.workspace_identity),et(),Y("Project Space assignment removed. The next fallback now applies."),wt?.()}catch(t){if(t instanceof zi){Ls.set(e.mapping_id,t.requiredGuardrailTokens),Y(`${t.guardrailWarnings[0]?.message??"Review the fallback access change."} Select Remove again to confirm.`,"warning");return}Ls.delete(e.mapping_id),Y(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function K4(e,t={}){const n=t.confirmed===!0;try{const r=Jo.get(e.workspace_identity),i=await TT({...n&&r?{confirmation_token:r.confirmationToken}:{},confirmed:n,workspace_identity:e.workspace_identity});Jo.delete(e.workspace_identity),et(),Y(`Forgot ${i.forgotten_memory_count.toLocaleString()} local memor${i.forgotten_memory_count===1?"y":"ies"}. ${i.peer_owned_memory_count.toLocaleString()} peer-owned memor${i.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),wt?.()}catch(r){if(r instanceof Qg){Jo.set(e.workspace_identity,{confirmationToken:r.preview.confirmation_token,localOwnedMemoryCount:r.preview.local_owned_memory_count,peerOwnedMemoryCount:r.preview.peer_owned_memory_count}),Wr(),et(),wt?.();return}Y(r instanceof Error?r.message:"Unable to forget project memories.","warning")}}async function xI(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await rc()).filter(i=>i&&i!==t)}catch{}const r=await mm({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const o=i.trim();return o?o===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await NT({project:r.trim(),workspace_identity:e.workspace_identity});Y(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),wt?.()}catch(i){Y(i instanceof Error?i.message:"Unable to change project.","warning")}}async function W4(e){const t=Yo.get(e);if(t&&!ea(t))return{offset:nn,project:t};try{let n=0,r=0;for(;;){const i=await ma({limit:zo,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!ea(c));if(o)return{offset:i.offset,project:o};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=N4)return null;n=s}}catch{return null}}function Lh(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(c=>c.dataset.projectWorkspaceIdentity===e&&c.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.dataset.projectClusterKey,i=r?[...document.querySelectorAll(".project-inventory-cluster")].find(c=>c.dataset.projectClusterKey===r):null,o=i?.querySelector(":scope > .project-inventory-cluster-details-row .project-inventory-details");if(o){o.open=!0;const c=i?.dataset.projectClusterKey;c&&xs.add(c)}n.open=!0;const s=t.dataset.projectRowKey;return s&&Es.add(s),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}function DI(){return{generation:hr,search:xe("projectsSearch")?.value??"",status:xe("projectsStatusFilter")?.value??"",offset:nn}}function z4(e){return hr!==e.generation||(xe("projectsSearch")?.value??"")!==e.search||(xe("projectsStatusFilter")?.value??"")!==e.status||nn!==e.offset}async function J4(e){const{project:t}=e;if(Lh(t.workspace_identity)||(Ds.add(Bs(t)),Wr(),et(),Lh(t.workspace_identity)))return;const n=xe("projectsSearch"),r=xe("projectsStatusFilter"),i=DI(),o=t.workspace_identity;n&&(n.value=o),r&&(r.value=""),nn=e.offset;const s=hr;await ta(),!Lh(t.workspace_identity)&&(hr!==s||n&&n.value!==o||r&&r.value!==""||nn!==e.offset||(n&&(n.value=i.search),r&&(r.value=i.status),nn=i.offset,await ta(),Y("Project administration could not be opened. Refresh Projects and try again.","warning")))}async function Y4(e){if(xd()){Y("Finish the open Space assignment, then try Repair again.","warning");return}const t=DI(),n=await W4(e.projectIdentity);if(z4(t))return;if(xd()){Y("Finish the open Space assignment, then try Repair again.","warning");return}if(!n){Y("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:r}=n;if(e.kind==="reassign_project"){if(r.identity_source==="unmapped"||r.session_count===0){Y("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await xI(r);return}await J4(n)}function X4(e){const t=hr,n=(Xo?.catch(()=>{})??Promise.resolve()).then(async()=>{if(hr===t)try{await Y4(e)}catch(r){Y(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Xo=n,n.then(()=>{Xo===n&&(Xo=null)},()=>{Xo===n&&(Xo=null)}),n}function Q4(e){const t=new Map;for(const n of e){const r=Bs(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function jI(e){const t=Cp(e),n=Ed(e),r=A4(e),i=n?Vr.get(e.workspace_identity):void 0,o=n?Jo.get(e.workspace_identity):void 0;return{kind:"project",key:r,detailKey:r,project:e,manageable:t,selected:t&&Dt.has(e.workspace_identity),shareEligible:PI(e),shareReady:$i,detailsOpen:Es.has(r),draftScopeId:n?js.get(e.workspace_identity)??null:null,pendingConfirmation:i?{requiredGuardrailTokens:[...i.requiredGuardrailTokens],scopeId:i.scopeId,warnings:[...i.warnings]}:null,pendingForgetConfirmation:o?{...o}:null,recipients:AI([e.workspace_identity])}}function Z4(e){if(e.length===1)return jI(e[0]);const t=Bs(e[0]),n=NI(e.filter(Cp));return{kind:"cluster",key:t,label:D4(e[0]),projects:e.map(jI),projectIds:n,selectedProjectIds:n.filter(r=>Dt.has(r)),worktreesOpen:Ds.has(t),detailsOpen:xs.has(t),draftScopeId:Os.get(t)??null,recipients:AI(NI(e))}}function OI(){const e=[...Dt].sort();return{rows:Q4(Kr.projects).map(Z4),recipientPolicyReady:Dh,shareInventoryReady:$i,scopeLabels:Object.fromEntries(Eh.map(t=>[t.scope_id,M4(t)])),selection:{projectIds:e,count:e.length,ready:$i&&Ad},pagination:{offset:Kr.offset,limit:zo,total:Kr.total,hasMore:Kr.has_more},scopeGroups:U4().map(t=>({key:t.key,label:t.label,scopes:[...t.scopes]})),statusOptions:CI.map(([t,n])=>({label:n,value:t}))}}function LI(){document.getElementById("projectsInventorySkeleton")?.remove()}function e6(e){if(e.total===0)return"0 projects";const t=Math.min(e.offset+e.projects.length,e.total);return`${e.total.toLocaleString()} projects · ${e.offset+1}–${t}`}function Wr(e){if(!Zo)return;const t=xe("projectsInventoryList");t&&Yz(t,OI(),g6,e)}function $I(e){Zo=!0,Kr={projects:[...e.projects],total:e.total,offset:e.offset,has_more:e.has_more};const t=xe("projectsInventoryMeta"),n=xe("projectsInventoryList");if(!t||!n)return;LI(),Yo.clear();for(const o of e.projects)E4(o);Wr(),t.textContent=e6(e);const r=xe("projectsPrevPage"),i=xe("projectsNextPage");r&&(r.disabled=e.offset===0),i&&(i.disabled=!e.has_more),Mi(),et()}function t6(e,t,n){$4().then(()=>{if(t===xh&&$h(n)){if(xd()){et();return}$I(e)}})}async function n6(e={},t){const n=new Map;let r=0;for(;;){const i=await(t?.offset===r?t.promise:ma({limit:zo,offset:r,signal:e.signal}));for(const o of i.projects)n.set(o.workspace_identity,o);if(!i.has_more)break;r+=i.limit}return[...n.values()]}function MI(){return{query:xe("projectsSearch")?.value.trim()??"",status:xe("projectsStatusFilter")?.value??"",offset:nn}}function $h(e){const t=MI();return t.query===e.query&&t.status===e.status&&t.offset===e.offset}function r6(e,t){return ma({limit:zo,offset:t.offset,q:t.query||void 0,status:t.status||void 0,signal:e.signal})}function FI(e,t,n){const r=xe("recipientPolicyManagementMount");r&&hb(r,xc(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Dt.clear(),Mi(),et(),wt?.()}})}function i6(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}function BI(e,t){t4(e,t,{onOpenTeamSetup:II,onFocusFallback:()=>xe("projectsSearch")?.focus()})}function ta(e={}){const t=h6(e);return kI=t,t}async function qI(e,t){return e.signal?.aborted?!1:!e.awaitTeamSetupSummary&&!e.requireTeamSetupSummary?kI??!1:(await t,!1)}function Dd(e,t){return!t.signal?.aborted&&e===xh}function jd(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}async function o6(e){if(!jd(e))return!0;const t=await jh(e);return e.signal?.aborted?!1:!e.requireTeamSetupSummary||t.ok}async function a6(e){if(Nd=!0,!jd(e))return!0;const t=++Ms,n=await jh(e);if(e.signal?.aborted||t!==Ms)return!1;const r=xe("recipientPolicyReviewMount");return n.ok?(r&&BI(r,n.summary),!0):(r&&fI(r),!e.requireTeamSetupSummary)}function s6(e){return jd(e.options)?e.teamSetupSummaryPromise.then(t=>!Dd(e.loadGeneration,e.options)||e.entryLoadGeneration!==Ms?!1:e.requiredLoadSucceeded&&(!e.options.requireTeamSetupSummary||t.ok)):e.requiredLoadSucceeded}async function c6(e,t){return jd(e)&&await t,!1}function l6(e){const t=xe("recipientPolicyReviewMount");if(!t)return;const n=i6(t);"review"in e?R4(n,e.review,{isRepairAvailable:r=>!r.projectIdentity.startsWith("unmapped:"),onRefresh:async()=>{await ta()},onRepair:X4}):P4(n,e.error),t.hidden=n.hidden&&!t.querySelector(".project-team-setup-entry")}async function d6(e,t){const n=r6(e,t),r=!t.query&&!t.status?{offset:t.offset,promise:n}:void 0,[i,o,s,c,l]=await Promise.all([n,_T(e),n6(e,r).then(d=>({ok:!0,projects:d})).catch(()=>({ok:!1,projects:[]})),vT(e).then(d=>({ok:!0,review:d})).catch(d=>({ok:!1,error:d})),Pu(e).then(d=>({ok:!0,intent:d})).catch(d=>({ok:!1,error:d}))]);return{intentResult:l,recipientPolicyReview:c,result:i,settings:o,shareInventory:s}}function u6(e){if(!e.ok)return;const t=new Set(xc(e.projects).map(n=>n.canonicalProjectIdentity));for(const n of Dt)t.has(n)||Dt.delete(n)}function p6(e,t,n){const{intentResult:r,recipientPolicyReview:i,result:o,settings:s,shareInventory:c}=e;Eh=s.scopes,$i=c.ok,Ad=r.ok,Dh=r.ok,Qo=r.ok?r.intent:Td,u6(c);const l=xe("projectShareFlowMount");return l&&Gb(l,c.projects,{inventoryError:!c.ok}),l6(i),FI(c.projects,Qo,!c.ok||!r.ok),$I(o),t6(o,t,n),c.ok&&"review"in i&&r.ok}function f6(e){e.teamSetupSummaryPromise.then(t=>{if(!Dd(e.loadGeneration,e.options)||e.entryLoadGeneration!==Ms)return;const n=xe("recipientPolicyReviewMount");if(n){if(!t.ok){fI(n);return}BI(n,t.summary)}})}function m6(e,t){Zo=!0,Yo.clear(),Kr={projects:[],total:0,offset:nn,has_more:!1},$i=!1,Ad=!1,Dh=!1,Qo=Td;const n=xe("projectShareFlowMount");n&&Gb(n,[],{inventoryError:!0}),FI([],Td,!0),Mi(),et(),LI(),t.textContent="Project inventory failed to load.",Wr(e instanceof Error?e.message:"Unable to load project inventory.")}async function h6(e){const t=xe("projectsInventoryMeta"),n=xe("projectsInventoryList");if(!t||!n)return o6(e);if(xd())return a6(e);Nd=!1;const r=++xh,i=MI();Zo||Mi(),(!Zo||!t.textContent?.trim())&&(t.textContent="Loading project inventory…");let o=null;try{const s=++Ms;o=jh(e);const c=await d6(e,i);if(!Dd(r,e))return qI(e,o);if(!$h(i))return!1;const l=p6(c,r,i);return f6({entryLoadGeneration:s,loadGeneration:r,options:e,teamSetupSummaryPromise:o}),s6({entryLoadGeneration:s,loadGeneration:r,options:e,requiredLoadSucceeded:l,teamSetupSummaryPromise:o})}catch(s){return Dd(r,e)?$h(i)?(m6(s,t),c6(e,o)):!1:qI(e,o)}}function Fi(e){return Yo.get(e)??Kr.projects.find(t=>t.workspace_identity===e)??null}var g6={toggleSelection(e){x4(e)},shareProject(e){const t=Fi(e);!t||!PI(t)||!$i||qc([t.workspace_identity])},manageRecipients(e){const t=[...new Set(e)].sort();if(t.length!==0){if(t.length===1){Ra({mode:"project-manage",projectId:t[0]});return}for(const n of t)Dt.add(n);Mi(),et(),Ra({mode:"project-add",projectIds:t})}},setProjectDetailsOpen(e,t){t?Es.add(e):Es.delete(e),et()},setClusterDetailsOpen(e,t){t?xs.add(e):xs.delete(e),et()},setClusterWorktreesOpen(e,t){t?Ds.add(e):Ds.delete(e),Wr(),et()},setProjectScopeDraft(e,t){js.set(e,t),Vr.delete(e),Wr(),et(),wt?.()},setClusterScopeDraft(e,t){t?Os.set(e,t):Os.delete(e),et()},async saveProjectScope(e,t){const n=Fi(e);n&&await Oh(n,t)},async saveClusterScope(e,t){const n=Kr.projects.filter(r=>Bs(r)===e).filter(Ed);n.length>0&&await G4(n,t)},async removeProjectScope(e){const t=Fi(e);t&&await V4(t)},async keepProjectLocal(e){const t=Fi(e);t&&await Oh(t,"local-default")},async reassignProject(e){const t=Fi(e);t&&await xI(t)},async forgetProject(e,t={}){const n=Fi(e);n&&await K4(n,t)},async confirmProjectScope(e){const t=Fi(e),n=Vr.get(e);!t||!n||await Oh(t,n.scopeId,n.requiredGuardrailTokens)},cancelProjectScopeConfirmation(e){Vr.delete(e),et(),wt?.()},cancelProjectForgetConfirmation(e){Jo.delete(e),et(),wt?.()},onSpaceSelectBlur(){L4()}};function v6(e,t={}){wt=e,II=t.onOpenTeamSetup,Dt.clear(),Es.clear(),xs.clear(),Ds.clear(),js.clear(),Os.clear(),Vr.clear(),Ls.clear(),Jo.clear(),Zo=!1;const n=xe("projectsStatusFilter");n&&n.options.length===0&&n.append(...CI.map(([o,s])=>new Option(s,o)));const r=()=>{hr+=1,nn=0,wt?.()};xe("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),xe("projectsPrevPage")?.addEventListener("click",()=>{hr+=1,nn=Math.max(0,nn-zo),wt?.()}),xe("projectsNextPage")?.addEventListener("click",()=>{hr+=1,nn+=zo,wt?.()});const i=xe("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Dt.size!==0&&Ra({mode:"project-add",projectIds:[...Dt].sort()})})),Mi()}function Mh(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(o=>o.trim()):r;if(t.requireNonEmpty&&i.some(o=>o.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function y6(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,o]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof o!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=o}return r}function b6(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Mh(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(k){if(!i||n.has("claude_command"))throw k;const P=r.claude_command;o=Array.isArray(P)?P.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=Mh(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(k){if(!i||n.has("codex_command"))throw k;const P=r.codex_command;s=Array.isArray(P)?P.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=Mh(t.observerAuthCommand,{label:"observer auth command"})}catch(k){if(!i||n.has("observer_auth_command"))throw k;const P=r.observer_auth_command;c=Array.isArray(P)?P.filter(T=>typeof T=="string"):[]}let l={};try{l=y6(t.observerHeaders)}catch(k){if(!i||n.has("observer_headers"))throw k;const P=r.observer_headers;P&&typeof P=="object"&&!Array.isArray(P)&&Object.entries(P).forEach(([T,E])=>{typeof T=="string"&&T.trim()&&typeof E=="string"&&(l[T]=E)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),f=t.observerRichTemperature.trim(),p=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),b=u===""?"":Number(u),_=f===""?"":Number(f),v=p===""?"":Number(p),S=Number(m),w=m===""?"":S;if(d!==""&&!Number.isFinite(g))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof b!="number"||!Number.isFinite(b)||b<0))throw new Error("simple tier temperature must be a non-negative number");if(f!==""&&(typeof _!="number"||!Number.isFinite(_)||_<0))throw new Error("rich tier temperature must be a non-negative number");if(p!==""&&(typeof v!="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(S)||S<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:Ze(t.observerProvider),observer_model:Ze(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Ze(t.observerSimpleModel),observer_simple_temperature:b,observer_reasoning_effort:Ze(t.observerReasoningEffort),observer_reasoning_summary:Ze(t.observerReasoningSummary),observer_rich_model:Ze(t.observerRichModel),observer_rich_temperature:_,observer_rich_reasoning_effort:Ze(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Ze(t.observerRichReasoningSummary),observer_rich_max_output_tokens:v,observer_runtime:Ze(t.observerRuntime),observer_auth_source:Ze(t.observerAuthSource||"auto")||"auto",observer_auth_file:Ze(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:w,sync_enabled:t.syncEnabled,sync_host:Ze(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Ze(t.syncCoordinatorUrl),sync_coordinator_group:Ze(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function _6(e){return e.resolved_observer_runtime||Ae(Ie(e.config,e.effective,"observer_runtime"))||"api_http"}function UI(e){return Kt(e.config,"observer_tier_routing_enabled")||Kt(e.env_overrides,"observer_tier_routing_enabled")}function w6(e){const t=e.config||{},n=e.effective||{},r=e.observer_apply?.active?.tierRoutingEnabled;return e.observer_apply?.state==="active"&&!UI(e)&&typeof r=="boolean"?r:gd(Ie(t,n,"observer_tier_routing_enabled"))}function S6(e){const t=e.config||{},n=e.effective||{},r=Ie(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([f,p])=>typeof f=="string"&&f.trim()&&typeof p=="string")):{},o=Ie(t,n,"claude_command"),s=Array.isArray(o)?o.filter(f=>typeof f=="string"):[],c=Ie(t,n,"codex_command"),l=Array.isArray(c)?c.filter(f=>typeof f=="string"):[],d=Ie(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(f=>typeof f=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Ae(Ie(t,n,"observer_provider")),observerModel:Ae(Ie(t,n,"observer_model")),observerTierRoutingEnabled:w6(e),observerSimpleModel:Ae(Ie(t,n,"observer_simple_model")),observerSimpleTemperature:Ae(Ie(t,n,"observer_simple_temperature")),observerReasoningEffort:Ae(Ie(t,n,"observer_reasoning_effort")),observerReasoningSummary:Ae(Ie(t,n,"observer_reasoning_summary")),observerRichModel:Ae(Ie(t,n,"observer_rich_model")),observerRichTemperature:Ae(Ie(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Ae(Ie(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Ae(Ie(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Ae(Ie(t,n,"observer_rich_max_output_tokens")),observerRuntime:_6(e),observerAuthSource:Ae(Ie(t,n,"observer_auth_source"))||"auto",observerAuthFile:Ae(Ie(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Ae(Ie(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Ae(Ie(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Ae(Ie(t,n,"observer_max_chars")),packObservationLimit:Ae(Ie(t,n,"pack_observation_limit")),packSessionLimit:Ae(Ie(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Ae(Ie(t,n,"raw_events_sweeper_interval_s")),syncEnabled:gd(Ie(t,n,"sync_enabled")),syncHost:Ae(Ie(t,n,"sync_host")),syncPort:Ae(Ie(t,n,"sync_port")),syncInterval:Ae(Ie(t,n,"sync_interval_s")),syncMdns:gd(Ie(t,n,"sync_mdns")),syncCoordinatorUrl:Ae(Ie(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Ae(Ie(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Ae(Ie(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Ae(Ie(t,n,"sync_coordinator_presence_ttl_s"))}}function C6(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection lives in Connection.";const n=_3(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Ze(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Kt(t,r))?"Env override":n.source}: ${n.model}`}function k6(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function I6(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Connection 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 R6(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while Connection controls simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-6-luna` for Direct API (including pi-derived API-key providers) or Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function P6(e){return!e}function N6(e,t,n){return t.has(e)||n.has(e)}function T6(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var W={previouslyFocused:null,baseline:{},effectiveConfig:{},resolvedObserverRuntime:null,observerRuntimeByAuthSource:{},observerRuntimeAfterAuthOverrideRemoval:{},observerAutomaticRuntimeByAuthSource:{},observerApply:null,observerTierRoutingExplicit:!1,observerModelDefaults:null,restartRequiredKeys:new Set,envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,hideTooltip:null},jt=Fa({open:!1,activeTab:"observer",dirty:!1,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...u3}},showAdvanced:g3()});function zt(){return jt.value}function qs(e){jt.value={...jt.value,...e}}function A6(){W.hideTooltip?.()}function zr(e){qs({renderState:{...jt.value.renderState,...e}})}function GI(e){zr({values:{...jt.value.renderState.values,...e}})}function HI(e){qs({activeTab:["observer","queue","sync"].includes(e)?e:"observer"})}function Od(e){qs({dirty:e})}function Ld(e){qs({open:e})}function E6(e){v3(e),qs({showAdvanced:e})}function VI(){return zt().open}function KI(e){return N6(e,W.protectedKeys,d3)}function Fh(e={}){const t=b6({values:zt().renderState.values,touchedKeys:W.touchedKeys,baseline:W.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors});return W.touchedKeys.has("observer_runtime")||(t.observer_runtime=W.baseline.observer_runtime),t}function WI(e){const t=y.feedProcessingStatus,n=x6(e);y.feedProcessingStatus=n,(t.kind!==n.kind||t.kind==="pending"&&n.kind==="pending"&&t.count!==n.count)&&Ln(!0),zr({observerStatus:e&&typeof e=="object"?e:null})}function x6(e){if(!e||typeof e!="object")return{kind:"unavailable"};const t=e,n=Number(t.queue?.pending);return Number.isFinite(n)&&n>0?{kind:"pending",count:Math.floor(n)}:t.capture_enabled===!1?{kind:"paused"}:{kind:"ready"}}function D6(e,t){return e&&typeof e=="object"&&Object.keys(e).length>0?t?"Fields show configuration-resolved values. Runtime behavior may apply automatic provider defaults. Environment settings supply some fields.":"Fields show configuration-resolved values. The current connection and models are shown separately while changes apply.":"Effective values are unavailable. Reload Settings; if this persists, restart the viewer and inspect its configuration."}function j6(e){W.resolvedObserverRuntime=e.resolved_observer_runtime??null,W.observerRuntimeByAuthSource=e.observer_runtime_by_auth_source??{},W.observerRuntimeAfterAuthOverrideRemoval=e.observer_runtime_after_auth_override_removal??{},W.observerAutomaticRuntimeByAuthSource=e.observer_automatic_runtime_by_auth_source??{}}function O6(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},o=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=S6(t);W.envOverrides=i,W.effectiveConfig={...r,...t.effective},j6(t),W.observerApply=t.observer_apply??null,W.observerTierRoutingExplicit=UI(t),W.observerModelDefaults=t.observer_model_defaults??null,W.restartRequiredKeys=new Set(t.restart_required_keys??[]),W.protectedKeys=new Set(o),y.configDefaults=n,y.configPath=t.path||"",W.touchedKeys=new Set,zr({effectiveText:D6(t.effective,Object.keys(i).length>0),overridesVisible:Object.keys(i).length>0,pathText:y.configPath?`Config path: ${y.configPath}`:"Config path: n/a",providers:y3(t.providers),statusText:"No unsaved changes",values:s});try{const c=Fh({allowUntouchedParseErrors:!0});W.baseline=S3(c,r,i),W.baseline.observer_runtime=Ze(Ae(r.observer_runtime))}catch{W.baseline={}}Od(!1)}async function L6(e={}){if(zt().open)return;const[t,n]=await Promise.allSettled([qg(e),Bg(e)]);e.signal?.aborted||(t.status==="fulfilled"&&O6(t.value),WI(n.status==="fulfilled"?n.value:null))}function zI(e){if(!e)return"Not available";const t=e.reasoningEffort?` · ${e.reasoningEffort} reasoning`:"";return`${e.provider} · ${e.model}${t}`}function $6({active:e}){return a("details",{className:"settings-note observer-routing-details",children:[a("summary",{children:"Models in use"}),e.tierRoutingEnabled?a("dl",{className:"observer-routing-list",children:[a("div",{children:[a("dt",{children:"Simple requests"}),a("dd",{children:zI(e.simple)})]}),a("div",{children:[a("dt",{children:"Rich requests"}),a("dd",{children:zI(e.rich)})]})]}):a("dl",{className:"observer-routing-list",children:a("div",{children:[a("dt",{children:"All requests"}),a("dd",{children:[e.provider," · ",e.model]})]})})]})}function M6({status:e,onRetry:t,onRefresh:n}){return e?a(U,{children:[e.active?a($6,{active:e.active}):null,e.state==="applying"?a("div",{role:"status",children:"Applying observer settings. New events will wait."}):null,e.state==="failed"?a("div",{role:"alert",children:[e.message??"Observer settings were saved but are not active."," ",a("button",{className:"settings-button",onClick:t,type:"button",children:"Retry applying observer settings"})]}):null,e.state!=="active"?a("button",{className:"settings-link-button",onClick:n,type:"button",children:"Check observer status"}):null]}):null}function F6({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function B6({available:e,method:t}){const n=Object.entries(e??{}).filter(([,r])=>r&&typeof r=="object");return!n.length||["codex_sidecar","claude_sidecar","opencode_v2"].includes(t??"")?null:a("details",{className:"status-credentials",children:[a("summary",{children:"API keys and saved sign-ins"}),a("ul",{children:n.map(([r,i])=>a("li",{children:[r,": ",f3(i)]},r))})]})}function q6({failure:e,onOpenDiagnostics:t}){return a("div",{className:"status-issue",children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue-message",children:typeof e.error_message=="string"&&e.error_message.trim()?e.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof e.observer_provider=="string"?e.observer_provider.trim():"",typeof e.observer_model=="string"&&e.observer_model.trim()?`→ ${e.observer_model.trim()}`:"",typeof e.observer_runtime=="string"&&e.observer_runtime.trim()?`(${e.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${m3(e.updated_at)}`,typeof e.attempt_count=="number"&&Number.isFinite(e.attempt_count)?`Attempts ${e.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof e.impact=="string"&&e.impact.trim()?a("div",{className:"status-issue-impact",children:e.impact.trim()}):null,a(F6,{onOpenDiagnostics:t})]})}function U6({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=n?.auth?.token_present===!1&&(n.runtime==="api_key"||n.auth.method==="none");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[e.latest_failure?a(q6,{failure:e.latest_failure,onOpenDiagnostics:t}):null,a("div",{className:"status-active",children:[a("span",{className:"status-label",children:"Current connection"}),a("span",{children:n?a(U,{children:[String(n.provider||"unknown"),n.model?` · ${String(n.model)}`:""," ·"," ",p3(n.auth?.method||"none")]}):"Waiting for the first session"})]}),r?a("div",{className:"status-token-warning",children:"No Direct API key detected. Check your credentials."}):null,a(B6,{available:e.available_credentials,method:n?.auth?.method})]})}function JI(e,t){const n=t.getBoundingClientRect(),r=8,i=8,o=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-o/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-o-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Us(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function G6(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 H6(){const e=Xe("settingsModal");(G6(e)[0]||e)?.focus()}function V6(e,t){const n=e.getAttribute("aria-describedby")?.split(/\s+/).filter(Boolean)??[];if(!n.includes(t))return e.setAttribute("aria-describedby",[...n,t].join(" ")),()=>{const r=(e.getAttribute("aria-describedby")?.split(/\s+/)??[]).filter(i=>i&&i!==t);r.length>0?e.setAttribute("aria-describedby",r.join(" ")):e.removeAttribute("aria-describedby")}}function K6(e,t,n){return ye(()=>typeof document>"u"?null:_n(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,id:n,ref:t,role:"tooltip",children:e.content}),document.body),[e.content,e.visible,n,t])}function W6(){const e=`settings-help-${ht()}`,[t,n]=R({anchor:null,content:"",visible:!1}),r=x(null);return Ge(()=>{if(!(!t.visible||!t.anchor))return V6(t.anchor,e)},[t.anchor,t.visible,e]),q(()=>{const i=f=>{const p=f.dataset.tooltip?.trim();p&&n({anchor:f,content:p,visible:!0})},o=()=>{n(f=>!f.visible&&!f.anchor&&!f.content?f:{anchor:null,content:"",visible:!1})},s=f=>{const p=Us(f.target);p&&i(p)},c=f=>{const p=Us(f.target);if(!p)return;const m=f.relatedTarget;m instanceof Element&&p.contains(m)||o()},l=f=>{const p=Us(f.target);p&&i(p)},d=f=>{Us(f.target)&&o()},u=f=>{const p=Us(f.target);p&&(f.preventDefault(),n(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const g=p.dataset.tooltip?.trim()||"";return g?{anchor:p,content:g,visible:!0}:m}))};return document.addEventListener("pointerover",s),document.addEventListener("pointerout",c),document.addEventListener("focusin",l),document.addEventListener("focusout",d),document.addEventListener("click",u),()=>{document.removeEventListener("pointerover",s),document.removeEventListener("pointerout",c),document.removeEventListener("focusin",l),document.removeEventListener("focusout",d),document.removeEventListener("click",u)}},[]),Ge(()=>{if(!t.visible||!t.anchor||!r.current)return;const i=requestAnimationFrame(()=>{r.current&&t.anchor&&JI(r.current,t.anchor)});return()=>{cancelAnimationFrame(i)}},[t.anchor,t.content,t.visible]),q(()=>{if(!t.visible||!t.anchor)return;const i=()=>{r.current&&t.anchor&&JI(r.current,t.anchor)};return globalThis.addEventListener("resize",i),document.addEventListener("scroll",i,!0),()=>{globalThis.removeEventListener("resize",i),document.removeEventListener("scroll",i,!0)}},[t.anchor,t.visible]),{tooltipPortal:K6(t,r,e),setTooltip:n}}function z6({DialogContent:e,onClose:t}){const{open:n}=jt.value,{tooltipPortal:r,setTooltip:i}=W6();q(()=>{const s=()=>i({anchor:null,content:"",visible:!1});return W.hideTooltip=s,()=>{W.hideTooltip===s&&(W.hideTooltip=null)}},[]),q(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const o=re(()=>{W.startPolling&&W.refresh&&t(W.startPolling,W.refresh)},[t]);return a(U,{children:[a(Zt,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:s=>{s.preventDefault()},onOpenAutoFocus:s=>{s.preventDefault(),H6()},onOpenChange:s=>{if(s){Ld(!0);return}o()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),r]})}function YI(e){return{controlId:e,existingData:"Stored memories stay unchanged; no backfill runs.",scope:"Queued and future model requests on this device",stage:"Observation processing",timing:"After viewer restart"}}function Bh(e){return{controlId:e,existingData:"Stored memories stay unchanged; no reprocessing runs.",scope:"Queued and future events on this device",stage:"Observation processing",timing:"After viewer restart"}}function XI(e){return{controlId:e,existingData:"Stored memories and existing packs stay unchanged; the value is saved only.",scope:"No current effect",stage:"Saved setting",timing:"Not used when Codemem creates context packs"}}function $n(e,t){return{controlId:e,existingData:"Existing memories are not reprocessed locally, but eligible memories may be sent to or received from trusted peers.",scope:t,stage:"Device sync",timing:"After viewer restart"}}function J6(e){return{controlId:e,existingData:"Stored memories stay unchanged. Local Claude and Codex sessions authenticate through their CLI logins instead.",scope:"No effect while Connection mode uses a local Claude or Codex session",stage:"Sidecar authentication",timing:"Not used by local Claude or Codex sessions"}}var Y6=new Set(["observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"]);function $d(e){return e==="claude_sidecar"||e==="codex_sidecar"}var X6=Object.fromEntries([...["observerProvider","observerModel","observerRuntime","observerMaxChars","observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"].map(YI),...["observerTierRoutingEnabled","observerSimpleModel","observerSimpleTemperature","observerReasoningEffort","observerReasoningSummary","observerRichModel","observerRichTemperature","observerRichReasoningEffort","observerRichReasoningSummary","observerRichMaxOutputTokens"].map(Bh),XI("packObservationLimit"),XI("packSessionLimit"),{controlId:"rawEventsSweeperIntervalS",existingData:"Processed events stay unchanged; no backfill runs.",scope:"Background queue on this viewer",stage:"Queue processing",timing:"Immediately after save"},$n("syncEnabled","Future sync cycles on this device"),$n("syncInterval","Future sync cycles on this device"),$n("syncHost","Incoming peer connections to this device"),$n("syncPort","Incoming peer connections to this device"),$n("syncMdns","Advertise this device on the local network; this does not scan for peers"),$n("syncCoordinatorGroup","Fallback coordinator discovery when no coordinator group list is configured"),$n("syncCoordinatorTimeout","Future coordinator requests"),$n("syncCoordinatorPresenceTtl","Future coordinator presence checks")].map(e=>[e.controlId,e]));function qh(e,t={}){let n=X6[e];if(!n)return;const r=Uh(t.observerRuntime);if(Y6.has(e)&&$d(r))return J6(e);if(n=e5(e,r)??n,n.scope==="No current effect")return n;const i=md[e],o=i?W.envOverrides[i]:void 0;return typeof o!="string"||!o.trim()?n:{...n,timing:`After removing ${o.trim()} and restarting the viewer`}}function Gs(e=jt.value.renderState.values.observerRuntime){return W.envOverrides.observer_runtime?!!String(W.effectiveConfig.observer_runtime??"").trim():W.touchedKeys.has("observer_runtime")?!!e?.trim():!!String(W.baseline.observer_runtime??"").trim()}function Uh(e){const t=W.envOverrides.observer_runtime,n=Jr("observerRuntime",e),r=W.touchedKeys.has("observer_runtime")&&n!==W.baseline.observer_runtime;if(r&&!n&&!t){const o=Md(Jr("observerAuthSource"));return W.observerAutomaticRuntimeByAuthSource[o]||"api_http"}if(t||!r){const o=Q6();if(o)return o;if(W.resolvedObserverRuntime)return W.resolvedObserverRuntime}const i=String(n??"").trim().toLowerCase();return["api_key","opencode_v2"].includes(i)||$d(i)?i:"api_http"}function Q6(){if(!W.touchedKeys.has("observer_auth_source"))return;const e=Md(Jr("observerAuthSource"));return W.observerRuntimeByAuthSource[e]}function Z6(e){return W.envOverrides.observer_auth_source?!0:W.touchedKeys.has("observer_runtime")&&e!==W.baseline.observer_runtime&&!W.envOverrides.observer_runtime?e?.trim()?!1:Object.values(W.observerAutomaticRuntimeByAuthSource).includes("api_http"):Object.values(W.observerRuntimeByAuthSource).includes("api_http")}function Jr(e,t){const n=md[e];return n&&W.envOverrides[n]?W.effectiveConfig[n]:t??jt.value.renderState.values[e]}function na(e,t){return{controlId:e,existingData:"Stored memories stay unchanged; this value is saved only.",scope:"No current effect",stage:"Saved setting",timing:t}}function e5(e,t){const n=$d(t),r=String(Jr("observerProvider"));if(e==="observerProvider"&&n&&Gs())return na(e,"Local Claude and Codex sessions select their own provider");if(e==="observerModel")return n5(t,r);const i=Md(Jr("observerAuthSource"));if(e==="observerAuthTimeoutMs"&&!["auto","command"].includes(i))return na(e,"Only command authentication uses this timeout");if(e==="observerAuthCacheTtlS"&&!["file","command"].includes(i))return na(e,"Only explicit file or command authentication uses this cache");if(/Temperature$/.test(e))return i5(e,t,QI(e,r));if(/Reasoning(Effort|Summary)$/.test(e)||e==="observerRichMaxOutputTokens")return o5(e,n);if(e==="syncEnabled"&&!t5(Jr(e)))return{...$n(e,"Stop future peer transfers on this device"),existingData:"Stored memories remain. Disabling sync does not retract copies already replicated to peers."};if(e==="syncHost"||e==="syncPort")return{...$n(e,"Incoming connections and newly generated pairing addresses"),timing:"Pairing payloads change immediately after save; restart the viewer before sharing or using them so the listener uses the new address"}}function Md(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return["auto","env","file","command","none"].includes(t)?t:"auto"}function t5(e){return typeof e=="boolean"?e:typeof e!="string"?!1:["1","true","yes","on"].includes(e.trim().toLowerCase())}function n5(e,t){const n="observerModel",r=Jr("observerTierRoutingEnabled");return(r===!0||r==="true"||r==="1")&&r5(e,t)?na(n,"Tier models or built-in tier defaults take precedence over the base model"):{...YI(n),scope:"Requests that use the base model, including tiers that fall back to it",timing:"After viewer restart, only where no tier model or built-in tier default takes precedence"}}function QI(e,t){const n=e.startsWith("observerSimple")?"observer_simple_provider":"observer_rich_provider",r=String(W.effectiveConfig[n]??"").trim().toLowerCase(),i=t.trim().toLowerCase();return["openai","anthropic"].includes(r)?r:["openai","anthropic"].includes(i)?i:r||i}function r5(e,t){return e==="claude_sidecar"?!0:["observerSimpleModel","observerRichModel"].every(n=>String(Jr(n)??"").trim()?!0:e==="codex_sidecar"?!1:["openai","anthropic"].includes(QI(n,t)))}function i5(e,t,n){return $d(t)||n==="anthropic"?na(e,"Anthropic and local Claude/Codex sessions do not send sampling temperature"):{...Bh(e),scope:"Only tier requests whose transport sends sampling temperature; OpenAI reasoning requests omit it",timing:"After viewer restart, only when the selected transport and reasoning mode support temperature"}}function o5(e,t){if(t)return na(e,"Local Claude and Codex sessions do not use these API tuning fields");const n=e==="observerRichMaxOutputTokens"?"Rich-tier API requests whose transport consumes the output-token limit; unsupported transports ignore it":"OpenAI Responses requests only; other transports ignore reasoning fields";return{...Bh(e),scope:n,timing:"After viewer restart, only when the effective request transport consumes this setting"}}function ZI({controlId:e,existingData:t,scope:n,stage:r}){return a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:"Change details"}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function a5({scope:e,stage:t,timing:n}){return e==="No current effect"||t==="Sidecar authentication"?a("div",{className:"settings-effect-note small",children:["Inactive · ",n]}):/only/i.test(e)?a("div",{className:"settings-effect-note small",children:e}):null}function s5(e,t){const n=W.envOverrides[e];if(n)return n;if(t==="Sidecar authentication"&&!Gs())return W.envOverrides.observer_auth_source}function c5(){const e=Md(W.touchedKeys.has("observer_auth_source")?jt.value.renderState.values.observerAuthSource:W.baseline.observer_auth_source);return(W.observerRuntimeAfterAuthOverrideRemoval[e]??W.observerRuntimeByAuthSource[e])==="api_http"}function l5({configKey:e,...t}){const{scope:n,stage:r,timing:i}=t,o=s5(e,r),s=n==="No current effect"||r==="Sidecar authentication";if(typeof o!="string"||!o.trim())return a(U,{children:[a(a5,{...t}),a(ZI,{...t})]});let c="Remove that environment setting and restart the viewer to apply changes here.";const l=W.envOverrides.observer_auth_source;return r==="Sidecar authentication"&&!Gs(jt.value.renderState.values.observerRuntime)&&c5()&&typeof l=="string"&&l.trim()?c=`Inactive for the current connection · ${i}. Remove ${[...new Set([l.trim(),o.trim()])].join(" and ")} and restart the viewer to use the saved authentication settings. The connection may change after removal.`:s&&(c=`Inactive · ${i}. Removing the environment setting does not activate this field for the current connection.`),a(U,{children:[a("div",{className:"settings-env-note small",children:["Controlled by ",o.trim(),". ",c]}),a(ZI,{...t})]})}function eR({controlId:e,existingData:t,scope:n,stage:r,timing:i}){const o=md[e];if(o?.startsWith("observer_"))return a(l5,{configKey:o,controlId:e,existingData:t,scope:n,stage:r,timing:i});let s=i;return i==="After viewer restart"?s="Change details":i.startsWith("After removing ")?s=`Environment-controlled · ${i}`:n==="No current effect"||r==="Sidecar authentication"?s=`Inactive · ${i}`:i.startsWith("After viewer restart,")&&(s="Change details"),a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:s}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Takes effect:"})," ",i]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function tR(e,t){for(const n of yn(e)){if(!n||typeof n!="object"||!("props"in n))continue;const r=n.props;if(typeof r.id=="string"&&qh(r.id,t))return r.id;const i=tR(r.children,t);if(i)return i}}function De({children:e,className:t="field",hidden:n=!1,id:r}){const i={observerRuntime:jt.value.renderState.values.observerRuntime},o=tR(e,i),s=o?qh(o,i):void 0;return a("div",{className:t,hidden:n,id:r,children:[e,s?a(eR,{...s}):null]})}function nR(e,t,n,r){if(!t)return"";if(e.observerRuntime==="claude_sidecar")return n?t[n].anthropic??t.claude:t.claude;if(e.observerRuntime==="codex_sidecar")return n&&(e.observerModel.trim()||t[n].openai)||t.codex;const i=u5(e,t);return n?d5(e,t,n,i,r):t.base[i]??""}function d5(e,t,n,r,i){const o=i?.trim().toLowerCase(),s=t[n][o??""]?o:r;return t[n][s??""]||e.observerModel.trim()||t.base[o||r]||""}function u5(e,t){const n=e.observerProvider.trim().toLowerCase();if(n)return n;const r=e.observerModel.trim().toLowerCase(),i=r.split("/")[0]??"";return Object.hasOwn(t.base,i)?i:r.startsWith("claude")?"anthropic":"openai"}var Fd=null;function p5(){if(Fd&&Date.now()-Fd.loadedAt<6e4)return Fd.promise;const e=fetch("/api/observer-model-catalog").then(t=>t.json()).then(t=>Array.isArray(t.models)?t.models:[]).catch(()=>[]);return Fd={loadedAt:Date.now(),promise:e},e}function rR({id:e,values:t,provider:n}){const r=t[e];let i=n?.trim().toLowerCase()||t.observerProvider;t.observerRuntime==="codex_sidecar"?i="openai":t.observerRuntime==="claude_sidecar"&&(i="anthropic");const[o,s]=R([]);q(()=>{let d=!0;return p5().then(u=>{d&&s(u)}),()=>{d=!1}},[]);const c=i||(r.startsWith("claude")?"anthropic":"openai"),l=o.filter(d=>d.provider===c);return a(U,{children:[a("datalist",{id:`${e}-catalog`,children:l.map(d=>a("option",{value:d.model},`${d.provider}:${d.model}`))}),l.length?a("div",{className:"small",children:"OpenCode model list; account access is not verified."}):null]})}function Bd({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`,l=qh(i);return a("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[a("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:o}),a(Eo,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"}),l?a(eR,{...l}):null]})}function iR({values:e,onTextInput:t,getObserverModelLabel:n,getObserverModelTooltip:r,modelDefaults:i}){const o=e.observerTierRoutingEnabled;return a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:o?"Fallback model":n()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":r(),type:"button",children:"?"})]}),a(be,{id:"observerModel",list:"observerModel-catalog",onInput:t("observerModel"),placeholder:nR(e,i),value:e.observerModel}),o?a("div",{className:"small",children:"Used only when a tier has no selected or built-in model."}):null,["api_http","api_key","opencode_v2"].includes(e.observerRuntime)?a(rR,{id:"observerModel",values:e}):null]})}function oR({tier:e,values:t,onTextInput:n,tierProviders:r,modelDefaults:i}){const o=e==="simple"?"observerSimpleModel":"observerRichModel",s=e==="simple"?"Simple model":"Rich model",c=e==="simple"?"Used for shorter, simpler requests.":"Used for larger or more involved requests.";return a(De,{children:[a("label",{htmlFor:o,children:s}),a(be,{id:o,list:`${o}-catalog`,onInput:n(o),placeholder:nR(t,i,e,r?.[e]),value:t[o]}),a("div",{className:"small",children:c}),["api_http","api_key","opencode_v2"].includes(t.observerRuntime)?a(rR,{id:o,values:t,provider:r?.[e]}):null]})}function f5(e){const{values:t,onSwitchInput:n,hiddenUnlessAdvanced:r}=e,i=t.observerTierRoutingEnabled,o=t.observerModel.trim().length>0;return a("div",{className:"settings-group observer-model-settings",children:[a("h3",{className:"settings-group-title",children:"Models"}),a(Bd,{checked:i,className:"field",id:"observerTierRoutingEnabled",label:"Use simple and rich models",onCheckedChange:n("observerTierRoutingEnabled")}),i?a(U,{children:[a(oR,{tier:"simple",...e}),a(oR,{tier:"rich",...e}),o||!r()?a("details",{className:"observer-fallback-details",children:[a("summary",{children:o?"Fallback model · Custom value set":"Fallback model (optional)"}),a(iR,{...e})]}):null]}):a(iR,{...e})]})}function qd({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function m5({runtime:e,onSelectValueChange:t}){let n="Keeps your existing connection rules until you choose a connection below.";e==="claude_sidecar"?n="Uses your local Claude CLI login. Claude chooses the provider.":e==="codex_sidecar"?n="Uses your local Codex CLI login. Codex chooses the provider.":e==="opencode_v2"?n="Uses the selected provider account in OpenCode. OpenCode must be running.":e==="api_key"&&(n="Uses an API key for the selected provider. Does not use subscription sign-ins.");const r=[{label:"Automatic (detect connection)",value:"automatic"},{label:"OpenCode account",value:"opencode_v2"},{label:"API key",value:"api_key"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}];return e==="api_http"&&r.unshift({label:"Existing API connection (legacy)",value:"api_http"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Choose which account handles model requests. An explicit connection never falls back to another account.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Connection mode",id:"observerRuntime",onValueChange:i=>t("observerRuntime")(i==="automatic"?"":i),options:r,value:e}),a("div",{className:"small",children:n})]})}function h5({value:e,providerOptions:t,onSelectValueChange:n}){const r={anthropic:"Anthropic",opencode:"OpenCode",openai:"OpenAI"};return a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Pi setup can also derive a provider and model from an API-key provider.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Model provider",id:"observerProvider",onValueChange:n("observerProvider"),options:[{label:"Auto (infer provider)",value:""},...t.map(i=>({...i,label:r[i.value]??i.label}))],placeholder:"Auto (infer provider)",value:e}),a("div",{className:"small",children:"Use auto unless you need to pin a provider."})]})}function g5({values:e,runtime:t,explicit:n,providerOptions:r,onSelectValueChange:i}){return a(U,{children:[a(m5,{runtime:n?t:"automatic",onSelectValueChange:i}),!n||!(t==="claude_sidecar"||t==="codex_sidecar")?a(h5,{value:e.observerProvider,providerOptions:r,onSelectValueChange:i}):null]})}function v5(e){return e==="claude_sidecar"||e==="codex_sidecar"}function y5(e){return v5(e)||e==="opencode_v2"}function b5({values:e,effectiveObserverRuntime:t=e.observerRuntime,hasExplicitObserverRuntime:n=!0,allowAutomaticAuthChanges:r=!1,tierProviders:i,modelDefaults:o,observerMaxCharsDefault:s,providerOptions:c,showAuthFile:l,showAuthCommand:d,hiddenUnlessAdvanced:u,onTextInput:f,onSelectValueChange:p,onSwitchInput:m,getObserverModelLabel:g,getObserverModelTooltip:b,protectedConfigHelp:_,observerStatusBannerSlot:v}){return a(U,{children:[a("p",{className:"small observer-panel-intro",children:["Shared across ",$k(),"."]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(g5,{values:e,providerOptions:c,onSelectValueChange:p,runtime:t,explicit:n}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Do,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:_("codex_command")})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Do,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:_("claude_command")})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(be,{id:"observerMaxChars",min:"1",onInput:f("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:s?`Default: ${s}`:""})]})]}),a(f5,{values:{...e,observerRuntime:t},tierProviders:i,modelDefaults:o,hiddenUnlessAdvanced:u,onTextInput:f,onSwitchInput:m,getObserverModelLabel:g,getObserverModelTooltip:b}),v,a("div",{className:"settings-group",hidden:y5(t)&&!r,children:[a("h3",{className:"settings-group-title",children:"API credentials"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Credential source"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Authentication method",id:"observerAuthSource",onValueChange:p("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],value:e.observerAuthSource}),a("div",{className:"small",children:"API keys are read from your config or environment. File and command sources use the saved protected settings below."})]}),a(De,{hidden:!l,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(be,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:_("observer_auth_file")})]}),a(De,{hidden:!d,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(Do,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:_("observer_auth_command")})]}),a("div",{className:"small",hidden:!d,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(qd,{hidden:u(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(be,{id:"observerAuthTimeoutMs",min:"1",onInput:f("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(be,{id:"observerAuthCacheTtlS",min:"0",onInput:f("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(Do,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:_("observer_headers")})]})]})]})}function aR({detail:e,title:t}){return a("div",{className:"settings-section-intro",children:[a("div",{className:"settings-section-intro-title",children:t}),a("div",{className:"small settings-section-intro-detail",children:e})]})}function _5({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r}){return a(U,{children:[a(aR,{detail:"Adjust background processing and, if needed, advanced model request controls. Choose models in Connection.",title:"Background processing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),a("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),a(be,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),a("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),a("div",{className:"settings-group settings-advanced",hidden:!t||n(),children:[a("h3",{className:"settings-group-title",children:"Model tuning"}),a("div",{className:"small",children:"These controls apply only when the selected connection supports them."}),a("div",{children:[a("h4",{children:"Simple tier"}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(be,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),a("div",{className:"settings-advanced",hidden:!t||n(),children:[a("h4",{children:"Shared reasoning defaults"}),a("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),a(De,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(be,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(De,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(be,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),a("div",{children:[a("h4",{children:"Rich tier"}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(be,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(be,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(be,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(be,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),a("div",{className:"settings-group settings-advanced",hidden:n(),children:[a("h3",{className:"settings-group-title",children:"Pack limits"}),a(qd,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(be,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),a("div",{className:"small",children:"Default number of observations to include in a pack."})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(be,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),a("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function w5({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(U,{children:[a(aR,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Device Sync"}),a(Bd,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a(De,{children:[a("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),a(be,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),a("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncHost",children:"Sync host"}),a(be,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncPort",children:"Sync port"}),a(be,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(Bd,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),a(be,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),a("div",{className:"small",children:i("sync_coordinator_url")})]}),a(De,{children:[a("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),a(be,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),a("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:a(qd,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),a(be,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),a(be,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function S5({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,restartRequired:o=!1,onClose:s,onSave:c,onActiveTabChange:l,onAdvancedToggle:d,onShowGettingStarted:u,observerStatusBannerSlot:f}){const p=!i||r.isSaving,m=i&&!r.isSaving&&!r.statusText.startsWith("Save failed")?"Unsaved changes":r.statusText;return a("form",{className:"modal-card",onKeyDown:g=>ns(g,{onSubmit:c,disabled:p}),onSubmit:g=>g.preventDefault(),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(kr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:s})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(Bd,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:d}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(qd,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),a(Kf,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:l,tabs:l3,triggerClassName:"settings-tab",value:t,children:[a(bi,{className:"settings-panel",forceMount:!0,value:"observer",children:a(b5,{...e,observerStatusBannerSlot:f})}),a(bi,{className:"settings-panel",forceMount:!0,value:"queue",children:a(_5,{...e})}),a(bi,{className:"settings-panel",forceMount:!0,value:"sync",children:a(w5,{...e})})]}),a("details",{className:"settings-config-details",children:[a("summary",{children:"Configuration details"}),a("div",{className:"small mono",id:"settingsPath",children:r.pathText}),a("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."})]})]}),a("div",{className:"modal-footer",children:[a("div",{className:"settings-footer-copy",children:[a("div",{"aria-live":"polite",className:"small",id:"settingsStatus",children:m}),i&&o?a("div",{role:"status",className:"small settings-restart-required",children:"Restart required"}):null,a("button",{className:"settings-link-button",onClick:u,type:"button",children:"Show getting started"})]}),a("button",{className:"settings-save","data-primary-action":"true",disabled:p,id:"settingsSave",onClick:c,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function sR(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};Object.entries(t).forEach(([l,d])=>{o(l)||Kt(r,l)&&!i.has(l)||b3(d,n[l])||(s[l]=d)});const c="observer_tier_routing_enabled";return(["observer_runtime","observer_provider","observer_model","observer_auth_source"].some(l=>Kt(s,l))||i.has(c))&&typeof t[c]=="boolean"&&!Kt(r,c)&&!o(c)&&(s[c]=t[c]),s}function C5(e){const t=s=>{const c=md[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.onValuesChanged?.(),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 k5(e,t,n,r){return r||t.length>0||n.length>0||e.sync?.ok===!1}function I5(e){return Array.isArray(e.applying_keys)&&e.applying_keys.length>0}function R5(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=>mh(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>mh(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>mh(String(p))):[],s=I5(n),c=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],l=Array.isArray(n.manual_actions)?n.manual_actions:[],d=n.sync&&typeof n.sync=="object"?n.sync:{},u=[];r.length&&u.push(`Applied now: ${hd(r)}.`),i.length&&u.push(`Live settings updated: ${hd(i)}.`),s&&u.push("Observer settings saved. Applying them now; new events will wait."),d.attempted&&typeof d.message=="string"&&d.message?u.push(`Sync: ${d.message}.`):Array.isArray(d.affected_keys)&&d.affected_keys.length&&typeof d.reason=="string"&&d.reason&&u.push(`Sync: ${d.reason}.`),o.length&&u.push(`Restart required for ${hd(o)}. Run: codemem serve restart`),c.forEach(p=>{u.push(p)}),l.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&u.push(`If needed: ${p.command}.`)}),u.length||u.push("Saved.");const f=k5(n,o,c,s);return{message:u.join(" "),type:f?"warning":"success"}}function P5(){return[["observer_runtime","observerRuntime"],["observer_provider","observerProvider"],["observer_model","observerModel"],["observer_auth_source","observerAuthSource"]].some(([e,t])=>W.touchedKeys.has(e)&&Ze(jt.value.renderState.values[t])!==W.baseline[e])}function cR(){const e=W.observerApply;if(!e)return;const t=e.active?.tierRoutingEnabled;e.state!=="active"||typeof t!="boolean"||W.observerTierRoutingExplicit||W.touchedKeys.has("observer_tier_routing_enabled")||P5()||(W.baseline.observer_tier_routing_enabled=t,GI({observerTierRoutingEnabled:t}))}function lR(e){if(!e||typeof e!="object")return;const t=e.observer_apply;!t||!["active","applying","failed"].includes(t.state)||(W.observerApply=t,cR(),zr({}))}function N5(){try{const e=sR({current:Fh({allowUntouchedParseErrors:!0}),baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:KI});return Object.keys(e).some(t=>W.restartRequiredKeys.has(t)&&!(t in W.envOverrides))}catch{return!1}}var T5=()=>C6({...zt().renderState.values,observerRuntime:Gs()?Uh():"api_http"},W.envOverrides),A5=()=>k6(zt().renderState.values),E5=()=>I6(zt().renderState.values),x5=()=>R6(zt().renderState.values),D5=()=>P6(zt().showAdvanced),{onTextInput:j5,onSelectValueChange:O5,onSwitchInput:L5}=C5({getTouchedKeys:()=>W.touchedKeys,getValues:()=>zt().renderState.values,updateFormState:GI,setDirty:e=>Od(e),onValuesChanged:cR});async function $5(){try{lR(await zP())}catch{Y("Observer settings could not be applied. Retry from Settings.","warning")}}async function M5(){try{lR(await qg()),WI(await Bg())}catch{Y("Observer status could not be refreshed. Try again.","warning")}}function F5(){const e=jt.value.renderState.observerStatus,t=W.observerApply;return a(U,{children:[a(U6,{status:e,onOpenDiagnostics:q5}),a(M6,{status:t,onRetry:()=>{$5()},onRefresh:()=>{M5()}})]})}function B5(){!W.startPolling||!W.refresh||(ra(W.startPolling,W.refresh),!zt().open&&(WG(),document.getElementById("tabBtn-feed")?.click(),JG()))}function q5(e){if(!W.startPolling||!W.refresh||(ra(W.startPolling,W.refresh),zt().open))return;const t=wl("settingsButton");queueMicrotask(()=>Tr({...e,trigger:t}))}function U5(){return{simple:String(W.effectiveConfig.observer_simple_provider??"").trim(),rich:String(W.effectiveConfig.observer_rich_provider??"").trim()}}function G5(){const e=jt.value,t=e.renderState.values,n=Array.from(new Set(e.renderState.providers.concat(t.observerProvider?[t.observerProvider]:[]))).sort((i,o)=>i.localeCompare(o)).map(i=>({label:i,value:i})),r={values:t,effectiveObserverRuntime:Uh(t.observerRuntime),hasExplicitObserverRuntime:Gs(t.observerRuntime),allowAutomaticAuthChanges:Z6(t.observerRuntime),tierProviders:U5(),observerMaxCharsDefault:String(y.configDefaults?.observer_max_chars||""),modelDefaults:W.observerModelDefaults??void 0,providerOptions:n,showAuthFile:t.observerAuthSource==="file",showAuthCommand:t.observerAuthSource==="command",showTieredRouting:t.observerTierRoutingEnabled,hiddenUnlessAdvanced:D5,onTextInput:j5,onSelectValueChange:O5,onSwitchInput:L5,getObserverModelLabel:A5,getObserverModelTooltip:E5,getObserverModelDescription:x5,getObserverModelHint:T5,protectedConfigHelp:T6};return a(S5,{panelProps:r,activeTab:e.activeTab,showAdvanced:e.showAdvanced,renderState:e.renderState,settingsDirty:e.dirty,restartRequired:N5(),onClose:()=>{W.startPolling&&W.refresh&&ra(W.startPolling,W.refresh)},onSave:()=>{W.startPolling&&W.refresh&&K5(W.startPolling,W.refresh)},onActiveTabChange:HI,onAdvancedToggle:E6,onShowGettingStarted:B5,observerStatusBannerSlot:a(F5,{})})}function H5(){return a(z6,{DialogContent:G5,onClose:ra})}function V5(){const e=Xe("settingsDialogMount");e&&ke(a(H5,{}),e)}function dR(){Xe("settingsDialogMount")&&(W.shellMounted||(V5(),W.shellMounted=!0))}function uR(e){Pi("settings-health"),W.shellMounted||dR(),Ld(!0),W.previouslyFocused=document.activeElement,e()}function ra(e,t){if(zt().dirty&&!globalThis.confirm("Discard unsaved changes?")){Ld(!0);return}Ld(!1),A6(),(W.previouslyFocused&&typeof W.previouslyFocused.focus=="function"?W.previouslyFocused:wl("settingsButton"))?.focus(),W.previouslyFocused=null,W.touchedKeys=new Set,e(),t()}async function K5(e,t){if(!zt().renderState.isSaving){zr({isSaving:!0,statusText:"Saving changes…"});try{const n=Fh({allowUntouchedParseErrors:!0}),r=sR({current:n,baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:KI});if(Object.keys(r).length===0){zr({isSaving:!1,statusText:"No unsaved changes"}),Od(!1),ra(e,t);return}const i=await JP(r),o=R5(i);zr({isSaving:!1,statusText:"Saved changes"}),Od(!1),ra(e,t),Y(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";zr({isSaving:!1,statusText:`Save failed: ${r}`})}}}function W5(e,t,n){W.startPolling=t,W.refresh=n,dR(),wl("settingsButton")?.addEventListener("click",()=>uR(e))}function z5(e){e.dataset.syncRenderRoot="preact"}function J5(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function lt(e,t){z5(e),ke(t,e)}function ia(e){e.dataset.syncRenderRoot==="preact"&&ke(null,e)}function Y5(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 X5(e){return typeof e=="object"&&e!==null}function Q5(e,t){return y.pairingCommandRaw="",{payloadText:e,hintText:t}}function Z5(e){if(!X5(e))return Q5("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 y.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function eJ(){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 tJ(){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 nJ(){const e=y.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 rJ(){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 iJ(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 oJ({items:e}){return a(U,{children:e.map((t,n)=>a("div",{class:"stat",children:a("div",{class:"stat-content",children:[a("div",{class:"value",children:t.value}),a("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function aJ({attempts:e,note:t}){return a(U,{children:[t?a("div",{class:"small",children:t}):null,e.map((n,r)=>a("div",{class:"diag-line",children:[a("div",{class:"left",children:[a("div",{children:[n.peerLabel," — ",n.status]}),n.detail?a("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?a("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null,n.action?a("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function pR({text:e}){return a(U,{children:e})}function sJ({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function cJ(e,t){if(!t.length){ia(e);return}lt(e,a(oJ,{items:t}))}function lJ(e,t,n){if(!t.length){ia(e);return}lt(e,a(aJ,{attempts:t,note:n}))}function Bi(e,t){lt(e,a(sJ,{...t}))}function fR(e,t,n){lt(e,a(pR,{text:n.payloadText})),t&<(t,a(pR,{text:n.hintText}))}function mR({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=x(null),f=x(null),p=x(!1);Ge(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),f.current&&(f.current.id=s)},[s,n,e]),q(()=>{if(!e){p.current=!1;return}p.current||(p.current=!0,queueMicrotask(()=>{f.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(es,{forceMount:!0,asChild:!0,children:a("div",{ref:f,id:s,className:c,hidden:!e,children:d})});return a(Za,{open:e,onOpenChange:t,children:[a(Zf,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?_n(m,l):m]})}function dJ({open:e,onOpenChange:t}){return a(mR,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[a("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),a("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),a("div",{className:"actor-create-row",children:[a("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),a(be,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),a("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),a("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),a("div",{className:"sync-ttl-group",children:[a("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),a(be,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),a("span",{children:"hours"})]}),a("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),a("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),a(Do,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),a("div",{className:"peer-meta",id:"syncInviteAdminHint"}),a("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function uJ({contentHost:e,open:t,onOpenChange:n}){return a(mR,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[a("div",{className:"peer-title",children:[a("strong",{children:"Pairing command"}),a("div",{className:"peer-actions",children:a("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),a("div",{className:"pairing-body",children:a("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),a("div",{className:"peer-meta",id:"pairingHint"})]})}function pJ(e,t){lt(e,a(dJ,{...t}))}function fJ(e,t){lt(e,a(uJ,{...t}))}function ce(e){return String(e??"").trim()}function mJ(e){return ce(e).replace(/\s+/g," ").toLowerCase()}function hJ(e){const t=ce(e);return t?t.slice(0,8):"Unnamed device"}function hR(e){return ce(e?.last_error).toLowerCase()}function gR(e){return e.includes("401")&&e.includes("unauthorized")}function vR(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var gJ={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function yR(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 vJ(e){const t=yR(e),n=ce(e.device?.device_id),r=Number(e.device?.address_count??0),i=Array.isArray(e.device?.addresses)&&e.device.addresses.some(o=>ce(o))||Number.isFinite(r)&&r>0;return!n||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":i}function Gh(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),o=wJ(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${o}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>bR(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=>bR(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:ce(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function bR(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=ce(e.error);return yJ(n)?"trust":bJ(n)?"scope":null}function yJ(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function bJ(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function _J(e){const t=ce(e?.reason);return gJ[t]??(t.replaceAll("_"," ")||"sync filters")}function wJ(e){const t=new Map;for(const n of e){const r=_J(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 _R(e){const t=ce(e.localName);if(t)return t;const n=ce(e.coordinatorName);return n||hJ(ce(e.deviceId))}function SJ(e){const t=ce(e.localName),n=ce(e.coordinatorName);return t||n?!1:!!ce(e.deviceId)}function CJ(e){const t=e.sync_health?.receive?.operations_24h??0,n=e.sync_health?.send?.operations_24h??0;return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Hs(e){const t=ce(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=hR(e);return gR(n)?"needs-repair":vR(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function Hh(e){const t=e?.status||{},n=ce(t.peer_state),r=hR(e),i=ce(t.sync_status)==="ok"||ce(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}:gR(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}:vR(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 kJ={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 IJ(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,o]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(o??0));if(s===0)continue;const c=i;r.push({reason:c,label:kJ[c]??i,count:s})}return r.sort((i,o)=>o.count-i.count||i.label.localeCompare(o.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function wR(e){return Array.isArray(e)?e.map(t=>ce(t)).filter(t=>!!t):[]}function SR(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 Ud(e,t){return e?e.replaceAll("_"," "):t}function RJ(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=ce(r.scope_id),o=ce(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[Ud(ce(r.kind),"user"),Ud(ce(r.authority_type),"local"),`${Ud(ce(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 PJ(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=ce(n.scope_id),i=ce(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=ce(n.last_applied_cursor),c=ce(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=Ud(ce(n.authority_type),"local"),u=Number(n.membership_epoch??0),f=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(p=>!!p).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:f}}).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 NJ=["personal","private","home","mine","me"],TJ=["oss","open source","opensource","community","public"],AJ=["work","client"],EJ=["local","legacy","review"];function xJ(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>ce(t)??"").join(" ").toLowerCase()}function DJ(e){return[e.scope_id,e.label,e.kind].map(t=>ce(t)??"").join(" ").toLowerCase()}function CR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vh(e,t){const n=xJ(e);return t.some(r=>{const i=CR(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function kR(e){return Vh(e,NJ)||Vh(e,TJ)}function jJ(e){const t=DJ(e);return EJ.some(n=>{const r=CR(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function OJ(e){return!kR(e)&&(!jJ(e)||Vh(e,AJ))}function LJ(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(ce(e.discovered_via_group_id)||ce(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(kR),r=t.some(OJ);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 $J(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function MJ(e){const t=wR(e?.effective_include),n=wR(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${SR(t,"all projects")}`,o=`Exclude filter: ${SR(n,"no exclusions")}`,s=$J(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:o,summary:`${r}. ${i}; ${o}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function FJ(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=ce(n?.display_name),i=ce(n?.actor_id),o=mJ(r);if(!r||!i||!o)return;const s=t.get(o)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(o,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function IR(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=ce(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const o=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>ce(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(ce(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var BJ=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),qJ=new Set(["pending","verifying","waiting"]);function UJ(e){return(Array.isArray(e?.groups)?e.groups.map(t=>ce(t)).filter(Boolean):[]).join(", ")||"none"}function GJ(e){return ce(e?.projects?.[0]?.display_name)||"the shared Project"}function HJ(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=Hh(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function VJ(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 KJ(e){return{status:e.status,coordinator:e.coordinator,peers:Array.isArray(e.peers)?e.peers:[],operations:Array.isArray(e.shareOperations)?e.shareOperations:[],reconciliationItems:Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],shareOperationsLoadError:e.shareOperationsLoadError===!0,label:UJ(e.coordinator)}}function WJ(e){if(e.status?.enabled===!1||e.coordinator?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${e.label}. 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: ${e.label}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const t=e.operations.find(r=>r.lifecycle?.state==="needs_attention"),n=e.reconciliationItems.find(r=>r.state==="needs_attention");return t?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."}:n?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access reconciliation needs review.`,nextAction:"Open Sharing, review this Project's access decision, then sync again."}:null}function zJ(e,t){if(e?.lifecycle?.state==="revoking")return`Keep both devices online, then sync again to finish removing future access for ${t}.`;const n=e?.lifecycle?.primary_action?.kind;return n==="retry_setup"?`Open Project sharing below and retry setup for ${t}.`:n==="copy_invite"?`Copy the invitation for ${t} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${t}.`}function JJ(e){const t=e.operations.find(o=>{const s=o.lifecycle?.state;return s!==void 0&&BJ.has(s)}),n=e.reconciliationItems.find(o=>{const s=o.state;return s!==void 0&&qJ.has(s)});if(!t&&!n)return null;const r=t?GJ(t):"the shared Project",i=t?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:i?"Removal pending":"Setup pending",meta:i?`Team: ${e.label}. Future access removal for ${r} is still pending.`:`Team: ${e.label}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:zJ(t,r)}}function YJ(e){return VJ(e.status)?{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${e.label}. 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."}:HJ(e.peers,e.coordinator)?{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${e.label}. 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."}:null}function XJ(e){const t=ce(e.coordinator?.presence_status);if(t==="not_enrolled")return{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${e.label}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."};if(t!=="posted"){const n=e.coordinator?.configured===!0;return{state:"unreachable",badgeLabel:n?"Unreachable":"Setup needed",meta:n?`Team: ${e.label}. 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:n?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}}return null}function QJ(e){const t=e.status?.sync_health;return{state:t?.state==="exchange_succeeded"?"healthy":"reachable",badgeLabel:jo(t),meta:Rm(t),nextAction:t?.state==="exchange_succeeded"?null:"Review Sending and Receiving on Devices, then retry sync."}}function RR(e){const t=KJ(e);return WJ(t)??JJ(t)??YJ(t)??XJ(t)??QJ(t)}function ZJ(e){return e.discovered?.stale?e.peer?Hs(e.peer)!=="connected":!0:!1}function PR(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 e9(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 t9(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 n9(e){const t=ce(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>ce(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 r9(e,t){const n=new Map,r=i=>{const o=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,o),o};return e.forEach(i=>{const o=ce(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=ce(i?.name)}),t.forEach(i=>{const o=ce(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=ce(i?.display_name)}),[...n.values()]}function i9(e){return e.map(t=>({id:`duplicate:${t.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:t.includesLocal?5:15,title:`Possible duplicate person: ${t.displayName}`,summary:t.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:t.actorIds}))}function o9(e,t){const n=ce(e.discovered?.fingerprint),r=ce(e.peer?.fingerprint);return!e.peer||!n||!r||n===r?null:PR({id:e.deviceId,name:t,title:`${t} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."})}function a9(e,t){if(!e.peer)return[];const n=[],r=Hs(e.peer),i=Hh(e.peer);return r==="needs-repair"&&n.push(PR({id:e.deviceId,name:t,title:i.state==="needs-repairing"?`${t} needs re-pairing`:`${t} needs review`,summary:i.description||"Sync needs review. Check device sync diagnostics, then retry."})),i.state==="trusted-by-you"&&n.push(e9({id:e.deviceId,key:"other-device-trust",name:t,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),SJ({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId})&&n.push(t9({id:e.deviceId,name:t,summary:"Give this device a friendly name so it is easier to recognize later."})),n}function s9(e){const t=_R({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId}),n=o9(e,t);return n?[n]:a9(e,t)}function c9(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=r9(n,r),o=e.duplicatePersonDecisions??{},s=FJ(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[...i9(s),...i.flatMap(s9)];return{primaryStatus:RR({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Hs(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>ZJ(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var NR={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 Yr(e){const t=document.getElementById(e);t&&t.remove()}var TR=!1;function l9(e){TR=e}var Kh=!1;function d9(e){Kh=e}var u9=new Set,Wh=new Set,zh=new Set,AR="codemem-sync-duplicate-person-decisions";function p9(e){const t=String(e||"").trim();t&&(Wh.add(t),zh.add(t),u9.add(t))}function Jh(e){const t=String(e||"").trim();return!!t&&Wh.has(t)}function f9(e){const t=String(e||"").trim();t&&Wh.delete(t)}function m9(e){const t=String(e||"").trim();return!t||!zh.has(t)?!1:(zh.delete(t),!0)}function Yh(){try{const e=localStorage.getItem(AR);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function ER(e){try{localStorage.setItem(AR,JSON.stringify(e))}catch{}}function xR(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function DR(){return Yh()}function h9(e,t){const n=xR(e);if(!n)return;const r=Yh();r[n]=t,ER(r)}function g9(e){const t=xR(e);if(!t)return;const n=Yh();delete n[t],ER(n)}function jR(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function OR(e){const t=String(e||"");return t?jR(t):""}function v9(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function y9(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Gd(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 Xh(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Gd(e)}function b9(e){return(Array.isArray(y.lastSyncPeers)?y.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function _9(){return IR({actors:y.lastSyncActors,peers:y.lastSyncPeers,duplicatePeople:y.lastSyncViewModel?.duplicatePeople}).visibleActors}function LR(e){return _9().filter(t=>String(t?.actor_id||"")!==e)}function w9(e,t){const n=LR(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Xh(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Qh(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=_l("div","sync-action"),i=_l("div","sync-action-text");i.textContent=n.label,i.appendChild(_l("span","sync-action-command",n.command));const o=_l("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Po(n.command,o)),r.append(i,o),e.appendChild(r)})}}function $R(e,t){return t&&e.error_redacted===!0}function S9(e){return e?{action:t=>Tr({severity:"error",subsystem:"sync",trigger:t})}:{}}function MR(){const e=document.getElementById("syncAttempts");if(!e)return;const t=y.lastSyncAttempts,n=String(y.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Bi(e,nJ());return}const r=iJ(n,t.slice(0,5).some(o=>o.status==="error")),i=t.slice(0,5).map(o=>{const s=o.started_at||o.started_at_utc||"",c=String(o.peer_device_id||"").trim(),l=Array.isArray(y.lastSyncPeers)?y.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",f=[],p=Ya();if(u&&o.error){const m=String(o.error);f.push(p?jR(m):m),$R(o,p)&&f.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&f.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!p&&o.address&&f.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:f.join(" · "),startedAt:s?sn(s):"",...S9(u),...$R(o,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});lJ(e,i,r)}function C9(){const e=document.getElementById("syncPrimaryStatusDetail");e&&(e.textContent="");const t=document.getElementById("syncStatusGrid"),n=document.getElementById("syncAttempts"),r=document.getElementById("syncMeta"),i=document.getElementById("syncActions");t&&Bi(t,tJ()),n&&Bi(n,rJ()),r&&(r.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."),Qh(i,[])}function oa(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function k9(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=oa(n.would_remove),o=oa(n.ambiguous),s=oa(r.applied),c=oa(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||o>0?`${o} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function I9(e){if(e.syncNoPeers)return[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:e.pending},{label:"Last sync",value:"Waiting for first peer"}];let t="Disabled";return e.retentionEnabled&&(t="Enabled"),e.retentionEnabled&&e.retentionLastRunAt&&(t=`${e.retentionDeleted.toLocaleString()} ops last run (approx)`),[{label:"State",value:e.daemonStateLabel},{label:"Pending events",value:e.pending},{label:"Last sync",value:e.lastSync?`${Ta(po(e.lastSync))} ago`:"never"},{label:"Last peer ping",value:e.lastPing?`${Ta(po(e.lastPing))} ago`:"never"},{label:"Retention",value:t}]}function FR(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Yr("syncDiagSkeleton");const r=y.lastSyncStatus;if(!r){Bi(e,eJ()),Qh(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},o=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=o.last_ping_at||r.last_ping_at||Y5(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",f=Number(r.pending||0),p=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),g=r.retention||{},b=r.cleanup_diagnostics,_=b?.stale_peer_rows??{},v=oa(_.would_remove),S=oa(_.ambiguous),w=g.enabled===!0,k=Number(g.last_deleted_ops||0),P=g.last_run_at||null,T=String(g.last_error||""),E={needs_attention:"Needs attention","offline-peers":"Offline peers",rebootstrapping:"Rebootstrapping"}[m]??yb(m),$=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,A=!$&&F===0;if(t){let H;$?H=["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"]:A?H=["Advanced sync is ready but idle","Pair another device from Devices, then return here for live peer status and recent attempts"]:H=[`Advanced state: ${E}`,`Peers: ${F}`,c?`Last sync: ${Ta(po(c))} ago`:"Last sync: never"],m==="offline-peers"&&H.push("All peers are currently offline; sync will resume automatically"),p&&m==="stopped"&&H.push(`Detail: ${p}`),p&&(m==="needs_attention"||m==="rebootstrapping")&&H.push(`Detail: ${p}`),w&&H.push(P?`Retention last ran ${Ta(po(P))} ago (approx oldest-first)`:"Retention enabled"),v>0?H.push(`${v.toLocaleString()} stale peer rows pending cleanup`):S>0&&H.push(`${S.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=H.join(" · ")}const j=$?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:f},{label:"Last sync",value:"Not running"}]:I9({daemonStateLabel:E,lastPing:l,lastSync:c,pending:f,retentionDeleted:k,retentionEnabled:w,retentionLastRunAt:P,syncNoPeers:A});!$&&!A&&(d||u)&&j.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!$&&!A&&s.seconds_since_last&&j.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!$&&!A&&o.seconds_since_last&&j.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!$&&w&&T&&j.push({label:T,value:"Retention"}),!$&&!A&&b&&j.push({label:"Cleanup",value:k9(b)}),cJ(e,j);const D=[];A||m==="offline-peers"||(m==="stopped"?(D.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),D.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?D.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?D.push({label:"Sync is rebuilding state in the background.",command:"codemem sync peers"}):d||u||m==="error"?(D.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),D.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!$&&!A&&f>0&&D.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!$&&S>0?D.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!$&&v>0&&D.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Qh(n,D)}var R9="syncRedactMount",P9="syncRedactLabel",BR=()=>{};function N9(e){BR=e}var Zh=()=>{};function eg(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;fJ(e,{contentHost:t,open:y.syncPairingOpen,onOpenChange:r=>{if(tF(r),eg(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&fR(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Zh()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=y.pairingCommandRaw;r&&await Po(r,n)})}function tg(){eg();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;fR(e,t,Z5(y.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!y.pairingCommandRaw)}function qR(){const e=document.getElementById(R9);e&<(e,h(Eo,{"aria-labelledby":P9,checked:Ya(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{nF(t),qR(),Zh(),FR(),BR(),MR(),tg()},thumbClassName:"sync-redact-switch-thumb"}))}function T9(e){Zh=e,eg(),qR()}var qi=new Map,ng=null,A9={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 E9(e){const t=e instanceof Error?e.message:String(e);return A9[t]??"Setup could not be retried. Review diagnostics for details."}function x9(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 D9(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function rg(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 j9({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=R(!1),[c,l]=R(()=>qi.get(e.operation_id)??null),d=x(null),u=e.lifecycle.primary_action;q(()=>{ng!==e.operation_id||!d.current||(ng=null,d.current.focus())},[c?.message,e.operation_id]);async function f(b){s(!0);try{let _=b;if(!_&&n){const S=(await n(e.operation_id)).lifecycle.primary_action;S?.kind==="copy_invite"&&(_=S.invite_link)}if(!_)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(S=>navigator.clipboard.writeText(S)))(_);const v={message:"Invite copied.",tone:"success"};qi.set(e.operation_id,v),l(v)}catch(_){const v={message:_ instanceof Error?_.message:"Invite could not be copied.",tone:"warning"};qi.set(e.operation_id,v),l(v)}finally{s(!1)}}async function p(){s(!0);try{const b=await t(e.operation_id),_=b.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:b.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${b.lifecycle.label}.`,tone:"success"};qi.set(e.operation_id,_),ng=e.operation_id,l(_),await r()}catch(b){const _={message:E9(b),tone:"warning"};qi.set(e.operation_id,_),l(_),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const b=e.projects.map(_=>_.project_id?.trim()).filter(_=>!!_);if(b.length!==e.projects.length){const _={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};qi.set(e.operation_id,_),l(_);return}if(!qc(b,e.person.display_name)){const _={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};qi.set(e.operation_id,_),l(_)}}function g(){if(u){if(u.kind==="copy_invite"){f(u.invite_link);return}if(u.kind==="retry_setup"){p();return}m()}}return a("section",{"aria-label":`${rg(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:rg(e.lifecycle.state)}),a("ul",{"aria-label":`${rg(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((b,_)=>a("li",{className:"peer-scope-chip",children:b.display_name},`${b.display_name}:${_}`))}),a("div",{className:"peer-scope-summary",children:e.lifecycle.label}),a("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?a("div",{className:"peer-actions",children:a("button",{"aria-busy":o,className:"settings-button",disabled:o,type:"button",onClick:g,children:o?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?a("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function O9({operations:e,...t}){const n=e[0].person,r=D9(e);return a("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[a("h3",{className:"device-row-name",children:n.display_name}),r.length>0?a("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>a("li",{children:i.display_name},i.device_id))}):null,e.map(i=>a(j9,{operation:i,...t},i.operation_id))]})}function L9(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:x9(e.operations).map(t=>a(O9,{...e,operations:t},t[0].person.actor_id))})}function $9(e,t){lt(e,a(L9,{...t}))}function UR({title:e,detail:t}){return a("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[a("strong",{children:e}),a("span",{children:t})]})}function M9(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 F9({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Gd(e),c=b9(o),l=LR(o),d=l.map(D=>String(D.actor_id||"")).join("|"),[u,f]=R(s),[p,m]=R(!1),[g,b]=R("Rename"),[_,v]=R(!1),[S,w]=R("Merge into selected person"),[k,P]=R(""),[T,E]=R(!1);q(()=>{f(s),m(!1),b("Rename"),v(!1),w("Merge into selected person"),P(""),E(!1)},[o,c,t,s,d]);const $=l.length?w9(k,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(D=>{const H=String(D.actor_id||"");return{label:D.is_local?Xh(D):Gd(D),value:H}})];async function A(){const D=u.trim();if(!D)return;m(!0),b("Saving…");let H=!1;try{await n(o,D),H=!0}catch{b("Retry rename")}finally{m(!1),H&&b("Rename")}}async function j(){if(!k)return;const D=l.find(V=>String(V.actor_id||"")===k);if(!D||!await Dn({title:`Merge ${s} into ${Gd(D)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;v(!0),w("Merging…");let H=!1;try{await r(k,o),H=!0}catch{w("Retry merge")}finally{v(!1),H&&w("Merge into selected person")}}return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:Xh(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?M9(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:a("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),a("div",{className:"actor-actions",children:e.is_local?a("div",{className:"peer-meta",children:"Rename yourself in config"}):a(U,{children:[a(be,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:p||_,type:"text",value:u,onInput:D=>f(D.currentTarget.value),onKeyDown:D=>ns(D,{onSubmit:()=>{A()},disabled:p||_||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:p||_,onClick:()=>{A()},children:g}),a("button",{type:"button",className:"settings-button danger",disabled:p||_,onClick:async()=>{await Dn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:p||_,onClick:()=>E(D=>!D),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?a(U,{children:[a("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),a("div",{className:"actor-merge-controls",children:[a(En,{ariaLabel:`Merge ${s} into another person`,disabled:_||l.length===0,onValueChange:P,options:F,placeholder:"Merge into person",triggerClassName:"actor-merge-select",value:k}),a("button",{type:"button",className:"settings-button",disabled:_||l.length===0||!k,onClick:()=>{j()},children:S})]}),a("div",{className:"peer-meta actor-merge-note",children:$})]}):null]})})]})}function B9({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(U,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(F9,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(UR,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function q9(e,t){lt(e,a(B9,{...t}))}function U9(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function G9(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${sn(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function H9({devices:e}){return a(U,{children:G9(e)})}function V9(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 K9(e){const t=U9(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ia(e.mount),ia(e.meta);return}const n=t.map(V9),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,lt(e.mount,a(En,{ariaLabel:"Legacy device",id:"syncLegacyDeviceSelect",onValueChange:e.onValueChange,options:n,value:r})),lt(e.meta,a(H9,{devices:t}))}function Xr({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}var W9="Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",z9="Review whether explicit Space access matches this device's intended role.";function J9(){return a("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[a("title",{children:"Chevron"}),a("path",{d:"m9 18 6-6-6-6"})]})}function Y9(e){switch(Hs(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Hd=null,GR=0,ig=new Set;function HR(e){if(Hd!==e){Hd=e,GR+=1;for(const t of ig)t(GR)}}function X9(){const[,e]=R(0);return q(()=>(ig.add(e),()=>{ig.delete(e)}),[]),Hd}var Q9={bidirectional:{glyph:"↕",label:"Applied and acknowledged operations observed (24h)"},publishing:{glyph:"↑",label:"Acknowledged operations observed (24h)"},subscribed:{glyph:"↓",label:"Applied operations observed (24h)"},none:null};function Z9(e){return e?`Initiated exchange: ${sn(e)}`:"Initiated exchange: not recorded"}function VR(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 eY(e,t,n,r=!1,i=!1,o=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||o&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${VR(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: ${VR(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 tY(e){y.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function nY(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 rY(){window.location.hash="advanced/teams/administration"}function og(e=y.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function iY({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),o=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||o,c=Hh(e),l=Q9[CJ(e)],d=e.status||{},u=RJ(e),f=Jh(i),p=f&&u.total===0,m=LJ(e),g=IJ(e),b=PJ(e),_=e.project_scope||{},v=MJ(_),S=v9(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(le=>String(le)))):[],k=Number(e.address_count??0),P=Number.isFinite(k)&&k>0?k:0,T=w.length?w.map(le=>Ya()?OR(le):le).join(" · "):P>0?`${P} ${P===1?"address":"addresses"} hidden`:"No addresses",E=y.lastDeviceIdentityInventory?.items.find(le=>le.deviceId===i||le.evidenceDeviceIds.includes(i)),$=eY(E,String(e.actor_id||"")||null,y.lastSyncActors,y.deviceIdentityInventoryLoadError,y.lastDeviceIdentityInventory?.truncated===!0,y.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),A=String(d.last_ping_at||d.last_ping_at_utc||""),j=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,D=m9(i),H=x(null),[V,z]=R(o),[M,C]=R(()=>y.syncPeerFeedbackById.get(i)??null),[O,B]=R(!1),[G,ne]=R("Save name"),[oe,te]=R(!1),[Me,pe]=R(!1),[Be,Te]=R("Remove device");q(()=>{f&&u.total>0&&f9(i)},[u.total,i,f]),q(()=>{z(o),C(y.syncPeerFeedbackById.get(i)??null),B(!1),ne("Save name"),te(!1),pe(!1),Te("Remove device")},[o,e.actor_id,i]),q(()=>{!D||!H.current||queueMicrotask(()=>H.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[D]);async function ae(){if(!i)return;const le=V.trim();if(!le){const kt={message:"Enter a friendly name for this device.",tone:"warning"};C(kt),y.syncPeerFeedbackById.set(i,kt),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}B(!0),ne("Saving…");try{const kt=await n(i,le);C(kt),y.syncPeerFeedbackById.set(i,kt),ne("Save name")}catch{ne("Retry")}finally{B(!1)}}async function _e(){if(p){const le=og();if(!await Dn({title:`Sync ${o} before advanced rule review?`,description:le?"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:le?"Review legacy Team/Space setup first":"Cancel"}))return}te(!0);try{const le=await r(e,S);C(le),le&&y.syncPeerFeedbackById.set(i,le)}finally{te(!1)}}async function Ce(){if(!i||!await Dn({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;pe(!0),Te("Removing…");let le=!1;try{await t(i,s),le=!0}catch{Te("Retry remove")}finally{pe(!1),le&&Te("Remove device")}}const Q=X9()===i&&i!=="",we=`device-drawer-${i||"unknown"}`,se=Y9(e),ot=Z9(F),ve=og(),Ot=`${Q?"Collapse":"Expand"} device ${o}`;return a(Za,{asChild:!0,open:Q,onOpenChange:le=>{le?HR(i):Hd===i&&HR(null)},children:a("div",{ref:H,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Zf,{asChild:!0,children:a("button",{"aria-label":Ot,className:"device-row-head device-row-head--trigger",type:"button",children:[a(jn,{state:se}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a(Ne,{variant:"badge",tone:c.isWarning?"badge-offline":"badge-online",children:c.badgeLabel}),p?a(Ne,{variant:"badge",tone:"actor-badge",children:"Review advanced rules"}):null,a(Ne,{variant:"badge",tone:u.isWarning?"badge-offline":"actor-badge",title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),g.badgeLabel?a(Ne,{variant:"badge",tone:"badge-offline",title:W9,children:g.badgeLabel}):null,m.badgeLabel?a(Ne,{variant:"badge",tone:"badge-offline",title:z9,children:m.badgeLabel}):null,e.discovered_via_group_id?a(Ne,{variant:"badge",tone:"actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:ot}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(J9,{})})]})}),a(es,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:we,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:oe,onClick:()=>{_e()},title:S?void 0:"Address details are hidden; sync will target this device by ID.",children:oe?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(be,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:O,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:V,onInput:le=>z(le.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:O,onClick:()=>{ae()},children:G}),a("button",{type:"button",className:"settings-button danger",disabled:Me,onClick:()=>{Ce()},children:Be})]}),a("div",{className:"peer-scope",children:[D?a("div",{className:"peer-meta",children:ve?"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."}):p?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:T}),j?a("div",{className:"peer-meta",children:j}):null,a("div",{className:"peer-meta",children:[ot,A?`Ping: ${sn(A)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(le=>a("li",{className:"peer-scope-chip",title:le.detail,children:le.label},le.scopeId))}):null,m.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:m.title}),a("div",{children:m.message}),a("div",{children:m.detail})]}):null,a("div",{className:"peer-meta",children:v.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:b.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":b.emptyMessage}),b.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:b.rows.map(le=>a("li",{title:le.detail,children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:`badge ${le.status==="received"?"badge-online":"actor-badge"}`,children:le.badgeLabel})]},le.scopeId))}):null,g.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":g.total,children:[a("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),a("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),a("ul",{className:"peer-scope-rejections-list",children:g.reasons.map(le=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:"peer-scope-rejection-count",children:le.count.toLocaleString()})]},le.reason))}),g.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",sn(g.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:$.summary}),a("div",{className:"peer-meta",children:$.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:nY(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>tY(E?.deviceId??i),children:$.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[v.statusLabel,". ",v.summary," ",v.note]}),ve?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:rY,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(Xr,{feedback:M})]})]})]})})}function oY(e){const t=y.syncPeersSectionFeedback,n=y.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(U,{children:[a(Xr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(iY,{peer:i,...e},o)})]}):a(U,{children:[a(Xr,{feedback:t}),a(UR,{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 aY(e,t){lt(e,a(oY,{...t}))}var Qr=async()=>{},Vd="";function ag(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function sY(e){Qr=e}function cY(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Yr("syncActorsSkeleton"),ag(!1);const n=IR({actors:y.lastSyncActors,peers:y.lastSyncPeers,duplicatePeople:y.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.`)),q9(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await jT(i,o),await Qr()},onMerge:async(i,o)=>{try{await uv(i,o),Y("People combined. Assigned devices moved to the selected person."),await Qr()}catch(s){throw Y(ft(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await OT(i),Y("Person removed. Assigned devices have been unassigned."),await Qr()}catch(o){throw Y(ft(o,"Failed to remove person."),"warning"),o}}})}function lY(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");ag(!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&&Bi(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function dY(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;$9(e,{operations:y.lastShareOperations,onAdvance:n=>kT(n),onLoadOperation:n=>CT(n),onReload:Qr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=y.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":y.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function sg(){const e=document.getElementById("syncPeers");if(!e)return;Yr("syncPeersSkeleton");const t=y.lastSyncPeers,n=Array.isArray(t)?t:[];y9(y.syncPeersSectionFeedback,n)&&(y.syncPeersSectionFeedback=null),aY(e,{peers:n,onRename:async(r,i)=>{try{return await Xg(r,i),await Qr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:ft(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await Tu({address:i,peerDeviceId:o||void 0}),c=Gh(s);let l;c.ok?o&&Jh(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${og()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await Qr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(o){return{message:ft(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Yg(r);const o={message:`Removed peer ${i}.`,tone:"success"};return y.syncPeerFeedbackById.delete(r),y.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await Qr(),o}catch(o){return{message:ft(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function uY(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");ag(!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&&Bi(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&&Bi(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 KR(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(y.lastSyncLegacyDevices)?y.lastSyncLegacyDevices:[];K9({devices:r,meta:n,mount:t,onValueChange:i=>{i!==Vd&&(Vd=i,KR())},panel:e,value:Vd})}function pY(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{ns(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){gi(n,"Enter a name for the person.");return}za(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await DT(i),Y("Person created."),n.value="",await e()}catch(o){Y(ft(o,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(Vd||"").trim();if(!i||!r||!await Dn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const o=r.textContent||"Attach device history";r.textContent="Attaching…";try{await LT(i),Y("Old device history attached to you."),await e()}catch(s){Y(ft(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function fY(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function cg(e=fY()){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 WR=!1;function mY(){WR||(WR=!0,window.addEventListener("hashchange",()=>{cg()}))}var Mn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function hY(e){Mn.loadSyncData=e}var gY=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function vY(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=y.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 lg(){const e=document.getElementById("syncAdminDisclosureMount");e&&pJ(e,{open:TR,onOpenChange:t=>{l9(t),lg(),Wd(),dg()}})}function zR(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function dg(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(y.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(y.lastTeamInvite?.warnings)?y.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Kd(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=y.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 Wd(){const e=document.getElementById("syncInvitePolicyMount");e&<(e,h(En,{ariaLabel:"Join policy",id:"syncInvitePolicy",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==Mn.invitePolicy&&(Mn.invitePolicy=n,Wd())},options:gY,value:Mn.invitePolicy}))}function yY(e){const t=(e.projects??[]).map(n=>`${n.display_name} (${n.existing_memory_count} existing ${n.existing_memory_count===1?"memory":"memories"})`).join(", ");return`${e.inviter_name||"A teammate"} invited you${e.team_name?` through ${e.team_name}`:""} to share ${t||"selected projects"}.`}function bY(e){if(!e.length){Y("Invite created. Copy the text above and share it with your teammate.","success");return}const t=e.length===1?"1 warning":`${e.length} warnings`;Y(`Invite created. Copy it above and review ${t}.`,"warning")}function _Y(e){const t=e;if(!(t.restart_required===!0||t.setup_state==="pending_inviter"||e.status==="pending_setup"))return{message:"Project invitation accepted.",tone:"success"};const n=typeof t.detail=="string"?t.detail.trim():"";let r="Project invitation accepted. Setup is still pending.";return t.restart_required===!0?r="Project invitation accepted. Restart codemem to finish setup.":t.setup_state==="pending_inviter"&&(r="Project invitation accepted. Waiting for the inviter to finish setup."),{message:n||r,tone:"warning"}}function wY(e){const t=e;if(t.type==="project_share")return _Y(e);if(t.type==="pair"){const n=String(t.peer_device_id??"").trim();return{message:n?`Paired with device ${n.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}return{message:e.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"}}function SY(e,t){lg(),Wd();const n=document.getElementById("operationStatusRoot");n&&Zp(n);const r=document.getElementById("syncNowButton"),i=document.getElementById("syncShareProjectsButton"),o=document.getElementById("syncCreateInviteButton"),s=document.getElementById("syncInviteGroup"),c=document.getElementById("syncInviteTtl"),l=document.getElementById("syncInviteOutput"),d=document.getElementById("syncJoinButton"),u=document.getElementById("syncJoinInvite"),f=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),m=document.getElementById("syncProjectInviteReviewHeading"),g=document.getElementById("syncRecipientName"),b=document.getElementById("syncRecipientDeviceName");let _="",v,S=0;const w=document.getElementById("syncPairingReview"),k=["syncPairingDeviceId","syncPairingFingerprint","syncPairingAddresses"].map(F=>document.getElementById(F)),P=()=>{w&&(w.hidden=!0);for(const F of k)F&&(F.textContent="")},T=F=>{if(!w||k.some(j=>!j))throw new Error("Pairing review unavailable. Refresh and try again.");const A=[F.device_id,F.fingerprint,F.addresses.join(`
|
|
121
|
-
`)];k.forEach((j,D)=>{j&&(j.textContent=A[D]??"")}),w.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},E=(F,A)=>A===S&&u?.value.trim()===F;i?.addEventListener("click",()=>{qc()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const $=async(F,A)=>{const j=await Jg(F);return E(F,A)?(v=j.kind,j.kind==="pair"?(T(j),"other"):j.kind!=="project_share_invite"||!f||!g||!b?"other":(p&&(p.textContent=yY(j)),g.value=mo(j.recipient_name),b.value=mo(j.device_name),f.hidden=!1,_=F,d&&(d.textContent="Accept and start syncing"),m?.focus(),"project")):"stale"};u?.addEventListener("input",()=>{S+=1,u.value.trim()!==_&&(_="",v=void 0,f&&(f.hidden=!0),P(),d&&(d.textContent="Review invite"))}),o?.addEventListener("click",async()=>{if(!o||!s||!c||!l||o.disabled)return;const F=s.value.trim(),A=Number(c.value);let j=!0;if(F?za(s):j=gi(s,"Team name is required."),!A||A<1?j=gi(c,"Must be at least 1 hour."):za(c),!!j){o.disabled=!0,o.textContent="Creating…";try{const D=await Vg({group_id:F,policy:Mn.invitePolicy,ttl_hours:A||24});y.lastTeamInvite=D,dg(),l.value=String(D.encoded||""),l.hidden=!1,l.focus(),l.select(),bY(Array.isArray(D.warnings)?D.warnings:[])}catch(D){Y(ft(D,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),o.textContent="Retry",o.disabled=!1;return}finally{o.disabled&&(o.disabled=!1,o.textContent="Create invite")}}}),u?.addEventListener("keydown",F=>{ns(F,{onSubmit:()=>d?.click(),disabled:!d||d.disabled})}),d?.addEventListener("click",async()=>{if(!d||!u||d.disabled)return;const F=u.value.trim();if(!F){gi(u,"Paste a team invite or pairing payload.");return}if(za(u),_!==F){const j=S;d.disabled=!0;try{const D=await $(F,j);if(D==="project"||D==="stale")return}catch(D){if(!E(F,j))return;gi(u,ft(D,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{d.disabled=!1}if(!E(F,j))return;_=F,d.textContent="Accept invite";return}const A=f&&!f.hidden?{recipient_name:g?.value.trim()??"",device_name:b?.value.trim()??""}:void 0;if(A){const j=D=>mo(D)==="";if(j(A.recipient_name)){g&&gi(g,"Enter a human-readable name using 120 characters or fewer.");return}if(j(A.device_name)){b&&gi(b,"Enter a human-readable device name using 120 characters or fewer.");return}}d.disabled=!0,d.textContent="Accepting…";try{const j=await Su(F,A,v);y.lastTeamJoin=j;let D=wY(j);y.syncJoinFlowFeedback=D,Kd(),u.value="",S+=1,_="",v=void 0,P(),f&&(f.hidden=!0);try{await t()}catch(H){D={message:ft(H,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},y.syncJoinFlowFeedback=D,Kd()}}catch(j){y.syncJoinFlowFeedback={message:ft(j,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Kd(),d.textContent="Retry",d.disabled=!1;return}finally{d.disabled&&(d.disabled=!1,d.textContent="Review invite")}}),CY(r,e)}function CY(e,t){let n=!1;e&&(e.disabled=y.viewerActorId===null||e.getAttribute("aria-busy")==="true"),e?.addEventListener("click",async()=>{if(!e||n||e.disabled)return;const r=y.viewerActorId;if(r===null)return;n=!0,e.disabled=!0,e.setAttribute("aria-busy","true"),e.textContent="Syncing…";const i=SL("Syncing devices…","You can keep browsing."),o=(c,l)=>{i?i.finish(c,l):Y(c,l)};let s=!1;try{const c=await Tu();if(!IY(c)||r!==y.viewerActorId)throw new Error("Unconfirmed sync result");const l=Gh(c);o(l.message,l.warning?"warning":"success"),s=!0}catch(c){o(kY(c,r),"warning")}finally{n=!1,e.disabled=y.viewerActorId===null,e.removeAttribute("aria-busy"),e.textContent="Sync now"}s&&t()})}function kY(e,t){return t===y.viewerActorId&&e instanceof Error&&e.message==="sync_disabled"?"Sync is disabled. Enable device sync in Settings before trying again.":"Couldn’t confirm whether sync finished. Check device sync status before retrying."}function IY(e){return!e||typeof e!="object"||!("items"in e)||!Array.isArray(e.items)?!1:e.items.every(t=>t&&typeof t=="object"&&typeof t.peer_device_id=="string"&&typeof t.ok=="boolean"&&ug(t.opsIn)&&ug(t.opsOut)&&(t.opsSkipped===void 0||ug(t.opsSkipped))&&(t.error===void 0||typeof t.error=="string")&&Array.isArray(t.addressErrors))}function ug(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function RY({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(jn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ne,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state!=="needs-attention"?a(ZS,{health:y.lastSyncStatus?.sync_health}):a("div",{className:"advanced-sync-status-label",children:[a(jn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ne,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function pg({element:e,hidden:t=!1,restoreParent:n=null}){const r=x(null);return Ge(()=>{e&&(e.hidden=t)},[e,t]),Ge(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function PY({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(U,{children:[a("div",{className:"sync-action",children:a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide team setup":"Set up a new team instead"})}),e?a(pg,{element:e,hidden:!t,restoreParent:n}):null]})}function NY({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(U,{children:[c?a(U,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(pg,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(U,{children:[r?a(pg,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(PY,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function zd({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function TY({item:e,onAction:t}){const[n,r]=R(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function AY({request:e,onApprove:t,onDeny:n}){const[r,i]=R(null),[o,s]=R(null),[c,l]=R("Approve"),[d,u]=R("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(Xr,{feedback:o})]})}function EY({onReview:e,row:t}){const[n,r]=R(!1),[i,o]=R(null),s=t.actionLabel||"Pair with this device",[c,l]=R(s);return a(U,{children:[a("button",{"aria-label":`${c} for ${t.displayName}`,className:"settings-button",disabled:n,onClick:async()=>{r(!0),l("Pairing…"),o({message:`Pairing ${t.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const d=await e(t)||null;o(d),l(d?.tone==="warning"?"Retry":t.actionLabel||s)}catch{o({message:`Pairing ${t.displayName} failed. Try again.`,tone:"warning"}),l("Retry")}finally{r(!1)}},type:"button",children:c}),a(Xr,{feedback:i})]})}function xY({onInspect:e,onRemove:t,row:n}){const[r,i]=R(!1),[o,s]=R(null),[c,l]=R("Remove broken device record");return a(U,{children:[a("button",{"aria-label":`Open details for ${n.displayName}`,className:"settings-button",disabled:r,onClick:()=>e(n),type:"button",children:"Open device details"}),a("button",{"aria-label":`${c} for ${n.displayName}`,className:"settings-button danger",disabled:r,onClick:async()=>{i(!0),l("Removing…");try{s(await t(n)||null),l("Remove broken device record")}catch{l("Retry")}finally{i(!1)}},type:"button",children:c}),a(Xr,{feedback:o})]})}function DY({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a(Ne,{variant:"badge",tone:e.availabilityLabel==="Offline"?"actor-badge":"actor-badge local",children:e.availabilityLabel}),a(Ne,{variant:"badge",tone:"actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a(Ne,{variant:"badge",tone:"actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(EY,{onReview:r,row:e}):null,e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(xY,{onInspect:t,onRemove:n,row:e}):null]})]})}function jY(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(U,{children:[r?a(zd,{label:"Needs attention"}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(TY,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null]})}function OY({children:e}){return e?a(U,{children:[a(zd,{label:"Add devices & teammates"}),e]}):null}function LY({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!y.syncDiscoveredFeedback?null:_n(a(U,{children:[a(zd,{count:t.length||void 0,label:"Devices waiting for review"}),a(Xr,{feedback:y.syncDiscoveredFeedback}),t.map(o=>a(DY,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function $Y({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!y.syncJoinRequestsFeedback?null:_n(a(U,{children:[a(zd,{count:t.length||void 0,label:"Join requests to review"}),a(Xr,{feedback:y.syncJoinRequestsFeedback}),t.map(i=>a(AY,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function JR(e){return a(U,{children:[a(jY,{...e}),a(OY,{children:e.children}),a($Y,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(LY,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function YR(e){e&&(e.textContent="")}function Jd(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 MY(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vs(){return MY()?"auto":"smooth"}var fg="syncTeamActionsMount",FY="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function BY(e,t,n=!1){return e.length>1&&(!t||n)}function qY(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 UY(e,t){const n=document.createElement("div");n.id=fg,e.appendChild(n),lt(n,h(JR,{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 XR(e,t){const n=document.getElementById(fg);n&&(ia(n),n.remove()),YR(e),t.forEach(r=>{YR(r)})}function GY(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");XR(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,UY(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function Ks(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;lg(),Wd(),dg(),Kd(),vY();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Yr("syncTeamSkeleton"),zR();const f=y.lastSyncCoordinator,p=VY();HY(p.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},g=C=>{if(m(),C.kind==="possible-duplicate-person"){const ne=document.getElementById("syncActorsList");ne instanceof HTMLElement&&(ne.scrollIntoView({block:"center",behavior:Vs()}),Jd(ne));return}const O=String(C.deviceId||"").trim();if(!O)return;if(C.kind==="name-device"){const ne=document.querySelector(`[data-device-name-input="${CSS.escape(O)}"]`);if(ne instanceof HTMLInputElement){ne.scrollIntoView({block:"center",behavior:Vs()}),ne.focus(),ne.select(),Jd(ne);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(O)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:Vs()}),Jd(B);return}const G=document.querySelector(`[data-discovered-device-id="${CSS.escape(O)}"]`);G instanceof HTMLElement&&(G.scrollIntoView({block:"center",behavior:Vs()}),Jd(G))},b=async C=>{const O=Array.isArray(C.actorIds)?C.actorIds.map(te=>String(te||"").trim()).filter(Boolean):[],B=(Array.isArray(y.lastSyncActors)?y.lastSyncActors:[]).filter(te=>O.includes(String(te?.actor_id||"").trim()));if(B.length<2){Y("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const G=await p2({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(te=>({actorId:String(te?.actor_id||""),label:String(te?.display_name||te?.actor_id||"Unknown person"),isLocal:!!te?.is_local}))});if(G.action==="different-people"){h9(O,"different-people"),Y("Okay. I will keep these people separate on this device."),await Mn.loadSyncData();return}if(G.action!=="merge")return;const ne=B.find(te=>String(te?.actor_id||"")===G.primaryActorId),oe=B.find(te=>String(te?.actor_id||"")===G.secondaryActorId);if(!ne?.actor_id||!oe?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await uv(String(ne.actor_id),String(oe.actor_id)),g9(O),Y(`Combined duplicate people into ${String(ne.display_name||ne.actor_id)}.`),await Mn.loadSyncData()}catch(te){try{await Mn.loadSyncData()}catch{}Y(ft(te,"Failed to combine these people."),"warning")}},_=async C=>await mm({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:C,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:O=>O.trim()?null:"Enter a device name to pair this device."}),v=!!f?.configured,S=n9(f);e.title=v?String(f.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?qY(w,e,p.primaryStatus):e.textContent=p.primaryStatus.meta,!v){GY({actions:n,setupPanel:t,primaryStatus:p.primaryStatus});return}t.hidden=!0,n.hidden=!1;const k=String(f.presence_status||""),P=Array.isArray(y.lastSyncPeers)?y.lastSyncPeers:[],T=Array.isArray(p.attentionItems)?p.attentionItems:[],E=Array.isArray(f.discovered_devices)?f.discovered_devices:[],$=String(f.coordinator_url||"").trim(),F=E.map(C=>{const O=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),G=_R({coordinatorName:B,deviceId:O})||"Discovered device",ne=O&&G!==O?O:null,oe=String(C.fingerprint||"").trim(),te=String(C.incoming_reciprocal_request_id||"").trim(),Me=Array.isArray(C.groups)?C.groups.map(vr=>String(vr||"").trim()).filter(Boolean):[],pe=P.find(vr=>String(vr?.peer_device_id||"")===O),Be=BY(Me,!!pe,C.needs_local_approval===!0),Te=yR({device:C,pairedLocally:!!pe}),ae=String(pe?.fingerprint||"").trim(),_e=!!pe&&!!oe&&!!ae&&ae!==oe,Ce=y.pendingCoordinatorApprovalsByDeviceId.get(O),Q=C.needs_local_approval===!0&&Ce?.coordinatorUrl===$&&Ce?.incomingRequestId===te,we=Q?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",se=!Q&&!S&&vJ({device:C,hasAmbiguousCoordinatorGroup:Be,pairedLocally:!!pe}),ot=Array.isArray(C.addresses)?C.addresses:[],ve=Number(C.address_count??0),Ot=Number.isFinite(ve)&&ve>0?ve:0,at=WY({pairedLocally:!!pe,device:C,addressCount:ot.length+Ot}),le=[ot.length?ot.map(vr=>Ya()?OR(String(vr||"")):String(vr||"")).filter(Boolean).join(" · "):Ot>0?`${Ot} ${C.stale?"last-known":"fresh"} ${Ot===1?"address":"addresses"} hidden`:"No fresh addresses"];!ot.length&&ne&&le.push(`device id: ${O}`);let kt=null,tt=se?"accept":"none",Xs=null;_e?tt="conflict":Q?(kt="Waiting for refreshed coordinator status. You do not need to approve again.",tt="approval-pending"):S&&(!pe||Te.state==="needs-your-approval")?(kt=S.message,tt="setup-blocked"):Be?(kt="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",tt="ambiguous"):at?(kt=at.actionMessage,tt=at.mode):pe&&Jh(O)?(kt="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",tt="scope-pending"):pe?.last_error?(le.push(`error: ${String(pe.last_error)}`),se||(tt="paired")):pe?.status?.peer_state?(le.push(`status: ${String(pe.status.peer_state)}`),se||(tt="paired")):pe&&!se&&(tt="paired"),tt==="paired"&&(Xs=zY(Te.state,Te.description,pe?.last_error));const Qs=JY(_e,!!pe);return{actionMessage:kt,actionLabel:Te.actionLabel||(pe?"Review device":"Pair with this device"),approvalBadgeLabel:Q?"Approval sent":Te.badgeLabel,approvalState:we,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:Qs,coordinatorUrl:$,deviceId:O,displayName:G,displayTitle:ne,fingerprint:oe,groupId:Me[0]??"",incomingRequestId:te,mode:tt,note:le.join(" · "),pairedMessage:Xs}}),A=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),j=T.filter(C=>!C.deviceId||!A.has(C.deviceId)),D=[],H=F.filter(C=>C.mode!=="paired"&&C.mode!=="none"&&C.mode!=="scope-pending"),V=F.filter(C=>C.mode==="accept"||C.mode==="scope-pending").length,z=j.length+D.length+V;l&&(l.hidden=H.length===0&&!y.syncDiscoveredFeedback),d&&(d.textContent=H.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=D.length===0&&!y.syncJoinRequestsFeedback),XR(n,[c,u]);const M=document.createElement("div");M.id=fg,n.appendChild(M),lt(M,h(JR,{actionItems:j,actionableCount:z,children:h(NY,{invitePanel:r,invitePanelOpen:Kh,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(d9(!Kh),Ks())},presenceStatus:k}),discoveredListMount:u,discoveredRows:H,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async C=>{if(C.kind==="possible-duplicate-person"){await b(C);return}g(C)},onDenyJoinRequest:async()=>null,onInspectConflict:C=>{m();const O=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(O instanceof HTMLElement){O.scrollIntoView({block:"center",behavior:Vs()}),Y(`Opened the conflicting local device record for ${C.displayName}.`,"warning");return}Y("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async C=>{if(!await Dn({title:`Remove ${C.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 Yg(C.deviceId);const O={message:`Removed the broken local device record for ${C.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return y.syncDiscoveredFeedback=O,await Mn.loadSyncData(),O}catch(O){return{message:ft(O,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async C=>{try{const O=await _(C.displayName);return O?await KY(C,O):null}catch(O){return{message:ft(O,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:D,presenceStatus:k,primaryStatus:p.primaryStatus}))}function HY(e){const t=document.getElementById("syncAdvancedStatusMount");t&<(t,h(RY,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function VY(){return y.lastSyncViewModel||{primaryStatus:RR({status:y.lastSyncStatus,coordinator:y.lastSyncCoordinator,peers:y.lastSyncPeers,shareOperations:y.lastShareOperations,shareOperationsLoadError:y.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function KY(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await VN(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&y.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(y.pendingAcceptedSyncPeers)?y.pendingAcceptedSyncPeers.filter(f=>String(f?.peer_device_id||"").trim()!==e.deviceId):[];y.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],p9(e.deviceId);let u=n?{message:FY,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"};y.syncDiscoveredFeedback=u,n&&Ks();try{t.trim()!==l.trim()&&(await Xg(e.deviceId,t.trim()),y.pendingAcceptedSyncPeers=y.pendingAcceptedSyncPeers.map(f=>String(f?.peer_device_id||"").trim()===e.deviceId?{...f,name:t.trim()}:f),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(f){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ft(f,"Device connected, but naming did not finish."),tone:"warning"}}y.syncDiscoveredFeedback=u;try{await Mn.loadSyncData()}catch(f){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ft(f,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},y.syncDiscoveredFeedback=u}return u}function WY({pairedLocally:e,device:t,addressCount:n}){return e&&t.needs_local_approval!==!0?null:t.stale?{actionMessage:"Wait for a fresh coordinator presence update, then review this device again here.",mode:"stale"}:e||n>0?null:{actionMessage:"Wait for this device to publish a fresh address, then refresh and review it.",mode:"waiting-address"}}function zY(e,t,n){if(e==="waiting-for-other-device")return t||"Waiting on the other device.";const r=String(n||"").toLowerCase();return r.includes("401")&&r.includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null}function JY(e,t){return e?NR.conflicts:t?NR.pairedLocally:"Not connected on this device"}function YY(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 aa(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function QR(e){return aa(e)?"Unclear project identity":e.displayProject}function rn(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function XY(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function QY(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ZY(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function e8(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function t8(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 n8(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function r8({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",t8(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:n8(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function ZR(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${QY(t)}\\b`,"g"),ZY(t,n))),r}function i8(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 o8({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function a8({group:e,disabled:t,onChange:n,scopes:r,value:i}){const o=ht();return a("label",{className:"legacy-review-target",htmlFor:o,children:[a("span",{children:"Destination Space"}),a(Pn,{className:"peer-scope-input",disabled:t,id:o,onChange:s=>n(e,s.currentTarget.value),value:i,children:[a("option",{value:"",children:"Choose Space…"}),r.map(s=>a("option",{value:s.scopeId,children:[s.label," · ",e8(s.authorityType),s.scopeId===e.suggestedScopeId?" · suggested":""]},s.scopeId))]})]})}function s8({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=R({}),[l,d]=R({}),[u,f]=R(o),[p,m]=R({}),[g,b]=R("all"),[_,v]=R(""),[S,w]=R(null),k=r.length,P=e.totalGroupCount??k,T=r.filter(aa).length,E=r.filter(C=>C.suggestedScopeId&&!aa(C)&&rn(C)).length,$=r.filter(C=>p[C.workspaceIdentity]&&rn(C)).length,F=r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).length,A=r.filter(C=>{const O=aa(C);return g==="suggested"&&(!C.suggestedScopeId||O)||g==="cleanup"&&!O||g==="no-suggestion"&&(C.suggestedScopeId||O)||g==="selected"&&!p[C.workspaceIdentity]?!1:!_.trim()||i8(C,i).includes(_.trim().toLowerCase())});async function j(C){const O=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!O||!t||S)){w(C.workspaceIdentity),d(B=>{const G={...B};return delete G[C.workspaceIdentity],G});try{const B=await t(C,O,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?G=>({...G,[C.workspaceIdentity]:B}):G=>{const ne={...G};return delete ne[C.workspaceIdentity],ne})}catch(B){d(G=>({...G,[C.workspaceIdentity]:ZR(B,O,i)}))}finally{w(null)}}}function D(C,O){f(B=>({...B,[C.workspaceIdentity]:O})),c(B=>{const G={...B};return delete G[C.workspaceIdentity],G}),d(B=>{const G={...B};return delete G[C.workspaceIdentity],G})}function H(C,O){m(B=>({...B,[C.workspaceIdentity]:O}))}function V(C){m(O=>({...O,...Object.fromEntries(A.filter(rn).map(B=>[B.workspaceIdentity,C]))}))}function z(){m(C=>({...C,...Object.fromEntries(r.filter(O=>O.suggestedScopeId&&!aa(O)&&rn(O)).map(O=>[O.workspaceIdentity,!0]))}))}async function M(){if(!t||S||F===0)return;const C=r.filter(O=>p[O.workspaceIdentity]&&rn(O)&&!!u[O.workspaceIdentity]);if(!C.every(O=>s[O.workspaceIdentity])){w("bulk");try{for(const O of C){if(s[O.workspaceIdentity])continue;const B=u[O.workspaceIdentity]||O.suggestedScopeId||"";if(B)try{const G=await t(O,B,!1);d(ne=>{const oe={...ne};return delete oe[O.workspaceIdentity],oe}),G&&c(ne=>({...ne,[O.workspaceIdentity]:G}))}catch(G){d(ne=>({...ne,[O.workspaceIdentity]:ZR(G,B,i)}))}}}finally{w(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[P.toLocaleString()," older"," ",P===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",k<P?` Showing ${k.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${k.toLocaleString()}`],["suggested",`Suggested ${E.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,O])=>a("button",{className:g===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:O},C))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>v(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:_}),a("button",{className:"settings-button",onClick:()=>V(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:z,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>V(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:S!=null||F===0||r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{M()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&$>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:A.map(C=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${QR(C)}`,checked:!!p[C.workspaceIdentity],className:"cm-checkbox",disabled:!rn(C),onChange:O=>H(C,O.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:QR(C)}),a("div",{className:"legacy-review-group-meta",children:[YY(C.identitySource),XY(C,i)]}),rn(C)?C.peerOwnedMemoryCount?a("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:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),aa(C)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?a("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?a("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,a(r8,{group:C}),i.length>0&&t&&rn(C)?a(a8,{group:C,disabled:S!=null,onChange:D,scopes:i,value:u[C.workspaceIdentity]||""}):null,i.length>0&&t&&rn(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{j(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function c8({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(U,{children:[t?a(s8,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(o8,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function l8(){xf("mine"),y.feedQuery="",window.location.hash="feed"}function d8(){window.location.hash="projects"}async function u8(e,t,n,r){try{const i=await AT({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return y.lastSyncLegacySharedReview=i.legacy_shared_review??null,Y(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),eP(),null}catch(i){if(i instanceof Zg)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function eP(){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(y.lastSyncSharingReview)?y.lastSyncSharingReview:[],o=y.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const f=u;return{displayProject:String(f.display_project||f.project||"Unknown project"),identitySource:String(f.identity_source||"unknown"),lastUpdatedAt:typeof f.last_updated_at=="string"?f.last_updated_at:null,memoryCount:Number(f.memory_count||0),memorySamples:Array.isArray(f.memory_samples)?f.memory_samples.map(p=>{const m=p,g=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:g,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(f.peer_owned_memory_count||0),reassignableMemoryCount:Number(f.reassignable_memory_count||0),suggestedScopeId:typeof f.suggested_scope_id=="string"?f.suggested_scope_id:null,suggestionReason:typeof f.suggestion_reason=="string"?f.suggestion_reason:null,workspaceIdentity:String(f.workspace_identity||f.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const f=u;return{authorityType:String(f.authority_type||"unknown"),label:String(f.label||f.scope_id||"Unknown domain"),scopeId:String(f.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){ia(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=y.currentProject?`current project (${y.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));lt(n,h(c8,{items:d,legacyReview:c,onLegacyReassign:u8,onLegacyReview:d8,onReview:l8}))}var Ws="";function p8(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of y.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){y.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||y.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function f8(){return[...y.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var sa=null,mg=0,hg=null,gg=0,vg=null,m8=15e3;function tP(e){return`project:${e||""}|includeJoinRequests:false`}function h8(e){const t=tP(e);return!sa||sa.key!==t||Date.now()>=sa.expiresAtMs?null:sa.payload}function g8(e,t){sa={key:tP(e),expiresAtMs:Date.now()+m8,payload:t}}function v8(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function y8(){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 b8(e,t){if(y.activeTab==="health"&&!t.requireFreshSyncStatus){const r=h8(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!Ya();return{payload:await sc(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function _8(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}function w8(){return{actorsPayload:{items:y.lastSyncActors},coordinatorAdminStatus:y.lastSyncCoordinatorAdminStatus,deviceIdentityInventory:y.lastDeviceIdentityInventory,shareOperations:y.lastShareOperations,actorLoadError:!1,coordinatorAdminLoadError:!1,deviceIdentityInventoryLoadError:y.deviceIdentityInventoryLoadError,shareOperationsLoadError:y.shareOperationsLoadError,duplicatePersonDecisions:DR()}}async function S8(e){if(e.requiredSurface!=="all")return w8();const t=DR();let n=null,r=null,i=y.lastDeviceIdentityInventory,o=y.lastShareOperations,s=!1,c=!1,l=y.deviceIdentityInventoryLoadError,d=!1;try{n=await UN({signal:e.signal})}catch{s=!0}try{r=await vu({signal:e.signal})}catch{c=!0}if(y.activeTab==="advanced"){l=!1;try{i=await Nu({signal:e.signal})}catch{l=!0}}try{const u=await dv({signal:e.signal});o=Array.isArray(u.items)?u.items:[]}catch{d=!0}return{actorsPayload:n,coordinatorAdminStatus:r,deviceIdentityInventory:i,shareOperations:o,actorLoadError:s,coordinatorAdminLoadError:c,deviceIdentityInventoryLoadError:l,shareOperationsLoadError:d,duplicatePersonDecisions:t}}function Yd(e={}){const t=C8(++mg,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return hg=t,t}async function C8(e,t){try{const n=y.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await b8(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:f,shareOperationsLoadError:p,duplicatePersonDecisions:m}=await S8(t);if(e!==mg)return hg??!1;if(t.signal?.aborted)return!1;const g=_8({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:p,requiresDeviceIdentityInventory:y.activeTab==="advanced",deviceIdentityInventoryLoadError:f});i&&g8(n,v8(r)),p8(r.coordinator);const b=JSON.stringify([r,o,s,c,f,l,p,m,f8()]);if(b===Ws)return g;Ws=b;const _=k8(r);Array.isArray(o?.items)?y.lastSyncActors=o.items:y.lastSyncActors=[];const v=Array.isArray(r.peers)?r.peers:[],S=new Set(v.map(k=>String(k?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(y.pendingAcceptedSyncPeers)?y.pendingAcceptedSyncPeers.filter(k=>{const P=String(k?.peer_device_id||"").trim();return P&&!S.has(P)}):[];return y.pendingAcceptedSyncPeers=w,y.lastSyncPeers=[...v,...w],f||(y.lastDeviceIdentityInventory=c),y.deviceIdentityInventoryLoadError=f,y.lastShareOperations=l,y.shareOperationsLoadError=p,y.lastSyncSharingReview=r.sharing_review||[],y.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,y.lastSyncCoordinator=r.coordinator||null,y.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,y.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],y.lastSyncAttempts=r.attempts||[],y.lastSyncLegacyDevices=r.legacy_devices||[],y.lastSyncDuplicatePersonDecisions=m,y.lastSyncViewModel=c9({actors:y.lastSyncActors,peers:y.lastSyncPeers,coordinator:y.lastSyncCoordinator,status:_,shareOperations:y.lastShareOperations,shareOperationsLoadError:p,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:y.lastSyncDuplicatePersonDecisions}),FR(),Ks(),cY(),dY(),eP(),sg(),KR(),MR(),nP(),d&&lY(),u&&(y.lastSyncCoordinatorAdminStatus=null,Ks()),g}catch{return t.signal?.aborted?!1:e!==mg?hg??!1:(Ws="",y.deviceIdentityInventoryLoadError=!0,R8(),!1)}}function k8(e){const t=e.status;return!t||typeof t!="object"?null:(y.lastSyncStatus={...t,sync_health:e.sync_health??null},y.lastSyncStatus)}function I8(){sa=null,Ws="",y.lastSyncStatus&&(y.lastSyncStatus={...y.lastSyncStatus,sync_health:null}),y.lastSyncPeers=y.lastSyncPeers.map(e=>({...e,sync_health:null})),y.lastSyncViewModel=null,Ks(),nP()}function R8(){I8(),Yr("syncTeamSkeleton"),Yr("syncActorsSkeleton"),Yr("syncPeersSkeleton"),Yr("syncDiagSkeleton"),y8(),zR();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),uY(),C9()}function nP(){if(y.activeTab==="health"){gh();return}Fk()}function P8(){Ws="",y.lastSyncPeers?.length&&sg()}async function Xd(){await Yd()}function N8(e={}){const t=T8(++gg,e.signal);return vg=t,t}async function T8(e,t){try{const n=await GN(!1,{signal:t});return t?.aborted?!1:e!==gg?vg??!1:(y.pairingPayloadRaw=n||null,tg(),!0)}catch{return t?.aborted?!1:e!==gg?vg??!1:(y.pairingPayloadRaw=null,tg(),!1)}}function A8(e){J5(),Ml(),hY(Xd),sY(Xd),N9(sg),SY(e,Xd),pY(Xd),T9(e),cg(),mY()}function E8(e,t){const n=Xe("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function x8(){try{const e=await bN();if(!e?.version)return;E8(e.version,"379bc99")}catch{}}var yg=null,rP=1500,zs=V1(),iP="codemem-legacy-upgrade-notice-dismissed",Zr=null,Jt=!1,Qd=!1,bg=!1;function oP(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function aP(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=oP(n.total_group_count,r.length),o=oP(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function sP(){try{return localStorage.getItem(iP)==="1"}catch{return!1}}function D8(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(iP,"1")}catch{}}function j8(e,t){e&&t?lL(t):dL()}function cP(e){!e||bg||sP()||(bg=!0,d_(()=>j8(!0,e)))}async function O8(){if(!(bg||sP()))try{cP(aP(await sc(!1,"",{includeJoinRequests:!1})))}catch{}}function Ui(e,t){y.viewerReconnectOpen=e;const n=Xe("viewerReconnectOverlay"),r=Xe("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",y.activeTab==="feed"&&Ln(!0))}async function _g(){try{return await yN(),!0}catch{return!1}}function Js(){return document.visibilityState!=="hidden"&&!VI()}function lP(){return`${y.activeTab}:${y.advancedSection}:${y.syncPairingOpen}`}function L8(e){y.refreshQueued||e.surface!==lP()||!e.refreshSucceeded||!Qd||Jt||(Qd=!1,Gp("connection_restored"))}function dP(){if(Jt)return;Jt=!0,Qd=!0,Gp("connection_lost"),Ys(),d_(),ei("error","(reconnecting)"),Ui(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await _g()){if(Zr&&(clearTimeout(Zr),Zr=null),Jt=!1,Ui(!0,"Viewer responded. Restoring your session…"),Js()){ei("refreshing"),Gi();try{await nu()}catch{}}else ei("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Jt||Ui(!1);return}Ui(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Zr=setTimeout(e,rP)};Zr=setTimeout(e,rP)}function ei(e,t){y.refreshState=e;const n=Xe("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=Xe("refreshAnnouncer");!s||yg===e||(s.textContent=o,yg=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}`,yg=null}var $8=5e3,M8=3e4,F8=3e4,wg=null;function Ys(){vd(),zs.cancel(),ti&&(clearTimeout(ti),ti=null),y.refreshQueued=!1,y.refreshTimer&&(clearInterval(y.refreshTimer),y.refreshTimer=null)}function uP(){Ys(),ei("paused")}function Gi(){if(y.refreshTimer||!Js()||Jt)return;const e=document.hasFocus()?$8:M8;y.refreshTimer=setInterval(()=>gr({automatic:!0}),e)}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Ys(),ei("paused","(tab hidden)")):!VI()&&!Jt&&(Gi(),gr({automatic:!document.hasFocus()}))}),window.addEventListener("blur",()=>{Ys(),Gi()}),window.addEventListener("focus",()=>{!Js()||Jt||(Ys(),Gi(),gr())});var Zd=!1;function pP(){const e=y.advancedSection==="sync",t=Xe("advancedSyncContent"),n=Xe("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Xe("advancedTabsMount");r&&jF(r,y.advancedSection,B8),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&Zd){Zd=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}cg(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function B8(e,t={}){Lw(e,!0),pP(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var q8=oF();function fP(e){const t=new Set(J1(y.lastCoordinatorAdminStatus));vi.forEach(r=>{const i=Xe(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),vi.forEach(r=>{const i=Xe(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=Xe(`tabBtn-${e}`);n&&q8(n),e==="advanced"&&pP()}function Fn(e,t={}){vd(),zs.cancel();const n=Ja(e,y.lastCoordinatorAdminStatus);n==="advanced"&&Lw(t.advancedSection??Ef()??y.advancedSection),$w(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&Pi("settings-health"),fP(n),gr()}function U8(){window.addEventListener("codemem:navigate-advanced-sync",V8),vi.forEach(e=>{Xe(`tabBtn-${e}`)?.addEventListener("click",()=>Fn(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Xe("syncTurnOnButton")?.addEventListener("click",()=>{HI("sync"),uR(uP)}),Xe("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),Mp("teams"),Fn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),Xe("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),Mp("invitations"),Fn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=Af();if(e){const t=Ef();Zd=Ow(),Fn(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),Zd=Ow(),Fn(y.activeTab)}async function G8(){try{const e=await rc();y.knownProjects=e,P8(),Nf(e,y.currentProject)}catch{}}function H8(e){y.pendingDeviceIdentityFocus=e?.trim()||null,Fn("devices",{canonicalHash:!0})}function V8(){Fn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var eu=eO({},{onOpenTeamSetup:aI,onReviewDevices:H8}),mP={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Sg=0,Cg=null,Yt=null;async function K8(e={}){const t=[];let n=0;for(;;){const r=await ma({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return xc(t)}function W8(){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 y.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of y.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=Hs(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function z8(){return y.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 hP(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function J8(e){return y.lastSyncPeers.flatMap(t=>{const n=String(t.peer_device_id??"").trim();if(!n)return[];const r=t.has_error?"error":t.status?.sync_status,i=["ok","error","stale"].includes(r??"")?r:"unknown";return[{deviceId:n,paired:t.pinned===!0,status:i,lastSyncAt:t.last_sync_at??t.status?.last_sync_at??null,recentIn:hP(t.recent_ops?.in),recentOut:hP(t.recent_ops?.out),syncHealth:t.sync_health,statusAvailable:e}]})}async function Y8(e){try{const t=await Tu({peerDeviceId:e});if(t.items.length!==1||t.items[0]?.peer_device_id!==e)return{message:"This device is no longer paired here. Refresh Devices before retrying.",tone:"warning"};const n=Gh(t),r=await tu();return{message:r?n.message:`${n.message} Refresh Devices to see the latest sync status.`,tone:n.ok&&!n.warning&&r?"success":"warning"}}catch(t){return t instanceof Error&&/\bsync_disabled\b/.test(t.message)?{message:"Device sync is off. Turn it on in Settings → Device Sync, then try again.",tone:"warning"}:{message:ft(t,"Could not sync this device. Check its pairing and try again."),tone:"warning"}}}function X8(e){if(e==="advanced_sync"){Fn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){Fn("sharing",{canonicalHash:!0}),Mp("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}Fn(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function tu(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=eX(t,++Sg,e);return Cg=n,n}async function Q8(){const[e,t]=await Promise.all([tu(),eu()]);return e&&t}function gP(){return{localDeviceId:y.lastSyncStatus?.device_id??void 0,onCommitted:Q8,onNavigate:X8,onRetry:()=>{tu()},onSyncDevice:Y8}}function Z8(e){if(!Yt){Xl(e,mP,{version:1,items:[]},[],[],{loadError:!0});return}Xl(e,Yt.intent,Yt.reconciliation,Yt.projects,Yt.availability,{...gP(),coordinatorEnrollmentIssueCount:Yt.coordinatorEnrollmentIssueCount,inventory:Yt.inventory,inventoryUnavailable:Yt.inventoryUnavailable,peerRuntimeMetadata:Yt.peerRuntimeMetadata,peerSyncMetadata:Yt.peerSyncMetadata,refreshError:!0})}async function eX(e,t,n){Yt||Xl(e,mP,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([K8(n),Pu(n),pT(n),Nu(n).then(p=>({inventory:p,unavailable:!1})).catch(()=>({inventory:Yt?.inventory,unavailable:!0})),Yd({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==Sg)return Cg??!1;const l=W8(),d=z8(),u=J8(c),f=pv(y.lastSyncStatus);return!s.unavailable&&s.inventory&&(y.lastDeviceIdentityInventory=s.inventory),y.deviceIdentityInventoryLoadError=s.unavailable,Xl(e,i,o,r,l,{...gP(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:f,peerRuntimeMetadata:d,peerSyncMetadata:u,syncStatusUnavailable:!c}),Yt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,peerSyncMetadata:u,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:f},c}catch{return n.signal?.aborted?!1:t!==Sg?Cg??!1:(Z8(e),!1)}}Xe("projectFilterMount")?.addEventListener(bw,e=>{const t=e.detail;typeof t=="string"&&(zs.cancel(),vd(),y.currentProject=t,Nf(y.knownProjects,t),Pi("scope"),Ln(!0),gr())});var ti=null;async function tX(e){await Promise.all([lW({signal:e.signal}),L6({signal:e.signal}),rL().catch(()=>{})])}async function nX(e,t){const n=Date.now();t.automatic&&wg!==null&&n-wg<F8||(wg=n,await dW({signal:e.signal}))}function rX(e,t,n,r,i){if(t!=="health"&&Fk(),t==="feed"){const c=G2();e.push(RS(c,{signal:r.signal}),Cs({signal:r.signal}))}if(t==="projects"&&e.push(ta({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(eu({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(tu({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(nX(r,i),Yd({requiredSurface:"health",requireFreshSyncStatus:Qd,signal:r.signal}).then(n)),t==="advanced"&&y.advancedSection==="sync"&&e.push(Yd({signal:r.signal}).then(n)),t==="advanced"&&y.advancedSection==="teams"&&e.push(ql({deferWhileRenaming:!0,signal:r.signal}).then(n)),!y.syncPairingOpen)return;const o=t==="advanced"&&y.advancedSection==="sync",s=N8({signal:r.signal});e.push(o?s.then(n):s)}async function gr(e={}){Jt||e.automatic&&(y.refreshInFlight||ti)||(ti&&clearTimeout(ti),ti=setTimeout(()=>{ti=null,nu(e)},80))}async function iX(e,t){if(!t.isCurrent()&&!gu(e))return;const n=await _g();t.isOwned()&&(n?ei("error"):dP())}function oX(e){zs.finish(e),y.refreshInFlight=!1,!(!y.refreshQueued||Jt||!Js())&&(y.refreshQueued=!1,nu())}function aX(e){return y.refreshInFlight?(e.automatic||(y.refreshQueued=!0),!0):!1}async function nu(e={}){if(Jt||!Js()||aX(e))return;y.refreshInFlight=!0;const t=zs.begin();try{ei("refreshing");const n=y.activeTab,r=lP(),i=[tX(t)];let o=!0;const s=!e.automatic||document.hasFocus();if(s&&rX(i,n,l=>{o=o&&l},t,e),await Un(Promise.all(i),t.signal),!t.isCurrent()){if(gu(t.signal.reason))throw t.signal.reason;return}cP(aP(y.lastSyncLegacySharedReview)),s&&n==="feed"&&Ln(!0);const c=Ja(y.activeTab,y.lastCoordinatorAdminStatus);c!==y.activeTab&&(vd(),$w(c)),fP(y.activeTab),ei(o?"idle":"error"),L8({refreshSucceeded:s&&o,surface:r})}catch(n){await iX(n,t)}finally{oX(t)}}rF(),Nf(y.knownProjects,y.currentProject);var vP=document.getElementById("toastRoot");vP&&i$(vP);var yP=document.getElementById("operationStatusRoot");yP&&Zp(yP);var bP=document.getElementById("diagnosticsDrawerMount");bP&&nL(bP);var _P=document.getElementById("legacyTeamSetupMount");_P&&vz(_P,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(y.activeTab==="sharing"?(t=await ta(n),e=await eu(n)):(e=await eu(n),t=await ta(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var wP=document.getElementById("legacyUpgradeDialogMount");wP&&cL(wP,{onDismiss:D8,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),H1(),aF(wl("themeToggle")),qw(jf()),U8(),GK(),iL(),v6(()=>gr(),{onOpenTeamSetup:aI}),A8(()=>gr()),Y2(),W5(uP,Gi,()=>gr()),G8(),Xe("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Gp("reconnect_requested"),Ui(!0,"Checking whether the viewer server is back…"),!await _g()){dP();return}Zr&&(clearTimeout(Zr),Zr=null),Jt=!1,Ui(!0,"Viewer responded. Restoring your session…"),Gi();try{await nu()}catch{}Jt||Ui(!1)}),x8(),O8(),gr(),Gi()})();
|
|
120
|
+
Global: ${d.total_tokens_saved.toLocaleString()} estimated saved`:"",b=[{label:l?"Savings (project)":"Savings",value:u?Aa(u.total_tokens_saved):"n/a",tooltip:u?`Estimated tokens saved by reusing compressed memories: ${u.total_tokens_saved.toLocaleString()}${g}`:"Usage data is unavailable",icon:"trending-up"},{label:l?"Injected (project)":"Injected",value:u?Aa(u.total_tokens_read):"n/a",tooltip:u?`Estimated tokens injected into context (pack size): ${u.total_tokens_read.toLocaleString()}${m}`:"Usage data is unavailable",icon:"book-open"},{label:l?"Reduction (project)":"Reduction",value:u?Rp(u.total_tokens_saved,u.total_tokens_read):"n/a",tooltip:u?`Estimated percent reduction from reuse. Factor: ${ux(u.total_tokens_saved,u.total_tokens_read)}.${m}${g}`:"Usage data is unavailable",icon:"percent"},{label:l?"Work investment (project)":"Work investment",value:"n/a",tooltip:"Work-investment data is unavailable",icon:"pencil"},{label:"Active memories",value:o?.active_memory_items??"n/a",icon:"check-circle"},{label:"Embedding coverage",value:o?vb(o.vector_coverage):"n/a",tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:o?vb(o.tags_coverage):"n/a",tooltip:"Share of active memories with tags",icon:"tag"}];i&&iW(b,p,f),Ek(e,b),t&&aW(t,o,s),ks()}function aW(e,t,n){if(!t){fd(e,sW(y.healthStats,"Database metrics"));return}const r=n?` · project: ${n}`:"",i=kl(y.healthStats)?" · showing stale data":"",o=mx(t.path);fd(e,`DB: ${o} · ${hx(t.size_bytes)}${r}${i}`)}function sW(e,t){return e.status==="loading"?`Loading ${t.toLowerCase()}…`:e.status==="failed"?`${t} failed to load`:`${t} not loaded`}var Gk=0,Di=null;function vd(){Di?.cancel()}function cW(e){if(y.activeTab!=="health"||y.lastUpdateStatus&&!y.lastUpdateStatus.unavailable||Di||e.signal?.aborted)return;const t=nc(),n={cancel:()=>{Di===n&&(Di=null,t.abort(),t.dispose(),e.signal?.removeEventListener("abort",n.cancel))}};Di=n,e.signal?.addEventListener("abort",n.cancel,{once:!0}),Un($T({signal:t.signal}),t.signal).then(i=>r(i),i=>r(MT(i)));function r(i){Di===n&&(Di=null,t.dispose(),e.signal?.removeEventListener("abort",n.cancel),y.activeTab==="health"&&(y.lastUpdateStatus=i,gh()))}}async function lW(e={}){const t=y.viewerActorId,n=await _N(e);if(e.signal?.aborted)return;y.viewerActorId=n.identity.actor_id;const r=document.getElementById("syncNowButton");if(r&&(r.disabled=y.viewerActorId===null||r.getAttribute("aria-busy")==="true"),t!==y.viewerActorId){if(t!==null&&y.activeTab==="feed"){await Cs({restart:!0,signal:e.signal}).catch(()=>{});return}Ln(!0)}}async function dW(e={}){const t=++Gk,n=y.currentProject;y.healthStats=Cl(y.healthStats),y.healthUsage=Cl(y.healthUsage,n),y.healthSession=Cl(y.healthSession,n),y.healthRawEvents=Cl(y.healthRawEvents),Is();const r=()=>!e.signal?.aborted&&t===Gk;cW(e),await Promise.all([yd(EN(e)).then(i=>{r()&&(y.healthStats=bd(y.healthStats,i),Is())}),yd(xN(n,e)).then(i=>{r()&&(y.healthUsage=bd(y.healthUsage,i,n),Is())}),yd(DN(n,e)).then(i=>{r()&&(y.healthSession=bd(y.healthSession,i,n),Is())}),yd(jN(n,e)).then(i=>{r()&&(y.healthRawEvents=bd(y.healthRawEvents,i),Is())})])}function Is(){oW(),ZK(document.getElementById("automaticRecallStats"),ir(y.healthStats)?.automatic_recall),Z3(),gh()}async function yd(e){try{return{ok:!0,data:await e}}catch(t){return{ok:!1,error:t instanceof Error?t.message:"Health request failed"}}}function bd(e,t,n=""){return"data"in t?K1(t.data,Date.now(),n):W1(e,t.error)}function vh(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function Hk(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function Vk(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var uW={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function Kk(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function pW(e){return e.targetIdentityRef?e.targetIdentityRef:e.identityEvidence==="label"?"":e.existingIdentityRef??""}function fW(e,t){return e.identityEvidence==="label"?`This computer lists it as ${t}. Confirm the person who uses that device.`:e.verifiedEvidenceKind==="active_assignment"?`Current assignment: ${t} · verified active assignment`:`Current assignment: ${t}`}function mW({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=ht(),f=`${u}-identity`,p=`${u}-evidence`,m=`${u}-assignment-help`,g=pW(o),b=o.targetIdentityRef??"",[_,v]=R(g);q(()=>v(g),[g]);const S=i.identityChoices.some(O=>O.identityRef===_),w=Kk(i,o.existingIdentityRef),k=Kk(i,o.suggestedIdentityRef),P=n?.has(o.deviceRef)??!1,T=e||P||r,E=T||!o.actions.assignIdentity.enabled,$=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!_&&!S,A=!o.actions.include.enabled||$||F||!b||_!==b,j=T||A,D=E||!_||$||F||_===b,H=!o.enabled||A,V=e?t:P?vh("device",o.deviceRef):void 0,z=[p,H?m:void 0,V].filter(Boolean).join(" "),M=[p,V].filter(Boolean).join(" "),C=o.decision==="unresolved";return a("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:[a("legend",{children:o.displayName}),C?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,a("div",{className:"small legacy-team-device-evidence",id:p,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),w?a("span",{children:fW(o,w)}):null,!w&&k?a("span",{children:["Suggested person: ",k]}):null,a("span",{children:["Decision: ",uW[o.decision]]})]}),a("label",{htmlFor:f,children:"Person using this device"}),a(Pn,{"aria-describedby":z,className:"legacy-team-device-select",disabled:E,id:f,onChange:O=>v(O.currentTarget.value),value:_,children:[a("option",{value:"",children:"Choose a person"}),_&&!S?a("option",{value:_,children:"Current server assignment"}):null,i.identityChoices.map(O=>a("option",{value:O.identityRef,children:O.displayName},O.identityRef))]}),o.enabled?F?a("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):$?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!_||!b||_!==b?a("p",{className:"small",id:m,children:_?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:a("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),a("div",{className:"legacy-team-device-actions",children:[a("button",{"aria-describedby":z,"aria-disabled":D?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{D||c(o,_)},type:"button",children:"Save assignment"}),o.enabled?a(U,{children:[a("button",{"aria-describedby":z,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{j||d(o,"included",b)},type:"button",children:"Include"}),a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":M,"aria-disabled":T||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!T&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function hW(e){const t=Hk(e.detail.devices);return a("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[a("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),a("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),a("div",{className:"legacy-team-device-list",children:t.map((n,r)=>h(mW,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function gW(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function vW({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=ht(),d=`${l}-mapping`,u=`${l}-help`,f=c.resolvedProjectRef??"",p=di(c.mappingChoices.map(z=>({canonicalId:z.resolvedProjectRef,displayName:z.displayName}))),m=[...new Set(c.mappingChoices.map(z=>z.resolvedProjectRef))],g=[...m].sort((z,M)=>z<M?-1:z>M?1:0),b=new Map(g.map((z,M)=>[z,`project-choice-${M+1}`])),_=new Map(c.mappingChoices.map(z=>[z.resolvedProjectRef,z])),v=m.flatMap(z=>{const M=_.get(z);return M?[{...M,label:p.get(z)??M.displayName,token:b.get(z)??""}]:[]}),S=v.find(z=>z.resolvedProjectRef===f)?.token??"",w=JSON.stringify(g),[k,P]=R(S);q(()=>P(S),[S,w]);const T=v.find(z=>z.token===k)?.resolvedProjectRef,E=n?.has(c.projectRef)??!1,$=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!k,A=e||E||r||!c.actions.map.enabled,j=A||!T||T===f,D=gW(c,p),H=[$||F?u:void 0,e?t:E?vh("project",c.projectRef):void 0].filter(Boolean).join(" "),V=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${V?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:V?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[V?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?a("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):a(U,{children:[a("p",{className:"small",children:D?`Saved mapping: ${D}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a(Pn,{"aria-describedby":H||void 0,className:"legacy-team-project-select",disabled:A,id:d,onChange:z=>P(z.currentTarget.value),value:k,children:[a("option",{value:"",children:"Choose a Project"}),v.map(z=>a("option",{value:z.token,children:z.label},z.resolvedProjectRef))]}),$?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":H||void 0,"aria-disabled":j?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!j&&T&&o(c,T)},type:"button",children:"Save mapping"})]})]})]})}function yW(e){const t=Vk(e.detail.projects),n=di(t.map(o=>({canonicalId:o.projectRef,displayName:o.displayName}))),r=e.detail.projects.filter(o=>o.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return a("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[a("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),a("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?a("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,a("div",{className:"legacy-team-project-list",children:t.map((o,s)=>a(vW,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(o.projectRef),index:s,onMap:e.onMap,presentationName:n.get(o.projectRef)??o.displayName,project:o},o.projectRef))}),e.detail.unresolvedProjectCount===0?a("div",{className:"legacy-team-setup-next-action",children:[a("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),a("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var Rs={add:"Add",update:"Update",remove:"Remove"},bW=10;function mt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function yh(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${kn(s)}`,d=n(o),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function bh(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${mt(e.projectRefs.size,t)}`:e.displayName}function Ps({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>bW;return a("section",{children:[a("h4",{children:i}),n.length>0?a(U,{children:[o&&r?a("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>a("li",{children:c},`${i}-summary-${l}`))}):null,s?a("details",{children:[a("summary",{children:["Show all ",mt(n.length,`exact ${t}`)]}),a(Wk,{items:n,title:i})]}):a(Wk,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function Wk({items:e,title:t}){return a("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>a("li",{children:n},`${t}-${r}`))})}function _W({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const o=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=R(null),d=c===s,u=e||!d,f=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),p=o.teamChanges.map(C=>{const O=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Rs[C.change]} ${C.teamDisplayName}: change device access from ${O} to the reviewed device list.`}),m=o.membershipChanges.map(C=>`${Rs[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),g=di([...n.projects.map(C=>({canonicalId:C.projectRef,displayName:C.displayName})),...o.projectChanges.map(C=>({canonicalId:C.projectRef,displayName:C.projectDisplayName}))]),b=o.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}]:[]]),_=di(b.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),v=new Map(b.map(C=>[C.resolvedProjectRef,_.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),S=di([...n.projects.flatMap(C=>C.canonicalProjectRef?[{canonicalId:C.canonicalProjectRef,displayName:C.displayName}]:[]),...[...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.canonicalProjectKind==="project").map(C=>({canonicalId:C.canonicalProjectRef,displayName:C.canonicalProjectDisplayName}))]),w=o.projectChanges.map(C=>`${Rs[C.change]} ${g.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?v.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?v.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),k=o.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${Rs[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),P=o.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${Rs[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),T=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,E=yh(o.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),$=yh(o.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),F=yh(o.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),A=n.devices.filter(C=>C.decision==="included").length,j=[mt(o.teamChanges.length,"Team policy change"),mt(o.membershipChanges.length,"membership change"),mt(o.projectChanges.length,"Project change"),mt(o.recipientChanges.length,"recipient change"),mt(o.deviceAccessChanges.length,"device-access change")],D=`${mt(n.projects.length,"Project")} included; ${mt(A,"included device")}.`,H=Math.max(n.candidate.projectCount,n.projects.length),V=new Set(o.deviceAccessChanges.map(C=>C.deviceRef)).size,z=[...o.teamChanges,...o.membershipChanges,...o.projectChanges,...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.change==="remove").length,M=o.teamChanges.length===0&&o.membershipChanges.length===0&&o.projectChanges.length===0&&o.recipientChanges.length>0&&o.recipientChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")&&o.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}.${V>0?` ${mt(V,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${mt(H,"reviewed Project")}.`:`${mt(T,"server-confirmed access change")} will be applied atomically; ${mt(z,"removal")} ${z===1?"is":"are"} included.`;return a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:"Review every server-confirmed access change before activating this Team."}),a("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[a("p",{className:"legacy-team-setup-net-effect",children:[a("strong",{children:"Net effect:"})," ",M]}),a("p",{children:[a("strong",{children:mt(T,"exact access change")})," to review."]}),a("ul",{children:j.map(C=>a("li",{children:C},C))}),a("p",{className:"small",children:["Scope: ",D]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(Ps,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:p,title:"Team policy"}),a(Ps,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(Ps,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:w,summaryItems:E.map(C=>`${bh(C,"reviewed Project")}, ${mt(C.changeCount,"Project change")}`),title:"Projects"}),a(Ps,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:k,summaryItems:$.map(C=>`${bh(C,"canonical Project")}, ${mt(C.changeCount,"recipient change")}`),title:"Recipients"}),a(Ps,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:P,summaryItems:F.map(C=>`${bh(C,"canonical Project")}, ${mt(C.changeCount,"device-access change")}`),title:"Device access"})]}),a("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[a("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:C=>{e&&C.preventDefault()},onChange:C=>{if(e){C.currentTarget.checked=d;return}l(C.currentTarget.checked?s:null)},type:"checkbox"}),a("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?a("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[a("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,a("button",{"aria-describedby":f||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"})]})}var _h=class extends Error{constructor(e){super("initial_setup_refresh_failed",{cause:e})}};function wW(e,t,n){return!(t instanceof _h)&&e.kind==="load"&&!e.refresh&&!e.completionOnly&&t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale"&&n!==void 0&&n.state!=="unavailable"}function SW(e){let t=null;return async n=>{try{const r=await IW(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){return CW(n,e,r)}}}async function CW(e,t,n){const r=n instanceof _h?n.cause:n;let i,o;try{i=await RW(e,t,r)}catch(s){o=s}return wW(e,n,i)?{status:"success",generation:e.generation,id:e.id,kind:e.kind,view:i}:{status:"failure",generation:e.generation,id:e.id,kind:e.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}async function kW(e,t){if(e.refresh)return t.refreshCandidate(e.candidateRef);const n=await t.loadDetail(e.candidateRef);if(e.completionOnly||e.readOnlyRecovery||n.state!=="unavailable"||n.unavailableReason!=="team_setup_confirmation_stale")return n;try{return await t.refreshCandidate(e.candidateRef)}catch(r){throw new _h(r)}}async function IW(e,t,n,r){switch(e.kind){case"load":return kW(e,t);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function RW(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Fe)||!ji(n.errorCode))){if(e.kind==="load"&&!e.refresh&&!e.completionOnly&&n.errorCode==="team_setup_confirmation_stale")return t.loadDetail(e.candidateRef);if(e.kind!=="load")return t.loadDetail(e.candidateRef)}}function ji(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function zk(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function PW(e,t,n){return Yk(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function Jk(e,t){return Yk(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function Yk(e,t){return{id:e,targetId:t}}var wh="Team setup changed since it was last reviewed. Reload the latest details to continue.",Xk="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",Qk="Team device details are temporarily unavailable. Check the coordinator connection and settings, then retry loading.",NW="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",TW="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",Zk="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",eI="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",AW="Another device completed this Team with different reviewed details. Retry to load the completed setup.",EW="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function xW(){return{status:"closed",generation:0}}function Sh(e,t){switch(t.type){case"open":return e.status==="open"&&fr(e)?e:DW(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&fr(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 jW(e,t.step);case"blocked_navigation":return _d(e,t.step,t.message);case"retry":return OW(e);case"refresh":return $W(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return Ch(e,t,"assign_device");case"decide_device":return Ch(e,t,"decide_device");case"clear_device":return Ch(e,t,"clear_device");case"map_project":return LW(e,t);case"finish":return MW(e);case"command_started":return oz(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return FW(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function DW(e,t){return Gr({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 jW(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return _d(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return _d(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return _d(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:zk(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function _d(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?Hk(e.view.devices).findIndex(i=>i.decision==="unresolved"):Vk(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:PW(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function OW(e){if(e.status!=="open"||e.step==="completed"||Ns(e)||fr(e))return e;const t=wd(e)??e.errors.find(r=>r.retry),n=t?.retry??"load";return Gr(e,{kind:"load",candidateRef:e.candidateRef,refresh:n==="refresh",completionOnly:n==="completion",readOnlyRecovery:n==="load"&&t?.readOnlyRetry===!0,focusOnOutcome:!0})}function Ch(e,t,n){if(e.status!=="open"||e.step==="completed"||!kh(e.view)||wd(e)||Ns(e)||fr(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return Gr(Oi(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function LW(e,t){if(e.status!=="open"||e.step==="completed"||!kh(e.view)||wd(e)||Ns(e)||fr(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:Gr(Oi(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 $W(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Ns(e)||fr(e)?e:Gr(Oi(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function MW(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:Gr(Oi(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 Gr(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 FW(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return n.kind==="load"&&(n.completionOnly||n.readOnlyRecovery)&&t.status==="success"&&t.view?.state!=="completed"?tI(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new Fe(409,"team_setup_confirmation_stale")}):t.status==="failure"?tI(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?qW(r,n.attemptId):t.view?nI({...iz(r,n),message:BW(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function BW(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 tI(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?nI(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=t.kind==="load"&&!t.refresh&&n.recoveredView?.state==="unavailable",o=UW(t,i&&n.recoveredView?.state==="unavailable"?new Fe(409,n.recoveredView.unavailableReason):n.cause,i?void 0:n.recoveryCause),s={...r,errors:[...Oi(r,o.scope).errors,o],message:""};return t.kind!=="load"||!t.focusOnOutcome?s:{...s,focus:Jk(s.nextFocusId,{hasError:!0,recovery:s.view?.state==="unavailable",step:s.step}),nextFocusId:s.nextFocusId+1}}function nI(e,t,n){const r=nz(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:rz(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:o,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=o.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:Jk(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!oI(s,t.attemptId)&&(s=Gr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function qW(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:zk(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return oI(n,t)||(n=Gr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function UW(e,t,n){const r=t instanceof Fe&&ji(t.errorCode),i=t instanceof Fe&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=XW({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i}),l=c?null:JW(e,t,n),d=r||i||o!==null,u=WW(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null}),f=GW(e,t,n,u);return{scope:HW(e,{globalError:d}),message:l??s,hideStaleView:!!l||e.kind==="load"&&e.completionOnly||f,readOnlyRetry:f,retry:u}}function GW(e,t,n,r){return e.kind!=="load"||r!=="load"?!1:e.readOnlyRecovery?!0:t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale"&&!!n}function HW(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function VW(e,t,n){const r=n instanceof Fe&&n.errorCode==="team_setup_confirmation_stale",i=t instanceof Fe&&t.errorCode==="team_setup_confirmation_stale";return!i&&!r?null:e.kind==="load"&&!e.refresh&&i&&n&&(!(n instanceof Fe)||!ji(n.errorCode))?"load":e.kind==="load"&&e.refresh?"completion":"refresh"}function KW(e,t){return e.kind!=="load"||!e.readOnlyRecovery||e.refresh||e.completionOnly?null:t instanceof Fe&&ji(t.errorCode)?"refresh":"load"}function WW(e,t,n,r){if(e.kind==="load"&&n instanceof Fe&&Sd(n.errorCode)!==null)return"completion";if(r.terminalRecovery)return e.kind==="load"?"completion":"load";const i=VW(e,t,n);if(i)return i;if(e.kind==="load"&&e.completionOnly)return zW(t);const o=KW(e,t);return o||(r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load")}function zW(e){return e instanceof Fe&&ji(e.errorCode)?"refresh":"completion"}function JW(e,t,n){return e.kind!=="load"||e.refresh||!(t instanceof Fe)||t.errorCode!=="team_setup_confirmation_stale"||!n?null:n instanceof Fe&&n.errorCode==="team_setup_roster_unavailable"?Qk:n instanceof Fe&&n.errorCode==="team_setup_completion_unavailable"?Zk:n instanceof Fe&&ji(n.errorCode)?wh:"The current Team setup could not be loaded. Retry to check the latest details."}function YW(e,t){return e.kind==="load"&&e.readOnlyRecovery?Qk:e.kind!=="finish"?Xk:t instanceof Fe&&t.reason==="local_candidate_scan_budget_exceeded"?TW:NW}function XW(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Fe?Sd(n.errorCode):null,c=tz(r instanceof Fe?Sd(r.errorCode):null),l=c??s,d=ZW(t.kind,l,n);return c?{completionCode:l,message:d??rI(t.kind),terminalRecoveryCode:c}:i?{completionCode:l,message:wh,terminalRecoveryCode:c}:o?{completionCode:l,message:YW(t,n),terminalRecoveryCode:c}:{completionCode:l,message:d??rI(t.kind),terminalRecoveryCode:c}}var QW="The coordinator needs an update before this Team setup can finish. No changes were applied. Ask the person who runs it to update it, then retry.";function ZW(e,t,n){return e!=="finish"?Ih(t):t==="team_setup_completion_unavailable"?ez(n):t==="team_setup_completion_invalid"&&n instanceof Fe&&n.reason==="coordinator_rejected_manifest"?QW:Ih(t)}function ez(e){return e instanceof Fe&&e.reason==="coordinator_route_missing"?`${eI} The coordinator may be running an older version.`:eI}function tz(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function rI(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 nz(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function kh(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function fr(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 Ns(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function wd(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function rz(e){if(ji(e))return wh;if(e==="team_setup_roster_unavailable")return Xk;const t=Ih(Sd(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function Sd(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function Ih(e){return e==="team_setup_completion_unavailable"?Zk:e==="team_setup_completion_conflict"?AW:e==="team_setup_completion_invalid"?EW:null}function iI(e){return e.kind==="global"||e.kind==="load"}function Oi(e,t){const n=iI(t);return{...e,errors:e.errors.filter(r=>n?!iI(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function iz(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?Oi(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?Oi(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function oz(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function oI(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var az={role:"list"},sz={role:"listitem"};function cz(e,t){return e?.state==="unavailable"||t?.retry==="refresh"||(t?.scope.kind==="load"||t?.hideStaleView===!0)&&!!e}function lz(e){const t=e.session,n=t.view,r=wd(t),i=t.commands.some(w=>w.kind==="load"),o=Ns(t)||fr(t),s=t.commands.some(w=>w.kind==="finish"),c=cz(n,r),l=r!=null&&(!n||c),d=!kh(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,f=n?`Set up ${n.candidate.displayName}`:"Set up Team",p=t.errors.filter(w=>w.scope.kind==="device"||w.scope.kind==="project"),m=p.length>0,g=p.some(w=>w.retry==="refresh"),b=new Set(p.flatMap(w=>w.scope.kind==="device"?[w.scope.itemRef]:[])),_=new Set(p.flatMap(w=>w.scope.kind==="project"?[w.scope.itemRef]:[])),v=new Set(t.commands.flatMap(w=>"deviceRef"in w?[w.deviceRef]:[])),S=new Set(t.commands.flatMap(w=>"projectRef"in w?[w.projectRef]:[]));return a(Zt,{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:w=>{w||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:a("div",{"aria-busy":o?"true":"false",className:"modal-card legacy-team-setup-card",children:[a("div",{className:"modal-header",children:[a("div",{id:"legacy-team-setup-title",tabIndex:-1,children:a(lo,{children:f})}),a(kr,{ariaDisabled:o,ariaLabel:`Close ${f}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[p.map(w=>a("p",{"aria-live":"assertive",id:"itemRef"in w.scope?vh(w.scope.kind,w.scope.itemRef):void 0,role:"alert",children:w.message},"itemRef"in w.scope?`${w.scope.kind}:${w.scope.itemRef}`:w.scope.kind)),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?g?"Refreshing…":"Retrying…":g?"Refresh Team setup":"Retry"})]}):null,n?a(U,{children:[t.step!=="completed"&&!l?a(dz,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?a(hW,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:b,busyDeviceRefs:v,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(yW,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:_,busyProjectRefs:S,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(_W,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(uz,{busy:o,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),a("div",{className:"modal-footer legacy-team-setup-actions",children:a("button",{"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function dz(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(U,{children:[a("ol",{...az,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,o)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return h("li",{...sz,className:"legacy-team-setup-step",key:i.step},a("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:o+1}),a("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${o+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?a("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?a("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function uz(e){return e.step==="completed"?a("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[a("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),a("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),a("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?a("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var pz={clearDecision:cT,finish:uT,loadDetail:oT,onCompleted:()=>{},refreshCandidate:dT,saveAssignment:aT,saveDecision:sT,saveProjectMapping:lT},Rh="codemem:open-legacy-team-setup";function aI(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(Rh,{detail:t})),t.handled}function fz(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 mz({dependencies:e}){const[t,n]=R(xW),r=x(null),i=ye(()=>SW(e),[e]),o=l=>{n(d=>Sh(d,l))};return Ge(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(f=>f.status==="open"&&fr(f)?Sh(f,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):Sh(f,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(Rh,l),()=>{window.removeEventListener(Rh,l)}},[]),q(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))o({type:"command_started",id:l.id}),i(l).then(d=>o({type:"effect_outcome",outcome:d}))},[i,t]),q(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),o({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:a(lz,{session:t,onAssign:(l,d)=>o({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>o({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(fr(t)){o({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}o({type:"close"})},onCloseAutoFocus:l=>gz(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){o({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}o({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>o({type:"finish"}),onMap:(l,d)=>o({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>o({type:"navigate",step:l}),onOpenAutoFocus:hz,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var hz=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function gz(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(fz(t.current)?t.current:n)?.focus(),t.current=null}function vz(e,t={}){const n={...pz,...t};ke(a(mz,{dependencies:n}),e)}function Cd(e,t){return`${e}-${Array.from(t,n=>(n.codePointAt(0)??0).toString(16).padStart(6,"0")).join("")||"empty"}`}function kd(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Ko(e){return e.identity_source!=="unmapped"&&!kd(e)}function Ph(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function yz(e){return e.git_remote||e.repository_identity||e.cwd||""}function sI(e){return e==="git_repository"?"git repository":e.replaceAll("_"," ")}function Nh(e,t){const n=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space";return t.some(r=>r.scope_id!==e.scope_id&&(r.label||"Untitled Space")===(e.label||"Untitled Space"))?`${n} · Space ID ${e.scope_id}`:n}function Id(e,t){if(!e)return"—";if(t.scopeLabels[e])return t.scopeLabels[e];for(const n of t.scopeGroups){const r=n.scopes.find(i=>i.scope_id===e);if(r)return`${Nh(r,n.scopes)} · ${n.label}`}return"Unknown Space"}function cI(e,t){return e?t.scopeGroups.some(n=>n.scopes.some(r=>r.scope_id===e)):!1}function lI(e,t,n){for(const r of[t,e.suggested_scope_id,e.resolved_scope_id])if(cI(r,n))return r??"";return e.resolved_scope_id||""}function dI(e,t){return kd(e)?"From other devices":Id(e.resolved_scope_id,t)}function bz(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 _z(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 Th(e){return(e.guardrail_warnings??[]).filter(t=>t.severity==="warning").length}function wz(e){const t=[];return(Th(e)>0||e.statuses.includes("needs_attention"))&&t.push({label:"Needs attention",tone:"badge-offline"}),e.statuses.includes("suggested")&&t.push({label:"Suggested"}),e.statuses.includes("legacy_review")&&t.push({label:"Older shared data",tone:"badge-offline"}),kd(e)&&t.push({label:"From another device"}),e.identity_source==="unmapped"&&t.push({label:"No stable identity",tone:"badge-offline"}),t}function Sz(e,t){return[["Workspace identity",e.workspace_identity],["Repository identity",e.repository_identity],["Project",e.project],["Project match source",sI(e.identity_source)],["Recorded workspace path",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",dI(e,t)],["Suggested Space",e.suggested_scope_id?Id(e.suggested_scope_id,t):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Recorded sessions",e.session_count],["Active memories",e.memory_count??"count unavailable"],["Latest recorded session",e.latest_session_at?Ph(e.latest_session_at):"Unknown"]]}function Cz({code:e}){return a("strong",{children:[{basename_collision_review:"Name collision",broad_org_domain_pattern:"Broad mapping",home_directory_org_domain_pattern:"Broad mapping",scope_reassignment_old_copies:"Previous copies",unknown_project_local_only:"Current behavior"}[e]??"Review item",": "]})}function kz({model:e}){const{project:t}=e;return t.sharing?.length?a("div",{className:"settings-note project-sharing-summary",children:[a("strong",{children:"Project sharing"}),a("ul",{"aria-label":`People sharing ${t.display_project}`,children:t.sharing.map(n=>a("li",{children:[a("strong",{children:_z(n)})," — ",n.lifecycle.label,"."," ",n.lifecycle.explanation]},n.person.actor_id))})]}):null}function Iz({model:e}){const t=e.project.worktrees??[];return t.length<2?null:a("div",{className:"settings-note",children:[a("strong",{children:"Worktrees"}),a("ul",{"aria-label":`Worktrees for ${e.project.display_project}`,children:t.map(n=>a("li",{children:n.cwd},n.cwd))})]})}function Rz({model:e,view:t}){const{project:n}=e,r=kd(n),i=(n.guardrail_warnings??[]).filter(o=>o.severity==="warning");return a(U,{children:[a("div",{className:"project-inventory-domain",children:dI(n,t)}),a("div",{className:"project-inventory-meta",children:[r?"source-owned project":bz(n.resolution_reason)," ·"," ","Project match source: ",sI(n.identity_source)," · Latest recorded session: ",n.latest_session_at?Ph(n.latest_session_at):"Unknown"]}),a("div",{className:"settings-note",children:"Projects can appear from recorded sessions or saved mappings even with no active memories. A project name alone does not identify who created it or why it was recorded."}),a(kz,{model:e}),a(Iz,{model:e}),r?a("div",{className:"settings-note",children:"Read-only here. Change it on the source device."}):null,n.identity_source==="unmapped"?a("div",{className:"settings-note",children:"Stays on this device until it has a path, git remote, or workspace id."}):null,n.suggested_scope_id&&n.suggested_scope_id!==n.resolved_scope_id?a("div",{className:"settings-note project-suggestion-note",children:n.suggestion_reason?`Suggestion: ${n.suggestion_reason}`:`Suggestion: assign this project to ${Id(n.suggested_scope_id,t)}.`}):null,i.length>0?a("div",{className:"settings-note project-attention-note",children:["Needs attention: ",i.map(o=>o.message).join(" ")]}):null,a("dl",{className:"project-detail-grid",children:Sz(n,t).map(([o,s])=>a("div",{className:"project-detail-pair",children:[a("dt",{children:o}),a("dd",{children:s==null||s===""?"—":String(s)})]},o))})]})}function Pz(e){const{callbacks:t,currentAssignable:n,model:r,scopeId:i,selectRef:o,setScopeId:s,view:c}=e,{project:l}=r,d=Cd("project-domain",r.key),u=!i||i===l.resolved_scope_id&&!n,f=l.suggested_scope_id&&i===l.suggested_scope_id?"Confirm suggestion":"Save Space";return a(U,{children:[a("label",{className:"sr-only",htmlFor:d,children:["Space for ",l.display_project]}),a(Pn,{className:"project-domain-select",id:d,onBlur:t.onSpaceSelectBlur,onChange:p=>{s(p.currentTarget.value),t.setProjectScopeDraft(l.workspace_identity,p.currentTarget.value)},ref:o,value:i,children:[!n&&l.resolved_scope_id?a("option",{disabled:!0,value:l.resolved_scope_id,children:[Id(l.resolved_scope_id,c)," — not assignable"]}):null,c.scopeGroups.map(p=>a("optgroup",{label:p.label,children:p.scopes.map(m=>a("option",{value:m.scope_id,children:Nh(m,p.scopes)},m.scope_id))},p.key))]}),a("button",{className:"settings-button",disabled:u,onClick:()=>{t.saveProjectScope(l.workspace_identity,i)},type:"button",children:f})]})}function Nz({callbacks:e,model:t}){const{project:n}=t;return a(U,{children:[a("button",{className:"settings-button",onClick:()=>{e.keepProjectLocal(n.workspace_identity)},type:"button",children:"Keep local-only"}),a("button",{className:"settings-button",disabled:n.mapping_id==null||n.resolution_reason!=="exact_mapping",onClick:()=>{e.removeProjectScope(n.workspace_identity)},type:"button",children:"Remove mapping"}),a("button",{className:"settings-button",disabled:n.session_count===0,title:n.session_count===0?"No sessions are available to reassign for this saved mapping.":void 0,onClick:()=>{e.reassignProject(n.workspace_identity)},type:"button",children:"Change project…"}),a("button",{className:"settings-button danger",disabled:(n.memory_count??0)===0,onClick:()=>{e.forgetProject(n.workspace_identity)},type:"button",children:"Forget local memories…"})]})}function Tz({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingConfirmation;return r?a("div",{className:"settings-note project-guardrail-confirmation project-space-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirmation required before saving this Space."}),a("p",{children:"Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save."}),a("ul",{children:r.warnings.map(i=>a("li",{children:[a(Cz,{code:i.code}),a("span",{children:i.message})]},`${i.code}:${i.message}`))}),a("button",{className:"settings-button",onClick:()=>{e.confirmProjectScope(n.project.workspace_identity)},ref:t,type:"button",children:"I understand, save Space"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectScopeConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]}):null}function Az({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingForgetConfirmation;if(!r)return null;const i=r.localOwnedMemoryCount===1?"memory":"memories",o=r.peerOwnedMemoryCount===1?"memory":"memories";return a("div",{className:"settings-note project-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirm project memory cleanup."}),a("p",{children:[r.localOwnedMemoryCount.toLocaleString()," locally owned ",i," will be forgotten. ",r.peerOwnedMemoryCount.toLocaleString()," peer-owned ",o," will be left unchanged."]}),a("p",{children:"Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device."}),a("button",{className:"settings-button danger",onClick:()=>{e.forgetProject(n.project.workspace_identity,{confirmed:!0})},ref:t,type:"button",children:"I understand, forget local memories"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectForgetConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]})}function Ez(e){const{callbacks:t,model:n,view:r}=e,{project:i}=n,o=Ko(i),s=o&&i.memory_count!=null&&!i.guardrail_warnings.some(c=>c.requires_confirmation);return a("div",{className:"project-inventory-actions",children:[s?a("button",{className:"settings-button",disabled:!r.shareInventoryReady,onClick:()=>t.shareProject(i.workspace_identity),title:r.shareInventoryReady?void 0:"The complete project list is unavailable.",type:"button",children:"Share"}):null,o?a(U,{children:[a(Pz,{...e}),a(Nz,{callbacks:t,model:n}),a(Tz,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n}),a(Az,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n})]}):null]})}function xz(e){const{model:t,onOpenChange:n,open:r,view:i}=e,{project:o}=t,s=Ko(o),[c,l]=R(()=>lI(o,t.draftScopeId,i));q(()=>{l(lI(o,t.draftScopeId,i))},[t.draftScopeId,o,i]);const d=i.scopeGroups.some(u=>u.scopes.some(f=>f.scope_id===o.resolved_scope_id));return a("tr",{className:"project-inventory-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:u=>n(u.currentTarget.open),open:r,children:[a("summary",{"data-project-focus-key":`admin:${s}:${o.workspace_identity}`,children:[a("span",{children:"Details"}),Th(o)>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",Th(o)]}):null]}),a("div",{className:"project-inventory-details-body",children:[a(Rz,{model:t,view:i}),a(Ez,{...e,currentAssignable:d,scopeId:c,setScopeId:l})]})]})})})}function Dz(e){const t=[{disabled:!e.canAssign,label:"Space assignment…",onSelect:e.onOpenSpaceAssignment},{disabled:!e.canChangeProject,label:"Change project…",onSelect:e.onChangeProject},{disabled:!e.canAssign,label:"Keep local-only",onSelect:e.onKeepLocal},...e.canRemoveMapping?[{label:"Remove mapping",onSelect:e.onRemoveMapping}]:[],{danger:!0,disabled:!e.canForget,label:"Forget local memories…",onSelect:e.onForget}];return a("div",{className:"project-row-menu",children:a(Vl,{actions:t,label:`More actions for ${e.label}`})})}function jz({label:e,onOpenSpaceAssignment:t}){return a("div",{className:"project-row-menu",children:a(Vl,{actions:[{label:"Space assignment for all…",onSelect:t}],label:`More actions for ${e}`})})}function Oz(e){return e.coveredProjectCount==null||e.knownProjectCount==null?" · Coverage unavailable":` · ${e.coveredProjectCount} of ${e.knownProjectCount} known Project entries`}function uI({available:e,cluster:t=!1,recipients:n}){if(!e)return a("span",{className:"project-recipient-status tertiary",children:"Unavailable"});if(n.length===0)return a("span",{className:"project-recipient-status tertiary",children:"No Teams or Identities added"});const r=t?n:n.slice(0,2),i=n.length-r.length,o=t&&n.some(c=>c.coveredProjectCount!==c.knownProjectCount);let s="Sharing across known entries";return o&&(s="Different sharing across entries"),n.some(c=>c.coveredProjectCount==null||c.knownProjectCount==null)&&(s="Coverage unavailable"),a("div",{className:"project-recipient-summary",children:[a("ul",{"aria-label":"Active recipients",className:"project-recipient-chips",children:[r.map(c=>a("li",{className:`project-recipient-chip project-recipient-chip-${c.kind.toLowerCase()}`,children:[c.kind,": ",c.displayName,t?Oz(c):""]},c.key)),i>0?a("li",{className:"project-recipient-chip",children:["+",i]}):null]}),t?a("span",{className:"project-recipient-status",children:s}):null]})}function Lz({model:e,view:t}){const{project:n}=e;return a(U,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:(n.memory_count??0).toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:n.session_count.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:Ph(n.latest_session_at)}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(uI,{available:t.recipientPolicyReady,recipients:e.recipients})})]})}function $z({callbacks:e,model:t,onOpenDetails:n,view:r}){const{project:i}=t;return!Ko(i)&&!t.manageable?a("td",{className:"project-inventory-cell project-inventory-row-actions"}):a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.manageable?a("button",{"aria-label":`Update sharing for ${i.display_project}`,className:"settings-button project-recipient-action project-selection-target","data-project-focus-key":`manage:${i.workspace_identity}`,disabled:!r.selection.ready,onClick:()=>e.manageRecipients([i.workspace_identity]),type:"button",children:"Update sharing"}):null,Ko(i)?a(Dz,{canAssign:!0,canChangeProject:i.session_count>0,canForget:(i.memory_count??0)>0,canRemoveMapping:i.mapping_id!=null&&i.resolution_reason==="exact_mapping",label:i.display_project,onChangeProject:()=>{e.reassignProject(i.workspace_identity)},onForget:()=>{e.forgetProject(i.workspace_identity)},onKeepLocal:()=>{e.keepProjectLocal(i.workspace_identity)},onOpenSpaceAssignment:n,onRemoveMapping:()=>{e.removeProjectScope(i.workspace_identity)}}):null]})}function Mz(e){const{callbacks:t,child:n,model:r,titleId:i,view:o}=e,{project:s}=r,c=yz(s);return a("tr",{className:`project-inventory-row-header project-inventory-table-row${n?" project-inventory-child-row":""}`,children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:r.manageable?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select ${s.display_project} for recipient sharing`,checked:r.selected,className:"project-selection-checkbox","data-project-focus-key":`select:${s.workspace_identity}`,onChange:()=>t.toggleSelection([s.workspace_identity]),type:"checkbox"}),a("span",{className:"sr-only",children:["Select ",s.display_project," for recipient sharing"]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:i,children:s.display_project}),c?a("span",{className:"project-inventory-signal mono small tertiary",children:c}):null,a("div",{className:"project-inventory-badges",children:wz(s).map(l=>a(Ne,{tone:l.tone,variant:"badge",children:l.label},l.label))})]}),a(Lz,{model:r,view:o}),a($z,{...e})]})}function pI({callbacks:e,child:t=!1,clusterKey:n,model:r,view:i}){const{project:o}=r,[s,c]=R(r.detailsOpen),l=x(null),d=x(null),u=g=>{c(g),e.setProjectDetailsOpen(r.detailKey,g)};q(()=>{r.detailsOpen&&c(!0)},[r.detailsOpen]);const f=!!(r.pendingConfirmation||r.pendingForgetConfirmation);q(()=>{f&&(u(!0),queueMicrotask(()=>d.current?.focus()))},[f]);const p=()=>{u(!0),queueMicrotask(()=>l.current?.focus())},m=Cd("project-title",r.detailKey);return a("tbody",{"aria-labelledby":m,className:`project-inventory-row${t?" project-inventory-child":""}`,"data-project-cluster-key":n,"data-project-repairable":String(Ko(o)),"data-project-workspace-identity":o.workspace_identity,children:[a(Mz,{callbacks:e,child:t,model:r,onOpenDetails:p,titleId:m,view:i}),a(xz,{callbacks:e,confirmationActionRef:d,model:r,onOpenChange:u,open:s,selectRef:l,view:i})]})}function Fz(e){const t=e.projects.filter(o=>Ko(o.project)),n=t.flatMap(o=>(o.project.guardrail_warnings??[]).filter(s=>s.requires_confirmation).map(s=>({project:o,warning:s}))),r=new Set(t.map(o=>o.project.suggested_scope_id).filter(o=>!!o)),i=new Set(t.map(o=>o.project.resolved_scope_id));return{assignable:t,blocking:n,hasMixed:r.size>1||i.size>1,memoryCount:e.projects.reduce((o,s)=>o+(s.project.memory_count??0),0),sessionCount:e.projects.reduce((o,s)=>o+s.project.session_count,0),warningTotal:e.projects.reduce((o,s)=>o+(s.project.guardrail_warnings??[]).filter(c=>c.severity==="warning").length,0)}}function Bz(e){const t=x(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedProjectIds.length>0&&e.selectedProjectIds.length<e.projectIds.length)},[e.projectIds.length,e.selectedProjectIds.length]),t}function qz({model:e,summary:t,view:n}){return a(U,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:t.memoryCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:t.sessionCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:"—"}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(uI,{available:n.recipientPolicyReady,cluster:!0,recipients:e.recipients})})]})}function Uz({callbacks:e,model:t,onOpenAssignment:n,summary:r,view:i}){return a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.projectIds.length>0?a("button",{"aria-label":`Manage sharing for ${t.label}`,className:"settings-button project-recipient-action project-selection-target",disabled:!i.selection.ready,onClick:()=>e.manageRecipients(t.projectIds),type:"button",children:"Manage sharing"}):null,r.assignable.length>0?a(jz,{label:t.label,onOpenSpaceAssignment:n}):null]})}function Gz(e){const{callbacks:t,model:n,onToggleWorktrees:r,summary:i,titleId:o,worktreesOpen:s}=e,c=Bz(n),l=e.view.rows.filter(f=>f.kind==="cluster"&&f.label===n.label),d=l.length>1?` (group ${l.findIndex(f=>f.key===n.key)+1} of ${l.length})`:"",u=n.projectIds.length>0&&n.selectedProjectIds.length===n.projectIds.length;return a("tr",{className:"project-inventory-row-header project-inventory-table-row",children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:n.projectIds.length>0?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select all Project entries for ${n.label}`,checked:u,className:"project-selection-checkbox",onChange:()=>t.toggleSelection(n.projectIds),ref:c,type:"checkbox"}),a("span",{className:"sr-only",children:["Select all Project entries for ",n.label]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:o,children:n.label}),a("div",{className:"project-inventory-badges",children:[a(Ne,{variant:"badge",children:[n.projects.length," Project entries"]}),a("button",{"aria-controls":e.entriesId,"aria-expanded":s,"aria-label":`${s?"Hide":"Show"} entries for ${n.label}${d}`,className:"settings-button project-worktrees-toggle",onClick:f=>{s&&f.currentTarget.focus(),r()},type:"button",children:s?"Hide entries":"Show entries"}),i.warningTotal>0?a(Ne,{tone:"badge-offline",variant:"badge",children:["Needs attention · ",i.warningTotal]}):null]})]}),a(qz,{...e}),a(Uz,{...e})]})}function Hz(e){const{callbacks:t,model:n,scopeId:r,selectRef:i,setScopeId:o,summary:s,view:c}=e;if(s.assignable.length===0){const d=n.projects.every(u=>u.project.read_only)?"These Project entries were received from other devices. Change Project or Space assignments on their source devices.":"These Project entries cannot be bulk assigned until they have stable local identities. Expand each entry for details.";return a("div",{className:"settings-note",children:d})}const l=cI(r,c);return a(U,{children:[a(Pn,{"aria-label":`Space for ${n.label} group`,className:"project-domain-select",onBlur:t.onSpaceSelectBlur,onChange:d=>{o(d.currentTarget.value),t.setClusterScopeDraft(n.key,d.currentTarget.value)},ref:i,value:r,children:[a("option",{value:"",children:"Choose Space…"}),c.scopeGroups.map(d=>a("optgroup",{label:d.label,children:d.scopes.map(u=>a("option",{value:u.scope_id,children:Nh(u,d.scopes)},u.scope_id))},d.key))]}),a("button",{className:"settings-button",disabled:!l||s.blocking.length>0,onClick:()=>{t.saveClusterScope(n.key,r)},type:"button",children:["Save Space for ",s.assignable.length," ",s.assignable.length===1?"Project entry":"Project entries"]})]})}function Vz({summary:e,onReviewEntries:t,entriesId:n}){return e.blocking.length>0?a("div",{className:"settings-note project-attention-note",children:[a("strong",{children:"Project match needs review."})," One or more Project entries need individual review before bulk assignment. Review the remote or recorded path before assigning a Space.",a("button",{"aria-controls":n,className:"settings-button project-review-entries",onClick:t,type:"button",children:"Review entries"})]}):e.hasMixed?a("div",{className:"settings-note project-attention-note",children:"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment."}):null}function Kz(e){const{onOpenChange:t,open:n,summary:r}=e;return a("tr",{className:"project-inventory-details-row project-inventory-cluster-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:i=>t(i.currentTarget.open),open:n,children:[a("summary",{children:[a("span",{children:"Advanced Space assignment"}),r.warningTotal>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",r.warningTotal]}):null]}),a("div",{className:"project-inventory-details-body",children:a("div",{className:"project-inventory-actions",children:[a(Hz,{...e}),a(Vz,{...e})]})})]})})})}function Wz({callbacks:e,model:t,view:n,entriesId:r,regionRef:i,summary:o}){return a("tr",{className:"project-cluster-entries-row",hidden:!t.worktreesOpen,children:a("td",{colSpan:7,children:a("section",{"aria-label":`Project entries for ${t.label}`,className:"project-cluster-entries",id:r,ref:i,tabIndex:-1,children:[a("table",{className:"project-inventory-table project-entries-table",children:[a("caption",{className:"sr-only",children:["Project entries for ",t.label]}),a("thead",{className:"sr-only",children:a("tr",{children:["Select","Project entry","Memories","Sessions","Last activity","Shared with","Actions"].map(s=>a("th",{scope:"col",children:s},s))})}),t.worktreesOpen?t.projects.map(s=>a(pI,{callbacks:e,child:!0,clusterKey:t.key,model:s,view:n},`${s.project.read_only?"received":"local"}:${s.key}`)):null]}),o.blocking.length>0?a("details",{className:"project-entry-review-details",children:[a("summary",{children:["Project matches needing review · ",o.blocking.length]}),a("ul",{children:o.blocking.map(({project:s,warning:c})=>a("li",{children:[a("strong",{children:["Project entry: ",s.project.workspace_identity]})," —"," ",c.message]},`${s.key}:${c.code}`))})]}):null]})})})}function zz(e){const{callbacks:t,model:n}=e,[r,i]=R(n.detailsOpen),[o,s]=R(n.draftScopeId??""),c=x(null),l=x(null);q(()=>{n.detailsOpen&&i(!0)},[n.detailsOpen]),q(()=>s(n.draftScopeId??""),[n.draftScopeId]);const d=Fz(n),u=b=>{i(b),t.setClusterDetailsOpen(n.key,b)},f=()=>{u(!0),queueMicrotask(()=>c.current?.focus())},p=Cd("project-cluster-title",n.key),m=Cd("project-cluster-entries",n.key),g=()=>{t.setClusterWorktreesOpen(n.key,!0),queueMicrotask(()=>l.current?.focus())};return a("tbody",{"aria-labelledby":p,className:"project-inventory-row project-inventory-cluster","data-project-cluster-key":n.key,children:[a(Gz,{...e,entriesId:m,onOpenAssignment:f,onToggleWorktrees:()=>t.setClusterWorktreesOpen(n.key,!n.worktreesOpen),summary:d,titleId:p,worktreesOpen:n.worktreesOpen}),a(Wz,{...e,entriesId:m,regionRef:l,summary:d}),a(Kz,{...e,entriesId:m,onReviewEntries:g,onOpenChange:u,open:r,scopeId:o,selectRef:c,setScopeId:s,summary:d})]})}function Jz({callbacks:e,error:t,view:n}){return t?a("div",{className:"settings-note",role:"status",children:t}):n.rows.length===0?a("div",{className:"settings-note",children:"No matching projects"}):a("table",{className:"project-inventory-table",children:[a("caption",{className:"sr-only",children:"Projects"}),a("thead",{children:a("tr",{className:"project-inventory-table-header project-inventory-table-row",children:[a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Select"})}),a("th",{scope:"col",children:"Project"}),a("th",{scope:"col",children:"Memories"}),a("th",{scope:"col",children:"Sessions"}),a("th",{scope:"col",children:"Last activity"}),a("th",{scope:"col",children:"Shared with"}),a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Actions"})})]})}),n.rows.map(r=>r.kind==="cluster"?a(zz,{callbacks:e,model:r,view:n},r.key):a(pI,{callbacks:e,model:r,view:n},r.detailKey))]})}function Yz(e,t,n,r){ke(a(Jz,{callbacks:n,error:r,view:t}),e)}function Xz(e){if(e?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement)return document.activeElement.dataset.teamSetupCandidateRef}function Qz(e,t,n){if(t){for(const r of e.querySelectorAll("button"))if(r.dataset.teamSetupCandidateRef===t){r.focus();return}n()}}function Zz(e,t){const n=document.createElement("div");n.className="project-inventory-actions";const r=document.createElement("strong");if(r.textContent=e.displayName,n.appendChild(r),!t)return n;const i=document.createElement("button");return i.setAttribute("aria-label",`Finish setting up ${e.displayName}`),i.className="settings-button",i.type="button",i.textContent="Finish setting up this Team",i.dataset.teamSetupCandidateRef=e.candidateRef,i.addEventListener("click",()=>t(e.candidateRef)),n.appendChild(i),n}function e4(e,t){const n=document.createElement("section");n.className="card project-team-setup-entry",n.dataset.teamSetupSignature=JSON.stringify(e.candidates.map(o=>[o.candidateRef,o.displayName]));const r=document.createElement("h2");r.textContent="Finish setting up this Team";const i=document.createElement("p");i.className="section-meta",i.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",n.append(r,i);for(const o of e.candidates)n.appendChild(Zz(o,t.onOpenTeamSetup));return n}function t4(e,t,n){const r=t?.candidates??[],i=e.querySelector(":scope > .project-team-setup-entry");i?.querySelector(".project-team-setup-status")?.remove();const o=Xz(i);if(r.length===0){i?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,o&&n.onFocusFallback();return}if(!t)return;const s=JSON.stringify(r.map(l=>[l.candidateRef,l.displayName]));if(i?.dataset.teamSetupSignature===s){e.hidden=!1;return}i?.remove(),e.hidden=!1;const c=e4(t,n);e.appendChild(c),Qz(c,o,n.onFocusFallback)}function fI(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}var mr=new Set,Rd=new Set,Ts=new EventTarget,As=new Set,mI=100,xt="";function Wo(e,t,n){n?e.add(t):e.delete(t),Ts.dispatchEvent(new Event("change"))}function hI(e,t){const[n,r]=R(e.has(t));return q(()=>{const i=()=>r(e.has(t));return Ts.addEventListener("change",i),i(),()=>Ts.removeEventListener("change",i)},[e,t]),n}function n4(){const[e,t]=R(()=>new Set(mr));return q(()=>{const n=()=>t(new Set(mr));return Ts.addEventListener("change",n),n(),()=>Ts.removeEventListener("change",n)},[]),e}function r4(e){const t=new Map;for(const n of e){const r=`${n.projectGroup.identity}\0${n.conditionCode}`,i=t.get(r);if(i){i.items.push(n);continue}t.set(r,{key:r,displayName:n.projectGroup.displayName,items:[n]})}return[...t.values()]}function gI(e,t){return e.options.find(n=>n.decision===t)}function i4(e){const t=e.items[0];if(Li(e,t.recommendedDecision))return"Choose a review response";const n=gI(t,t.recommendedDecision);return n?vI(n):t.recommendedDecision.replaceAll("_"," ")}function vI(e){switch(e.decision){case"apply_recommendation":return"Acknowledge local Identity suggestion";case"keep_project_local":return"Record local preference (access unchanged)";case"reject_suggestion":return"Dismiss suggestion (setup unchanged)";default:return e.label}}function yI(e){return[...new Map(e.map(t=>[t.id,t.label])).values()]}function Ah(e,t){return e.items.flatMap(n=>{const r=gI(n,t);return r?[r]:[]})}function o4(e){const t=new Map;for(const n of e)for(const r of n.preview.projects){const i=t.get(r.canonicalIdentity)??0;t.set(r.canonicalIdentity,Math.max(i,n.preview.affectedMemoryCount))}return[...t.values()].reduce((n,r)=>n+r,0)}function bI(e){const t=yI(e.flatMap(n=>n.preview.projects.map(r=>({id:r.canonicalIdentity,label:`${r.displayName} — ${r.canonicalIdentity}`}))));return{devices:yI(e.flatMap(n=>n.preview.effectiveDevices.map(r=>({id:r.deviceId,label:`${r.displayName} (${r.assignment})`})))),memoryCount:o4(e),projects:t}}function Hr(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function a4(e){return e==="unassigned_effective_device"?"Set up Identity or devices first":"Choose recipients first (Update sharing, below)"}async function s4(e){try{return await yT(e),{stale:!1,failed:!1}}catch(t){if(!(t instanceof ev))throw t;return As.add(e.reviewItemId),{stale:!0,failed:!1}}}function c4(e,t){if(t.status==="stale"){As.add(t.reviewItemId),e.stale=!0;return}t.status!=="applied"&&(e.failed=!0)}async function _I(e){const t={failed:!1,stale:!1};for(let n=0;n<e.length;n+=mI){const r=e.slice(n,n+mI),i=await bT(r);for(const o of i.results)c4(t,o)}return t}async function l4(e,t){const n=wI(e,t),r=n[0];return n.length===1&&r?s4(r):_I(n)}function wI(e,t){return e.items.map(n=>({decision:t,reviewItemId:n.reviewItemId,sourceFingerprint:n.sourceFingerprint}))}function d4(e,t){if(t.failed)return"Some items did not update. Try again.";if(t.stale)return"Changed since loaded. Check the refreshed choices.";for(const n of e.items)As.delete(n.reviewItemId);return"Applied"}function Pd(e,t){return e instanceof Error?e.message:t}function Li(e,t){const n=Ah(e,t);return n.length!==e.items.length||n.some(r=>r.preview.requiresDecisionInput)}function u4({options:e}){const{devices:t,memoryCount:n,projects:r}=bI(e);return a("div",{className:"recipient-policy-preview",children:[a("strong",{children:["Review context: ",Hr(r.length,"Project")," ·"," ",Hr(n,"memory","memories")," · ",Hr(t.length,"device")]}),a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Projects and paths"}),a("ul",{children:r.map(i=>a("li",{children:i},i))})]}),t.length>0?a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Devices"}),a("ul",{children:t.map(i=>a("li",{children:i},i))})]}):null]})}async function SI(e,t){try{await e.onRefresh?.()}catch(n){const r=Pd(n,"Unable to refresh review items.");xt=`${xt} Refresh failed: ${r}`,t(xt)}}function p4(e,t,n,r){const i=hI(mr,e.key);async function o(){const s=t.current;if(!(i||Li(e,s)||mr.has(e.key))){Wo(mr,e.key,!0),xt="Applying…",n(xt);try{try{xt=d4(e,await l4(e,s))}catch(c){xt=Pd(c,"Unable to apply decision. Try again.")}n(xt),await SI(r,n)}finally{Wo(mr,e.key,!1)}}}return{apply:o,pending:i}}function f4(e){const t=e.items[0],n=bI(Ah(e,t.recommendedDecision)),r=[`Suggested: ${i4(e)}`,Hr(n.memoryCount,"memory","memories"),Hr(n.devices.length,"device")];return e.items.length>1&&r.push(Hr(e.items.length,"worktree")),r.join(" · ")}function m4({blocked:e,group:t,onSelectedChange:n,pending:r,selected:i,stale:o}){const s=t.items[0],c=`Select ${t.displayName}: ${s.finding} (${s.projectGroup.identity})`;return a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("label",{className:"recipient-policy-review-selection",children:a("input",{"aria-label":c,checked:i,disabled:r||e,onChange:l=>n(l.currentTarget.checked),type:"checkbox"})}),a("strong",{children:t.displayName}),s.projectGroup.identity!==t.displayName?a("span",{className:"mono small recipient-policy-review-identity",children:s.projectGroup.identity}):null]}),a("div",{className:"small recipient-policy-review-meta",children:[s.conditionCode==="suggest_local_identity"?"Optional review · No action needed · ":null,f4(t),o?a(Ne,{variant:"badge",tone:"badge-offline",children:"Changed since loaded"}):null]})]})}function h4(e){return a(U,{children:[a(Pn,{"aria-label":`Review decision for ${e.group.displayName}`,className:"recipient-policy-review-select","data-review-control":"decision",disabled:e.pending,onChange:t=>e.onDecisionChange(t.currentTarget.value),value:e.blocked?"":e.decision,children:[e.blocked?a("option",{disabled:!0,value:"",children:"Choose a review response"}):null,e.group.items[0].options.filter(t=>!Li(e.group,t.decision)).map(t=>a("option",{value:t.decision,children:vI(t)},t.decision))]}),a("div",{className:"recipient-policy-review-actions",children:[a("button",{className:"settings-save","data-review-control":"apply",disabled:e.pending||e.blocked,onClick:e.onApply,ref:e.applyButtonRef,type:"button",children:e.pending?"Applying…":"Apply"}),a("button",{"aria-controls":e.detailsId,"aria-expanded":e.detailsOpen,className:"settings-button",onClick:e.onDetailsToggle,type:"button",children:"Review this suggestion"})]})]})}function g4({detailsId:e,group:t,open:n,requiresInput:r,selected:i,stale:o}){const s=t.items[0];return a("div",{className:"settings-note recipient-policy-review-details",hidden:!n,id:e,children:[a("div",{children:[s.finding," — ",s.reason]}),o?a("div",{children:"Changed since loaded. Check the refreshed choices."}):null,a("div",{className:"recipient-policy-deferred",hidden:!r,children:a4(s.conditionCode)}),a(u4,{options:i})]})}function v4({decision:e,group:t,onDecisionChange:n,onSelectedChange:r,onStatus:i,options:o,selected:s}){const c=`recipient-policy-details-${ht()}`,[l,d]=R(!1),u=x(e),f=x(null);u.current=e;const p=Ah(t,e),{apply:m,pending:g}=p4(t,u,i,o),b=Li(t,e),_=p.some(S=>S.preview.requiresDecisionInput),v=t.items.some(S=>As.has(S.reviewItemId));return a("article",{className:"recipient-policy-review-item","data-review-group":t.key,children:[a(m4,{blocked:b,group:t,onSelectedChange:r,pending:g,selected:s,stale:v}),a(h4,{applyButtonRef:f,blocked:b,decision:e,detailsId:c,detailsOpen:l,group:t,onApply:()=>{m()},onDecisionChange:S=>{u.current=S,f.current&&(f.current.disabled=Li(t,S)),n(S)},onDetailsToggle:()=>d(S=>!S),pending:g}),a("div",{className:"settings-note recipient-policy-review-details",children:"Apply records the selected review decision only. It does not grant or revoke access, assign an Identity, or change project mappings. Doing nothing preserves your current setup. To change recipients, use Update sharing in the project list below. For Identity or device setup, open Devices."}),a(g4,{detailsId:c,group:t,open:l,requiresInput:_,selected:p,stale:v})]})}function y4(e){const t=x(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedCount>0&&!e.allSelected)},[e.allSelected,e.selectedCount]),a("div",{className:"recipient-policy-review-bulk",children:[a("label",{className:"recipient-policy-review-select-all",children:[a("input",{"aria-label":"Select all ready review decisions",checked:e.allSelected,disabled:e.applying||e.actionableCount===0,onChange:n=>e.onSelectAll(n.currentTarget.checked),ref:t,type:"checkbox"}),a("span",{children:"Select all ready decisions"})]}),a("span",{className:"small recipient-policy-review-selection-count",children:[e.selectedCount," selected · ",e.actionableCount," ready to record"]}),a("div",{className:"recipient-policy-review-bulk-actions",children:[a("button",{className:"settings-button",disabled:e.applying||e.applySelectedBlocked||e.selectedCount===0,onClick:e.onApplySelected,type:"button",children:e.applying?"Applying…":`Apply selected (${e.selectedCount})`}),a("button",{className:"settings-save",disabled:e.applying||e.applyAllBlocked||e.actionableCount===0,onClick:e.onApplyAll,type:"button",children:e.applying?"Applying…":`Apply all (${e.actionableCount})`})]})]})}function b4(e){return Object.fromEntries(e.map(t=>[t.key,t.items[0].recommendedDecision]))}function _4(e,t){if(t.failed)return"Some decisions did not update. Check the refreshed list and try again.";if(t.stale)return"Some decisions changed since loaded. Check the refreshed choices.";for(const n of e)for(const r of n.items)As.delete(r.reviewItemId);return`Applied ${Hr(e.length,"decision")}`}async function w4(e,t){return _I(e.flatMap(n=>wI(n,t[n.key]??n.items[0].recommendedDecision)))}function S4({item:e,options:t}){const n=`recipient-policy-blocked-details-${ht()}`,r=`recipient-policy-repair-help-${ht()}`,[i,o]=R(!1),s=hI(Rd,e.blockedItemId),c=!!(t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0));async function l(){if(!(!t.onRepair||Rd.has(e.blockedItemId))){Wo(Rd,e.blockedItemId,!0);try{await t.onRepair(e.repair)}finally{Wo(Rd,e.blockedItemId,!1)}}}return a("article",{className:"recipient-policy-review-item recipient-policy-blocked-item",children:[a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("strong",{children:e.finding}),a(Ne,{variant:"badge",tone:"badge-offline",children:"Blocked"})]}),a("div",{className:"small recipient-policy-review-meta",children:["Owner: ",e.ownerLabel]})]}),a("div",{"aria-hidden":"true"}),a("div",{className:"recipient-policy-review-actions",children:[c?a("button",{"aria-describedby":r,className:"settings-button",disabled:s,onClick:()=>{l()},type:"button",children:e.repair.label}):a("span",{className:"small",children:"Repair in Projects"}),a("button",{"aria-controls":n,"aria-expanded":i,className:"settings-button",onClick:()=>o(d=>!d),type:"button",children:"Details"})]}),a("div",{className:"settings-note recipient-policy-review-details",hidden:!i,id:n,children:[a("div",{children:e.reason}),a("div",{id:r,children:e.repairAction})]})]})}function C4(e){const[t,n]=R(()=>b4(e)),r=x(t),[i,o]=R(()=>new Set),s=m=>t[m.key]??m.items[0].recommendedDecision,c=e.filter(m=>!Li(m,s(m))),l=c.filter(m=>i.has(m.key));function d(m,g){r.current={...r.current,[m.key]:g},n(r.current),Li(m,g)&&u(m.key,!1)}function u(m,g){o(b=>{const _=new Set(b);return g?_.add(m):_.delete(m),_})}function f(m){o(m?new Set(c.map(g=>g.key)):new Set)}function p(m){o(g=>{const b=new Set(g);for(const _ of m)b.delete(_.key);return b})}return{actionableGroups:c,allSelected:c.length>0&&l.length===c.length,clearSelected:p,decisionFor:s,decisionsRef:r,selectAll:f,selectedGroups:l,selectedKeys:i,setDecision:d,setGroupSelected:u}}function k4(e,t,n,r){const[i,o]=R(!1),s=x(!1);async function c(l){if(!(s.current||l.length===0||l.some(d=>mr.has(d.key)))){s.current=!0,o(!0);for(const d of l)Wo(mr,d.key,!0);xt=`Applying ${Hr(l.length,"decision")}…`,n(xt);try{try{const d=await w4(l,e.current);xt=_4(l,d),!d.failed&&!d.stale&&r(l)}catch(d){xt=Pd(d,"Unable to apply decisions. Try again.")}n(xt),await SI(t,n)}finally{for(const d of l)Wo(mr,d.key,!1);s.current=!1,o(!1)}}}return{apply:c,applying:i}}function I4({options:e,review:t}){const n=r4(t.reviewItems),[r,i]=R(xt),o=C4(n),s=n4(),c=k4(o.decisionsRef,e,i,o.clearSelected);return a("section",{className:"card recipient-policy-review","aria-labelledby":"recipientPolicyReviewTitle",children:[a("div",{className:"recipient-policy-review-header",children:[a("h2",{id:"recipientPolicyReviewTitle",children:["Sharing review ",a("span",{className:"recipient-policy-review-count",children:n.length})]}),a(Ne,{variant:"badge",tone:"badge-offline",children:"Not recorded"})]}),a("div",{className:"section-meta recipient-policy-review-status",role:"status","aria-live":"polite",children:r}),n.length>0?a(U,{children:[a(y4,{actionableCount:o.actionableGroups.length,allSelected:o.allSelected,applyAllBlocked:o.actionableGroups.some(l=>s.has(l.key)),applySelectedBlocked:o.selectedGroups.some(l=>s.has(l.key)),applying:c.applying,onApplyAll:()=>{c.apply(o.actionableGroups)},onApplySelected:()=>{c.apply(o.selectedGroups)},onSelectAll:o.selectAll,selectedCount:o.selectedGroups.length}),a("div",{className:"recipient-policy-review-list recipient-policy-review-decisions",children:n.map(l=>a(v4,{decision:o.decisionFor(l),group:l,onDecisionChange:d=>o.setDecision(l,d),onSelectedChange:d=>o.setGroupSelected(l.key,d),onStatus:i,options:e,selected:o.selectedKeys.has(l.key)},l.key))})]}):null,t.blockedItems.length>0?a("section",{className:"recipient-policy-review-section recipient-policy-review-blocked",children:[a("h3",{children:["Blocked repairs"," ",a("span",{className:"recipient-policy-review-count",children:t.blockedItems.length})]}),a("div",{className:"recipient-policy-review-list",children:t.blockedItems.map(l=>a(S4,{item:l,options:e},l.blockedItemId))})]}):null]})}function R4(e,t,n={}){if(t.reviewItems.length===0&&t.blockedItems.length===0){ke(null,e),e.hidden=!0;return}e.hidden=!1,ke(a(I4,{options:n,review:t}),e)}function P4(e,t){e.hidden=!1,ke(a("section",{className:"card recipient-policy-review",children:[a("h2",{children:"Sharing review"}),a("p",{className:"settings-note project-attention-note",role:"status",children:Pd(t,"Unable to load sharing decisions. Try again.")})]}),e)}var CI=[["","All projects"],["needs_attention","Needs attention"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","From other devices"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],wt=null,nn=0,zo=250,N4=100,Eh=[],Es=new Set,xs=new Set,Ds=new Set,js=new Map,Os=new Map,Vr=new Map,Ls=new Map,Jo=new Map,Nd=!1,Yo=new Map,$s=!1,$i=!1,xh=0,kI=null,hr=0,Ms=0,Xo=null,Fs=null,Dt=new Set,Td={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Qo=Td,Ad=!1,Dh=!1,Zo=!1,II,Kr={projects:[],total:0,offset:0,has_more:!1},RI=new Set;function et(){if(RI.size===0)return;const e=OI();for(const t of RI)t(e)}function T4(e=!1,t={}){if(!e&&Fs)return Fs;const n=rv(t).then(r=>({ok:!0,summary:r})).catch(()=>({ok:!1}));return Fs=n,n.then(()=>{Fs===n&&(Fs=null)}),n}function jh(e){return T4(e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0,e)}function xe(e){return document.getElementById(e)}function ea(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Ed(e){return e.identity_source!=="unmapped"&&!ea(e)}function PI(e){return Ed(e)&&e.memory_count!=null&&e.guardrail_warnings.every(t=>!t.requires_confirmation)}function A4(e){return`${ea(e)?"peer-received":"local"}:${e.workspace_identity}`}function E4(e){const t=Yo.get(e.workspace_identity);(!t||ea(t)&&!ea(e))&&Yo.set(e.workspace_identity,e)}function NI(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function Mi(){const e=Dt.size,t=xe("projectsShareSelected");t&&(t.textContent=e===0?"Add Teams or Identities":`Add Teams or Identities (${e})`,t.disabled=e===0||!$i||!Ad,t.classList.add("project-selection-target"));const n=xe("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`),Wr()}function x4(e){const t=e.every(n=>Dt.has(n));for(const n of e)t?Dt.delete(n):Dt.add(n);Mi(),et()}function TI(e,t,n){const r=[...new Set(e)].filter(i=>!t.has(i)).sort();return new Map(r.map((i,o)=>[i,r.length===1?`Unavailable ${n}`:`Unavailable ${n} ${o+1} of ${r.length}`]))}function AI(e){const t=new Set(e),n=Qo.projectRecipients.filter(d=>d.status==="active"&&t.has(d.canonicalProjectIdentity)),r=new Map(Qo.teams.map(d=>[d.teamId,d.status==="archived"?`${d.displayName} (archived)`:d.displayName])),i=new Map(Qo.identities.map(d=>[d.identityId,d.status==="merged"?`${d.displayName} (merged)`:d.displayName])),o=TI(n.flatMap(d=>d.recipientKind==="team"?[d.teamId]:[]),new Set(r.keys()),"Team"),s=TI(n.flatMap(d=>d.recipientKind==="identity"?[d.identityId]:[]),new Set(i.keys()),"Identity"),c=new Map,l=new Map;for(const d of n){const u=d.recipientKind==="team",f=u?`team:${d.teamId}`:`identity:${d.identityId}`,p=u?r.get(d.teamId)??o.get(d.teamId):i.get(d.identityId)??s.get(d.identityId),m=l.get(f)??new Set;m.add(d.canonicalProjectIdentity),l.set(f,m),c.set(f,{key:f,kind:u?"Team":"Identity",displayName:p??(u?"Unavailable Team":"Unavailable Identity"),coveredProjectCount:m.size,knownProjectCount:t.size})}return[...c.values()].sort((d,u)=>`${d.kind}:${d.displayName}`.localeCompare(`${u.kind}:${u.displayName}`))}function Bs(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function D4(e){return e.project||e.display_project||"Unnamed Project"}function EI(e){const t=String(e||"").trim();return t?y.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function j4(){return new Set(y.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function O4(e){return!$s||e.authority_type!=="coordinator"||!e.group_id?!1:!j4().has(String(e.group_id).trim())}function xd(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function L4(){Nd&&(Nd=!1,wt?.())}async function $4(){let e;try{const t=await vu();e=t&&typeof t=="object"?t:null}catch{y.lastProjectCoordinatorAdminGroups=[],$s=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){y.lastProjectCoordinatorAdminGroups=[],$s=!1;return}try{const t=await Ug(!1);y.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],$s=!0}catch{y.lastProjectCoordinatorAdminGroups=[],$s=!1}}function M4(e){const t=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space",n=EI(e.group_id);return n?`${t} · Team: ${n}`:e.authority_type==="local"?`${t} · Local device`:e.authority_type==="coordinator"?`${t} · Coordinator Space`:`${t} · ${e.authority_type||"Other"} Space`}function F4(){return Eh.filter(e=>e.scope_id!=="legacy-shared-review"&&!O4(e))}function B4(e){const t=EI(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function q4(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function U4(){const e=new Map;for(const t of F4()){const n=q4(t),r=B4(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.entries()].map(([t,n])=>({key:t,...n}))}async function Oh(e,t,n=[]){try{await IT({...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}),Vr.delete(e.workspace_identity),js.delete(e.workspace_identity),et(),Y("Space assignment updated. Device access unchanged."),wt?.()}catch(r){if(r instanceof zi){Vr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),Wr(),et(),wt?.();return}Y(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function G4(e,t){const n=e.filter(Ed);if(n.length!==0)try{await RT({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}))}),Y(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access unchanged.`),Os.delete(Bs(n[0])),et(),wt?.()}catch(r){Y(H4(r),"warning")}}function H4(e){return e instanceof zi?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":e instanceof Error?e.message:"Unable to update project Spaces."}async function V4(e){if(e.mapping_id!=null)try{await PT(e.mapping_id,Ls.get(e.mapping_id)??[]),Ls.delete(e.mapping_id),Vr.delete(e.workspace_identity),js.delete(e.workspace_identity),et(),Y("Project Space assignment removed. The next fallback now applies."),wt?.()}catch(t){if(t instanceof zi){Ls.set(e.mapping_id,t.requiredGuardrailTokens),Y(`${t.guardrailWarnings[0]?.message??"Review the fallback access change."} Select Remove again to confirm.`,"warning");return}Ls.delete(e.mapping_id),Y(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function K4(e,t={}){const n=t.confirmed===!0;try{const r=Jo.get(e.workspace_identity),i=await TT({...n&&r?{confirmation_token:r.confirmationToken}:{},confirmed:n,workspace_identity:e.workspace_identity});Jo.delete(e.workspace_identity),et(),Y(`Forgot ${i.forgotten_memory_count.toLocaleString()} local memor${i.forgotten_memory_count===1?"y":"ies"}. ${i.peer_owned_memory_count.toLocaleString()} peer-owned memor${i.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),wt?.()}catch(r){if(r instanceof Qg){Jo.set(e.workspace_identity,{confirmationToken:r.preview.confirmation_token,localOwnedMemoryCount:r.preview.local_owned_memory_count,peerOwnedMemoryCount:r.preview.peer_owned_memory_count}),Wr(),et(),wt?.();return}Y(r instanceof Error?r.message:"Unable to forget project memories.","warning")}}async function xI(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await rc()).filter(i=>i&&i!==t)}catch{}const r=await mm({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const o=i.trim();return o?o===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await NT({project:r.trim(),workspace_identity:e.workspace_identity});Y(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),wt?.()}catch(i){Y(i instanceof Error?i.message:"Unable to change project.","warning")}}async function W4(e){const t=Yo.get(e);if(t&&!ea(t))return{offset:nn,project:t};try{let n=0,r=0;for(;;){const i=await ma({limit:zo,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!ea(c));if(o)return{offset:i.offset,project:o};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=N4)return null;n=s}}catch{return null}}function Lh(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(c=>c.dataset.projectWorkspaceIdentity===e&&c.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.dataset.projectClusterKey,i=r?[...document.querySelectorAll(".project-inventory-cluster")].find(c=>c.dataset.projectClusterKey===r):null,o=i?.querySelector(":scope > .project-inventory-cluster-details-row .project-inventory-details");if(o){o.open=!0;const c=i?.dataset.projectClusterKey;c&&xs.add(c)}n.open=!0;const s=t.dataset.projectRowKey;return s&&Es.add(s),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}function DI(){return{generation:hr,search:xe("projectsSearch")?.value??"",status:xe("projectsStatusFilter")?.value??"",offset:nn}}function z4(e){return hr!==e.generation||(xe("projectsSearch")?.value??"")!==e.search||(xe("projectsStatusFilter")?.value??"")!==e.status||nn!==e.offset}async function J4(e){const{project:t}=e;if(Lh(t.workspace_identity)||(Ds.add(Bs(t)),Wr(),et(),Lh(t.workspace_identity)))return;const n=xe("projectsSearch"),r=xe("projectsStatusFilter"),i=DI(),o=t.workspace_identity;n&&(n.value=o),r&&(r.value=""),nn=e.offset;const s=hr;await ta(),!Lh(t.workspace_identity)&&(hr!==s||n&&n.value!==o||r&&r.value!==""||nn!==e.offset||(n&&(n.value=i.search),r&&(r.value=i.status),nn=i.offset,await ta(),Y("Project administration could not be opened. Refresh Projects and try again.","warning")))}async function Y4(e){if(xd()){Y("Finish the open Space assignment, then try Repair again.","warning");return}const t=DI(),n=await W4(e.projectIdentity);if(z4(t))return;if(xd()){Y("Finish the open Space assignment, then try Repair again.","warning");return}if(!n){Y("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:r}=n;if(e.kind==="reassign_project"){if(r.identity_source==="unmapped"||r.session_count===0){Y("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await xI(r);return}await J4(n)}function X4(e){const t=hr,n=(Xo?.catch(()=>{})??Promise.resolve()).then(async()=>{if(hr===t)try{await Y4(e)}catch(r){Y(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Xo=n,n.then(()=>{Xo===n&&(Xo=null)},()=>{Xo===n&&(Xo=null)}),n}function Q4(e){const t=new Map;for(const n of e){const r=Bs(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function jI(e){const t=Cp(e),n=Ed(e),r=A4(e),i=n?Vr.get(e.workspace_identity):void 0,o=n?Jo.get(e.workspace_identity):void 0;return{kind:"project",key:r,detailKey:r,project:e,manageable:t,selected:t&&Dt.has(e.workspace_identity),shareEligible:PI(e),shareReady:$i,detailsOpen:Es.has(r),draftScopeId:n?js.get(e.workspace_identity)??null:null,pendingConfirmation:i?{requiredGuardrailTokens:[...i.requiredGuardrailTokens],scopeId:i.scopeId,warnings:[...i.warnings]}:null,pendingForgetConfirmation:o?{...o}:null,recipients:AI([e.workspace_identity])}}function Z4(e){if(e.length===1)return jI(e[0]);const t=Bs(e[0]),n=NI(e.filter(Cp));return{kind:"cluster",key:t,label:D4(e[0]),projects:e.map(jI),projectIds:n,selectedProjectIds:n.filter(r=>Dt.has(r)),worktreesOpen:Ds.has(t),detailsOpen:xs.has(t),draftScopeId:Os.get(t)??null,recipients:AI(NI(e))}}function OI(){const e=[...Dt].sort();return{rows:Q4(Kr.projects).map(Z4),recipientPolicyReady:Dh,shareInventoryReady:$i,scopeLabels:Object.fromEntries(Eh.map(t=>[t.scope_id,M4(t)])),selection:{projectIds:e,count:e.length,ready:$i&&Ad},pagination:{offset:Kr.offset,limit:zo,total:Kr.total,hasMore:Kr.has_more},scopeGroups:U4().map(t=>({key:t.key,label:t.label,scopes:[...t.scopes]})),statusOptions:CI.map(([t,n])=>({label:n,value:t}))}}function LI(){document.getElementById("projectsInventorySkeleton")?.remove()}function e6(e){if(e.total===0)return"0 projects";const t=Math.min(e.offset+e.projects.length,e.total);return`${e.total.toLocaleString()} projects · ${e.offset+1}–${t}`}function Wr(e){if(!Zo)return;const t=xe("projectsInventoryList");t&&Yz(t,OI(),g6,e)}function $I(e){Zo=!0,Kr={projects:[...e.projects],total:e.total,offset:e.offset,has_more:e.has_more};const t=xe("projectsInventoryMeta"),n=xe("projectsInventoryList");if(!t||!n)return;LI(),Yo.clear();for(const o of e.projects)E4(o);Wr(),t.textContent=e6(e);const r=xe("projectsPrevPage"),i=xe("projectsNextPage");r&&(r.disabled=e.offset===0),i&&(i.disabled=!e.has_more),Mi(),et()}function t6(e,t,n){$4().then(()=>{if(t===xh&&$h(n)){if(xd()){et();return}$I(e)}})}async function n6(e={},t){const n=new Map;let r=0;for(;;){const i=await(t?.offset===r?t.promise:ma({limit:zo,offset:r,signal:e.signal}));for(const o of i.projects)n.set(o.workspace_identity,o);if(!i.has_more)break;r+=i.limit}return[...n.values()]}function MI(){return{query:xe("projectsSearch")?.value.trim()??"",status:xe("projectsStatusFilter")?.value??"",offset:nn}}function $h(e){const t=MI();return t.query===e.query&&t.status===e.status&&t.offset===e.offset}function r6(e,t){return ma({limit:zo,offset:t.offset,q:t.query||void 0,status:t.status||void 0,signal:e.signal})}function FI(e,t,n){const r=xe("recipientPolicyManagementMount");r&&hb(r,xc(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Dt.clear(),Mi(),et(),wt?.()}})}function i6(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}function BI(e,t){t4(e,t,{onOpenTeamSetup:II,onFocusFallback:()=>xe("projectsSearch")?.focus()})}function ta(e={}){const t=h6(e);return kI=t,t}async function qI(e,t){return e.signal?.aborted?!1:!e.awaitTeamSetupSummary&&!e.requireTeamSetupSummary?kI??!1:(await t,!1)}function Dd(e,t){return!t.signal?.aborted&&e===xh}function jd(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}async function o6(e){if(!jd(e))return!0;const t=await jh(e);return e.signal?.aborted?!1:!e.requireTeamSetupSummary||t.ok}async function a6(e){if(Nd=!0,!jd(e))return!0;const t=++Ms,n=await jh(e);if(e.signal?.aborted||t!==Ms)return!1;const r=xe("recipientPolicyReviewMount");return n.ok?(r&&BI(r,n.summary),!0):(r&&fI(r),!e.requireTeamSetupSummary)}function s6(e){return jd(e.options)?e.teamSetupSummaryPromise.then(t=>!Dd(e.loadGeneration,e.options)||e.entryLoadGeneration!==Ms?!1:e.requiredLoadSucceeded&&(!e.options.requireTeamSetupSummary||t.ok)):e.requiredLoadSucceeded}async function c6(e,t){return jd(e)&&await t,!1}function l6(e){const t=xe("recipientPolicyReviewMount");if(!t)return;const n=i6(t);"review"in e?R4(n,e.review,{isRepairAvailable:r=>!r.projectIdentity.startsWith("unmapped:"),onRefresh:async()=>{await ta()},onRepair:X4}):P4(n,e.error),t.hidden=n.hidden&&!t.querySelector(".project-team-setup-entry")}async function d6(e,t){const n=r6(e,t),r=!t.query&&!t.status?{offset:t.offset,promise:n}:void 0,[i,o,s,c,l]=await Promise.all([n,_T(e),n6(e,r).then(d=>({ok:!0,projects:d})).catch(()=>({ok:!1,projects:[]})),vT(e).then(d=>({ok:!0,review:d})).catch(d=>({ok:!1,error:d})),Pu(e).then(d=>({ok:!0,intent:d})).catch(d=>({ok:!1,error:d}))]);return{intentResult:l,recipientPolicyReview:c,result:i,settings:o,shareInventory:s}}function u6(e){if(!e.ok)return;const t=new Set(xc(e.projects).map(n=>n.canonicalProjectIdentity));for(const n of Dt)t.has(n)||Dt.delete(n)}function p6(e,t,n){const{intentResult:r,recipientPolicyReview:i,result:o,settings:s,shareInventory:c}=e;Eh=s.scopes,$i=c.ok,Ad=r.ok,Dh=r.ok,Qo=r.ok?r.intent:Td,u6(c);const l=xe("projectShareFlowMount");return l&&Gb(l,c.projects,{inventoryError:!c.ok}),l6(i),FI(c.projects,Qo,!c.ok||!r.ok),$I(o),t6(o,t,n),c.ok&&"review"in i&&r.ok}function f6(e){e.teamSetupSummaryPromise.then(t=>{if(!Dd(e.loadGeneration,e.options)||e.entryLoadGeneration!==Ms)return;const n=xe("recipientPolicyReviewMount");if(n){if(!t.ok){fI(n);return}BI(n,t.summary)}})}function m6(e,t){Zo=!0,Yo.clear(),Kr={projects:[],total:0,offset:nn,has_more:!1},$i=!1,Ad=!1,Dh=!1,Qo=Td;const n=xe("projectShareFlowMount");n&&Gb(n,[],{inventoryError:!0}),FI([],Td,!0),Mi(),et(),LI(),t.textContent="Project inventory failed to load.",Wr(e instanceof Error?e.message:"Unable to load project inventory.")}async function h6(e){const t=xe("projectsInventoryMeta"),n=xe("projectsInventoryList");if(!t||!n)return o6(e);if(xd())return a6(e);Nd=!1;const r=++xh,i=MI();Zo||Mi(),(!Zo||!t.textContent?.trim())&&(t.textContent="Loading project inventory…");let o=null;try{const s=++Ms;o=jh(e);const c=await d6(e,i);if(!Dd(r,e))return qI(e,o);if(!$h(i))return!1;const l=p6(c,r,i);return f6({entryLoadGeneration:s,loadGeneration:r,options:e,teamSetupSummaryPromise:o}),s6({entryLoadGeneration:s,loadGeneration:r,options:e,requiredLoadSucceeded:l,teamSetupSummaryPromise:o})}catch(s){return Dd(r,e)?$h(i)?(m6(s,t),c6(e,o)):!1:qI(e,o)}}function Fi(e){return Yo.get(e)??Kr.projects.find(t=>t.workspace_identity===e)??null}var g6={toggleSelection(e){x4(e)},shareProject(e){const t=Fi(e);!t||!PI(t)||!$i||qc([t.workspace_identity])},manageRecipients(e){const t=[...new Set(e)].sort();if(t.length!==0){if(t.length===1){Ra({mode:"project-manage",projectId:t[0]});return}for(const n of t)Dt.add(n);Mi(),et(),Ra({mode:"project-add",projectIds:t})}},setProjectDetailsOpen(e,t){t?Es.add(e):Es.delete(e),et()},setClusterDetailsOpen(e,t){t?xs.add(e):xs.delete(e),et()},setClusterWorktreesOpen(e,t){t?Ds.add(e):Ds.delete(e),Wr(),et()},setProjectScopeDraft(e,t){js.set(e,t),Vr.delete(e),Wr(),et(),wt?.()},setClusterScopeDraft(e,t){t?Os.set(e,t):Os.delete(e),et()},async saveProjectScope(e,t){const n=Fi(e);n&&await Oh(n,t)},async saveClusterScope(e,t){const n=Kr.projects.filter(r=>Bs(r)===e).filter(Ed);n.length>0&&await G4(n,t)},async removeProjectScope(e){const t=Fi(e);t&&await V4(t)},async keepProjectLocal(e){const t=Fi(e);t&&await Oh(t,"local-default")},async reassignProject(e){const t=Fi(e);t&&await xI(t)},async forgetProject(e,t={}){const n=Fi(e);n&&await K4(n,t)},async confirmProjectScope(e){const t=Fi(e),n=Vr.get(e);!t||!n||await Oh(t,n.scopeId,n.requiredGuardrailTokens)},cancelProjectScopeConfirmation(e){Vr.delete(e),et(),wt?.()},cancelProjectForgetConfirmation(e){Jo.delete(e),et(),wt?.()},onSpaceSelectBlur(){L4()}};function v6(e,t={}){wt=e,II=t.onOpenTeamSetup,Dt.clear(),Es.clear(),xs.clear(),Ds.clear(),js.clear(),Os.clear(),Vr.clear(),Ls.clear(),Jo.clear(),Zo=!1;const n=xe("projectsStatusFilter");n&&n.options.length===0&&n.append(...CI.map(([o,s])=>new Option(s,o)));const r=()=>{hr+=1,nn=0,wt?.()};xe("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),xe("projectsPrevPage")?.addEventListener("click",()=>{hr+=1,nn=Math.max(0,nn-zo),wt?.()}),xe("projectsNextPage")?.addEventListener("click",()=>{hr+=1,nn+=zo,wt?.()});const i=xe("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Dt.size!==0&&Ra({mode:"project-add",projectIds:[...Dt].sort()})})),Mi()}function Mh(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(o=>o.trim()):r;if(t.requireNonEmpty&&i.some(o=>o.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function y6(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,o]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof o!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=o}return r}function b6(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Mh(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(k){if(!i||n.has("claude_command"))throw k;const P=r.claude_command;o=Array.isArray(P)?P.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let s=[];try{s=Mh(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(k){if(!i||n.has("codex_command"))throw k;const P=r.codex_command;s=Array.isArray(P)?P.filter(T=>typeof T=="string").map(T=>T.trim()).filter(T=>T.length>0):[]}let c=[];try{c=Mh(t.observerAuthCommand,{label:"observer auth command"})}catch(k){if(!i||n.has("observer_auth_command"))throw k;const P=r.observer_auth_command;c=Array.isArray(P)?P.filter(T=>typeof T=="string"):[]}let l={};try{l=y6(t.observerHeaders)}catch(k){if(!i||n.has("observer_headers"))throw k;const P=r.observer_headers;P&&typeof P=="object"&&!Array.isArray(P)&&Object.entries(P).forEach(([T,E])=>{typeof T=="string"&&T.trim()&&typeof E=="string"&&(l[T]=E)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),f=t.observerRichTemperature.trim(),p=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),b=u===""?"":Number(u),_=f===""?"":Number(f),v=p===""?"":Number(p),S=Number(m),w=m===""?"":S;if(d!==""&&!Number.isFinite(g))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof b!="number"||!Number.isFinite(b)||b<0))throw new Error("simple tier temperature must be a non-negative number");if(f!==""&&(typeof _!="number"||!Number.isFinite(_)||_<0))throw new Error("rich tier temperature must be a non-negative number");if(p!==""&&(typeof v!="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(S)||S<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:Ze(t.observerProvider),observer_model:Ze(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Ze(t.observerSimpleModel),observer_simple_temperature:b,observer_reasoning_effort:Ze(t.observerReasoningEffort),observer_reasoning_summary:Ze(t.observerReasoningSummary),observer_rich_model:Ze(t.observerRichModel),observer_rich_temperature:_,observer_rich_reasoning_effort:Ze(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Ze(t.observerRichReasoningSummary),observer_rich_max_output_tokens:v,observer_runtime:Ze(t.observerRuntime),observer_auth_source:Ze(t.observerAuthSource||"auto")||"auto",observer_auth_file:Ze(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:w,sync_enabled:t.syncEnabled,sync_host:Ze(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Ze(t.syncCoordinatorUrl),sync_coordinator_group:Ze(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function _6(e){return e.resolved_observer_runtime||Ae(Ie(e.config,e.effective,"observer_runtime"))||"api_http"}function UI(e){return Kt(e.config,"observer_tier_routing_enabled")||Kt(e.env_overrides,"observer_tier_routing_enabled")}function w6(e){const t=e.config||{},n=e.effective||{},r=e.observer_apply?.active?.tierRoutingEnabled;return e.observer_apply?.state==="active"&&!UI(e)&&typeof r=="boolean"?r:gd(Ie(t,n,"observer_tier_routing_enabled"))}function S6(e){const t=e.config||{},n=e.effective||{},r=Ie(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([f,p])=>typeof f=="string"&&f.trim()&&typeof p=="string")):{},o=Ie(t,n,"claude_command"),s=Array.isArray(o)?o.filter(f=>typeof f=="string"):[],c=Ie(t,n,"codex_command"),l=Array.isArray(c)?c.filter(f=>typeof f=="string"):[],d=Ie(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(f=>typeof f=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Ae(Ie(t,n,"observer_provider")),observerModel:Ae(Ie(t,n,"observer_model")),observerTierRoutingEnabled:w6(e),observerSimpleModel:Ae(Ie(t,n,"observer_simple_model")),observerSimpleTemperature:Ae(Ie(t,n,"observer_simple_temperature")),observerReasoningEffort:Ae(Ie(t,n,"observer_reasoning_effort")),observerReasoningSummary:Ae(Ie(t,n,"observer_reasoning_summary")),observerRichModel:Ae(Ie(t,n,"observer_rich_model")),observerRichTemperature:Ae(Ie(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Ae(Ie(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Ae(Ie(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Ae(Ie(t,n,"observer_rich_max_output_tokens")),observerRuntime:_6(e),observerAuthSource:Ae(Ie(t,n,"observer_auth_source"))||"auto",observerAuthFile:Ae(Ie(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Ae(Ie(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Ae(Ie(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Ae(Ie(t,n,"observer_max_chars")),packObservationLimit:Ae(Ie(t,n,"pack_observation_limit")),packSessionLimit:Ae(Ie(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Ae(Ie(t,n,"raw_events_sweeper_interval_s")),syncEnabled:gd(Ie(t,n,"sync_enabled")),syncHost:Ae(Ie(t,n,"sync_host")),syncPort:Ae(Ie(t,n,"sync_port")),syncInterval:Ae(Ie(t,n,"sync_interval_s")),syncMdns:gd(Ie(t,n,"sync_mdns")),syncCoordinatorUrl:Ae(Ie(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Ae(Ie(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Ae(Ie(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Ae(Ie(t,n,"sync_coordinator_presence_ttl_s"))}}function C6(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection lives in Connection.";const n=_3(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Ze(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Kt(t,r))?"Env override":n.source}: ${n.model}`}function k6(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function I6(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Connection 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 R6(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while Connection controls simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-6-luna` for Direct API (including pi-derived API-key providers) or Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function P6(e){return!e}function N6(e,t,n){return t.has(e)||n.has(e)}function T6(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var W={previouslyFocused:null,baseline:{},effectiveConfig:{},resolvedObserverRuntime:null,observerRuntimeByAuthSource:{},observerRuntimeAfterAuthOverrideRemoval:{},observerAutomaticRuntimeByAuthSource:{},observerApply:null,observerTierRoutingExplicit:!1,observerModelDefaults:null,restartRequiredKeys:new Set,envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,hideTooltip:null},jt=Fa({open:!1,activeTab:"observer",dirty:!1,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...u3}},showAdvanced:g3()});function zt(){return jt.value}function qs(e){jt.value={...jt.value,...e}}function A6(){W.hideTooltip?.()}function zr(e){qs({renderState:{...jt.value.renderState,...e}})}function GI(e){zr({values:{...jt.value.renderState.values,...e}})}function HI(e){qs({activeTab:["observer","queue","sync"].includes(e)?e:"observer"})}function Od(e){qs({dirty:e})}function Ld(e){qs({open:e})}function E6(e){v3(e),qs({showAdvanced:e})}function VI(){return zt().open}function KI(e){return N6(e,W.protectedKeys,d3)}function Fh(e={}){const t=b6({values:zt().renderState.values,touchedKeys:W.touchedKeys,baseline:W.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors});return W.touchedKeys.has("observer_runtime")||(t.observer_runtime=W.baseline.observer_runtime),t}function WI(e){const t=y.feedProcessingStatus,n=x6(e);y.feedProcessingStatus=n,(t.kind!==n.kind||t.kind==="pending"&&n.kind==="pending"&&t.count!==n.count)&&Ln(!0),zr({observerStatus:e&&typeof e=="object"?e:null})}function x6(e){if(!e||typeof e!="object")return{kind:"unavailable"};const t=e,n=Number(t.queue?.pending);return Number.isFinite(n)&&n>0?{kind:"pending",count:Math.floor(n)}:t.capture_enabled===!1?{kind:"paused"}:{kind:"ready"}}function D6(e,t){return e&&typeof e=="object"&&Object.keys(e).length>0?t?"Fields show configuration-resolved values. Runtime behavior may apply automatic provider defaults. Environment settings supply some fields.":"Fields show configuration-resolved values. The current connection and models are shown separately while changes apply.":"Effective values are unavailable. Reload Settings; if this persists, restart the viewer and inspect its configuration."}function j6(e){W.resolvedObserverRuntime=e.resolved_observer_runtime??null,W.observerRuntimeByAuthSource=e.observer_runtime_by_auth_source??{},W.observerRuntimeAfterAuthOverrideRemoval=e.observer_runtime_after_auth_override_removal??{},W.observerAutomaticRuntimeByAuthSource=e.observer_automatic_runtime_by_auth_source??{}}function O6(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},o=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=S6(t);W.envOverrides=i,W.effectiveConfig={...r,...t.effective},j6(t),W.observerApply=t.observer_apply??null,W.observerTierRoutingExplicit=UI(t),W.observerModelDefaults=t.observer_model_defaults??null,W.restartRequiredKeys=new Set(t.restart_required_keys??[]),W.protectedKeys=new Set(o),y.configDefaults=n,y.configPath=t.path||"",W.touchedKeys=new Set,zr({effectiveText:D6(t.effective,Object.keys(i).length>0),overridesVisible:Object.keys(i).length>0,pathText:y.configPath?`Config path: ${y.configPath}`:"Config path: n/a",providers:y3(t.providers),statusText:"No unsaved changes",values:s});try{const c=Fh({allowUntouchedParseErrors:!0});W.baseline=S3(c,r,i),W.baseline.observer_runtime=Ze(Ae(r.observer_runtime))}catch{W.baseline={}}Od(!1)}async function L6(e={}){if(zt().open)return;const[t,n]=await Promise.allSettled([qg(e),Bg(e)]);e.signal?.aborted||(t.status==="fulfilled"&&O6(t.value),WI(n.status==="fulfilled"?n.value:null))}function zI(e){if(!e)return"Not available";const t=e.reasoningEffort?` · ${e.reasoningEffort} reasoning`:"";return`${e.provider} · ${e.model}${t}`}function $6({active:e}){return a("details",{className:"settings-note observer-routing-details",children:[a("summary",{children:"Models in use"}),e.tierRoutingEnabled?a("dl",{className:"observer-routing-list",children:[a("div",{children:[a("dt",{children:"Simple requests"}),a("dd",{children:zI(e.simple)})]}),a("div",{children:[a("dt",{children:"Rich requests"}),a("dd",{children:zI(e.rich)})]})]}):a("dl",{className:"observer-routing-list",children:a("div",{children:[a("dt",{children:"All requests"}),a("dd",{children:[e.provider," · ",e.model]})]})})]})}function M6({status:e,onRetry:t,onRefresh:n}){return e?a(U,{children:[e.active?a($6,{active:e.active}):null,e.state==="applying"?a("div",{role:"status",children:"Applying observer settings. New events will wait."}):null,e.state==="failed"?a("div",{role:"alert",children:[e.message??"Observer settings were saved but are not active."," ",a("button",{className:"settings-button",onClick:t,type:"button",children:"Retry applying observer settings"})]}):null,e.state!=="active"?a("button",{className:"settings-link-button",onClick:n,type:"button",children:"Check observer status"}):null]}):null}function F6({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function B6({available:e,method:t}){const n=Object.entries(e??{}).filter(([,r])=>r&&typeof r=="object");return!n.length||["codex_sidecar","claude_sidecar","opencode_v2"].includes(t??"")?null:a("details",{className:"status-credentials",children:[a("summary",{children:"API keys and saved sign-ins"}),a("ul",{children:n.map(([r,i])=>a("li",{children:[r,": ",f3(i)]},r))})]})}function q6({failure:e,onOpenDiagnostics:t}){return a("div",{className:"status-issue",children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue-message",children:typeof e.error_message=="string"&&e.error_message.trim()?e.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof e.observer_provider=="string"?e.observer_provider.trim():"",typeof e.observer_model=="string"&&e.observer_model.trim()?`→ ${e.observer_model.trim()}`:"",typeof e.observer_runtime=="string"&&e.observer_runtime.trim()?`(${e.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${m3(e.updated_at)}`,typeof e.attempt_count=="number"&&Number.isFinite(e.attempt_count)?`Attempts ${e.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof e.impact=="string"&&e.impact.trim()?a("div",{className:"status-issue-impact",children:e.impact.trim()}):null,a(F6,{onOpenDiagnostics:t})]})}function U6({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=n?.auth?.token_present===!1&&(n.runtime==="api_key"||n.auth.method==="none");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[e.latest_failure?a(q6,{failure:e.latest_failure,onOpenDiagnostics:t}):null,a("div",{className:"status-active",children:[a("span",{className:"status-label",children:"Current connection"}),a("span",{children:n?a(U,{children:[String(n.provider||"unknown"),n.model?` · ${String(n.model)}`:""," ·"," ",p3(n.auth?.method||"none")]}):"Waiting for the first session"})]}),r?a("div",{className:"status-token-warning",children:"No Direct API key detected. Check your credentials."}):null,a(B6,{available:e.available_credentials,method:n?.auth?.method})]})}function JI(e,t){const n=t.getBoundingClientRect(),r=8,i=8,o=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-o/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-o-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function Us(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function G6(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 H6(){const e=Xe("settingsModal");(G6(e)[0]||e)?.focus()}function V6(e,t){const n=e.getAttribute("aria-describedby")?.split(/\s+/).filter(Boolean)??[];if(!n.includes(t))return e.setAttribute("aria-describedby",[...n,t].join(" ")),()=>{const r=(e.getAttribute("aria-describedby")?.split(/\s+/)??[]).filter(i=>i&&i!==t);r.length>0?e.setAttribute("aria-describedby",r.join(" ")):e.removeAttribute("aria-describedby")}}function K6(e,t,n){return ye(()=>typeof document>"u"?null:_n(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,id:n,ref:t,role:"tooltip",children:e.content}),document.body),[e.content,e.visible,n,t])}function W6(){const e=`settings-help-${ht()}`,[t,n]=R({anchor:null,content:"",visible:!1}),r=x(null);return Ge(()=>{if(!(!t.visible||!t.anchor))return V6(t.anchor,e)},[t.anchor,t.visible,e]),q(()=>{const i=f=>{const p=f.dataset.tooltip?.trim();p&&n({anchor:f,content:p,visible:!0})},o=()=>{n(f=>!f.visible&&!f.anchor&&!f.content?f:{anchor:null,content:"",visible:!1})},s=f=>{const p=Us(f.target);p&&i(p)},c=f=>{const p=Us(f.target);if(!p)return;const m=f.relatedTarget;m instanceof Element&&p.contains(m)||o()},l=f=>{const p=Us(f.target);p&&i(p)},d=f=>{Us(f.target)&&o()},u=f=>{const p=Us(f.target);p&&(f.preventDefault(),n(m=>{if(m.anchor===p&&m.visible)return{anchor:null,content:"",visible:!1};const g=p.dataset.tooltip?.trim()||"";return g?{anchor:p,content:g,visible:!0}:m}))};return document.addEventListener("pointerover",s),document.addEventListener("pointerout",c),document.addEventListener("focusin",l),document.addEventListener("focusout",d),document.addEventListener("click",u),()=>{document.removeEventListener("pointerover",s),document.removeEventListener("pointerout",c),document.removeEventListener("focusin",l),document.removeEventListener("focusout",d),document.removeEventListener("click",u)}},[]),Ge(()=>{if(!t.visible||!t.anchor||!r.current)return;const i=requestAnimationFrame(()=>{r.current&&t.anchor&&JI(r.current,t.anchor)});return()=>{cancelAnimationFrame(i)}},[t.anchor,t.content,t.visible]),q(()=>{if(!t.visible||!t.anchor)return;const i=()=>{r.current&&t.anchor&&JI(r.current,t.anchor)};return globalThis.addEventListener("resize",i),document.addEventListener("scroll",i,!0),()=>{globalThis.removeEventListener("resize",i),document.removeEventListener("scroll",i,!0)}},[t.anchor,t.visible]),{tooltipPortal:K6(t,r,e),setTooltip:n}}function z6({DialogContent:e,onClose:t}){const{open:n}=jt.value,{tooltipPortal:r,setTooltip:i}=W6();q(()=>{const s=()=>i({anchor:null,content:"",visible:!1});return W.hideTooltip=s,()=>{W.hideTooltip===s&&(W.hideTooltip=null)}},[]),q(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const o=re(()=>{W.startPolling&&W.refresh&&t(W.startPolling,W.refresh)},[t]);return a(U,{children:[a(Zt,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:s=>{s.preventDefault()},onOpenAutoFocus:s=>{s.preventDefault(),H6()},onOpenChange:s=>{if(s){Ld(!0);return}o()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),r]})}function YI(e){return{controlId:e,existingData:"Stored memories stay unchanged; no backfill runs.",scope:"Queued and future model requests on this device",stage:"Observation processing",timing:"After viewer restart"}}function Bh(e){return{controlId:e,existingData:"Stored memories stay unchanged; no reprocessing runs.",scope:"Queued and future events on this device",stage:"Observation processing",timing:"After viewer restart"}}function XI(e){return{controlId:e,existingData:"Stored memories and existing packs stay unchanged; the value is saved only.",scope:"No current effect",stage:"Saved setting",timing:"Not used when Codemem creates context packs"}}function $n(e,t){return{controlId:e,existingData:"Existing memories are not reprocessed locally, but eligible memories may be sent to or received from trusted peers.",scope:t,stage:"Device sync",timing:"After viewer restart"}}function J6(e){return{controlId:e,existingData:"Stored memories stay unchanged. Local Claude and Codex sessions authenticate through their CLI logins instead.",scope:"No effect while Connection mode uses a local Claude or Codex session",stage:"Sidecar authentication",timing:"Not used by local Claude or Codex sessions"}}var Y6=new Set(["observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"]);function $d(e){return e==="claude_sidecar"||e==="codex_sidecar"}var X6=Object.fromEntries([...["observerProvider","observerModel","observerRuntime","observerMaxChars","observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"].map(YI),...["observerTierRoutingEnabled","observerSimpleModel","observerSimpleTemperature","observerReasoningEffort","observerReasoningSummary","observerRichModel","observerRichTemperature","observerRichReasoningEffort","observerRichReasoningSummary","observerRichMaxOutputTokens"].map(Bh),XI("packObservationLimit"),XI("packSessionLimit"),{controlId:"rawEventsSweeperIntervalS",existingData:"Processed events stay unchanged; no backfill runs.",scope:"Background queue on this viewer",stage:"Queue processing",timing:"Immediately after save"},$n("syncEnabled","Future sync cycles on this device"),$n("syncInterval","Future sync cycles on this device"),$n("syncHost","Incoming peer connections to this device"),$n("syncPort","Incoming peer connections to this device"),$n("syncMdns","Advertise this device on the local network; this does not scan for peers"),$n("syncCoordinatorGroup","Fallback coordinator discovery when no coordinator group list is configured"),$n("syncCoordinatorTimeout","Future coordinator requests"),$n("syncCoordinatorPresenceTtl","Future coordinator presence checks")].map(e=>[e.controlId,e]));function qh(e,t={}){let n=X6[e];if(!n)return;const r=Uh(t.observerRuntime);if(Y6.has(e)&&$d(r))return J6(e);if(n=e5(e,r)??n,n.scope==="No current effect")return n;const i=md[e],o=i?W.envOverrides[i]:void 0;return typeof o!="string"||!o.trim()?n:{...n,timing:`After removing ${o.trim()} and restarting the viewer`}}function Gs(e=jt.value.renderState.values.observerRuntime){return W.envOverrides.observer_runtime?!!String(W.effectiveConfig.observer_runtime??"").trim():W.touchedKeys.has("observer_runtime")?!!e?.trim():!!String(W.baseline.observer_runtime??"").trim()}function Uh(e){const t=W.envOverrides.observer_runtime,n=Jr("observerRuntime",e),r=W.touchedKeys.has("observer_runtime")&&n!==W.baseline.observer_runtime;if(r&&!n&&!t){const o=Md(Jr("observerAuthSource"));return W.observerAutomaticRuntimeByAuthSource[o]||"api_http"}if(t||!r){const o=Q6();if(o)return o;if(W.resolvedObserverRuntime)return W.resolvedObserverRuntime}const i=String(n??"").trim().toLowerCase();return["api_key","opencode_v2"].includes(i)||$d(i)?i:"api_http"}function Q6(){if(!W.touchedKeys.has("observer_auth_source"))return;const e=Md(Jr("observerAuthSource"));return W.observerRuntimeByAuthSource[e]}function Z6(e){return W.envOverrides.observer_auth_source?!0:W.touchedKeys.has("observer_runtime")&&e!==W.baseline.observer_runtime&&!W.envOverrides.observer_runtime?e?.trim()?!1:Object.values(W.observerAutomaticRuntimeByAuthSource).includes("api_http"):Object.values(W.observerRuntimeByAuthSource).includes("api_http")}function Jr(e,t){const n=md[e];return n&&W.envOverrides[n]?W.effectiveConfig[n]:t??jt.value.renderState.values[e]}function na(e,t){return{controlId:e,existingData:"Stored memories stay unchanged; this value is saved only.",scope:"No current effect",stage:"Saved setting",timing:t}}function e5(e,t){const n=$d(t),r=String(Jr("observerProvider"));if(e==="observerProvider"&&n&&Gs())return na(e,"Local Claude and Codex sessions select their own provider");if(e==="observerModel")return n5(t,r);const i=Md(Jr("observerAuthSource"));if(e==="observerAuthTimeoutMs"&&!["auto","command"].includes(i))return na(e,"Only command authentication uses this timeout");if(e==="observerAuthCacheTtlS"&&!["file","command"].includes(i))return na(e,"Only explicit file or command authentication uses this cache");if(/Temperature$/.test(e))return i5(e,t,QI(e,r));if(/Reasoning(Effort|Summary)$/.test(e)||e==="observerRichMaxOutputTokens")return o5(e,n);if(e==="syncEnabled"&&!t5(Jr(e)))return{...$n(e,"Stop future peer transfers on this device"),existingData:"Stored memories remain. Disabling sync does not retract copies already replicated to peers."};if(e==="syncHost"||e==="syncPort")return{...$n(e,"Incoming connections and newly generated pairing addresses"),timing:"Pairing payloads change immediately after save; restart the viewer before sharing or using them so the listener uses the new address"}}function Md(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return["auto","env","file","command","none"].includes(t)?t:"auto"}function t5(e){return typeof e=="boolean"?e:typeof e!="string"?!1:["1","true","yes","on"].includes(e.trim().toLowerCase())}function n5(e,t){const n="observerModel",r=Jr("observerTierRoutingEnabled");return(r===!0||r==="true"||r==="1")&&r5(e,t)?na(n,"Tier models or built-in tier defaults take precedence over the base model"):{...YI(n),scope:"Requests that use the base model, including tiers that fall back to it",timing:"After viewer restart, only where no tier model or built-in tier default takes precedence"}}function QI(e,t){const n=e.startsWith("observerSimple")?"observer_simple_provider":"observer_rich_provider",r=String(W.effectiveConfig[n]??"").trim().toLowerCase(),i=t.trim().toLowerCase();return["openai","anthropic"].includes(r)?r:["openai","anthropic"].includes(i)?i:r||i}function r5(e,t){return e==="claude_sidecar"?!0:["observerSimpleModel","observerRichModel"].every(n=>String(Jr(n)??"").trim()?!0:e==="codex_sidecar"?!1:["openai","anthropic"].includes(QI(n,t)))}function i5(e,t,n){return $d(t)||n==="anthropic"?na(e,"Anthropic and local Claude/Codex sessions do not send sampling temperature"):{...Bh(e),scope:"Only tier requests whose transport sends sampling temperature; OpenAI reasoning requests omit it",timing:"After viewer restart, only when the selected transport and reasoning mode support temperature"}}function o5(e,t){if(t)return na(e,"Local Claude and Codex sessions do not use these API tuning fields");const n=e==="observerRichMaxOutputTokens"?"Rich-tier API requests whose transport consumes the output-token limit; unsupported transports ignore it":"OpenAI Responses requests only; other transports ignore reasoning fields";return{...Bh(e),scope:n,timing:"After viewer restart, only when the effective request transport consumes this setting"}}function ZI({controlId:e,existingData:t,scope:n,stage:r}){return a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:"Change details"}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function a5({scope:e,stage:t,timing:n}){return e==="No current effect"||t==="Sidecar authentication"?a("div",{className:"settings-effect-note small",children:["Inactive · ",n]}):/only/i.test(e)?a("div",{className:"settings-effect-note small",children:e}):null}function s5(e,t){const n=W.envOverrides[e];if(n)return n;if(t==="Sidecar authentication"&&!Gs())return W.envOverrides.observer_auth_source}function c5(){const e=Md(W.touchedKeys.has("observer_auth_source")?jt.value.renderState.values.observerAuthSource:W.baseline.observer_auth_source);return(W.observerRuntimeAfterAuthOverrideRemoval[e]??W.observerRuntimeByAuthSource[e])==="api_http"}function l5({configKey:e,...t}){const{scope:n,stage:r,timing:i}=t,o=s5(e,r),s=n==="No current effect"||r==="Sidecar authentication";if(typeof o!="string"||!o.trim())return a(U,{children:[a(a5,{...t}),a(ZI,{...t})]});let c="Remove that environment setting and restart the viewer to apply changes here.";const l=W.envOverrides.observer_auth_source;return r==="Sidecar authentication"&&!Gs(jt.value.renderState.values.observerRuntime)&&c5()&&typeof l=="string"&&l.trim()?c=`Inactive for the current connection · ${i}. Remove ${[...new Set([l.trim(),o.trim()])].join(" and ")} and restart the viewer to use the saved authentication settings. The connection may change after removal.`:s&&(c=`Inactive · ${i}. Removing the environment setting does not activate this field for the current connection.`),a(U,{children:[a("div",{className:"settings-env-note small",children:["Controlled by ",o.trim(),". ",c]}),a(ZI,{...t})]})}function eR({controlId:e,existingData:t,scope:n,stage:r,timing:i}){const o=md[e];if(o?.startsWith("observer_"))return a(l5,{configKey:o,controlId:e,existingData:t,scope:n,stage:r,timing:i});let s=i;return i==="After viewer restart"?s="Change details":i.startsWith("After removing ")?s=`Environment-controlled · ${i}`:n==="No current effect"||r==="Sidecar authentication"?s=`Inactive · ${i}`:i.startsWith("After viewer restart,")&&(s="Change details"),a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:s}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Takes effect:"})," ",i]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function tR(e,t){for(const n of yn(e)){if(!n||typeof n!="object"||!("props"in n))continue;const r=n.props;if(typeof r.id=="string"&&qh(r.id,t))return r.id;const i=tR(r.children,t);if(i)return i}}function De({children:e,className:t="field",hidden:n=!1,id:r}){const i={observerRuntime:jt.value.renderState.values.observerRuntime},o=tR(e,i),s=o?qh(o,i):void 0;return a("div",{className:t,hidden:n,id:r,children:[e,s?a(eR,{...s}):null]})}function nR(e,t,n,r){if(!t)return"";if(e.observerRuntime==="claude_sidecar")return n?t[n].anthropic??t.claude:t.claude;if(e.observerRuntime==="codex_sidecar")return n&&(e.observerModel.trim()||t[n].openai)||t.codex;const i=u5(e,t);return n?d5(e,t,n,i,r):t.base[i]??""}function d5(e,t,n,r,i){const o=i?.trim().toLowerCase(),s=t[n][o??""]?o:r;return t[n][s??""]||e.observerModel.trim()||t.base[o||r]||""}function u5(e,t){const n=e.observerProvider.trim().toLowerCase();if(n)return n;const r=e.observerModel.trim().toLowerCase(),i=r.split("/")[0]??"";return Object.hasOwn(t.base,i)?i:r.startsWith("claude")?"anthropic":"openai"}var Fd=null;function p5(){if(Fd&&Date.now()-Fd.loadedAt<6e4)return Fd.promise;const e=fetch("/api/observer-model-catalog").then(t=>t.json()).then(t=>Array.isArray(t.models)?t.models:[]).catch(()=>[]);return Fd={loadedAt:Date.now(),promise:e},e}function rR({id:e,values:t,provider:n}){const r=t[e];let i=n?.trim().toLowerCase()||t.observerProvider;t.observerRuntime==="codex_sidecar"?i="openai":t.observerRuntime==="claude_sidecar"&&(i="anthropic");const[o,s]=R([]);q(()=>{let d=!0;return p5().then(u=>{d&&s(u)}),()=>{d=!1}},[]);const c=i||(r.startsWith("claude")?"anthropic":"openai"),l=o.filter(d=>d.provider===c);return a(U,{children:[a("datalist",{id:`${e}-catalog`,children:l.map(d=>a("option",{value:d.model},`${d.provider}:${d.model}`))}),l.length?a("div",{className:"small",children:"OpenCode model list; account access is not verified."}):null]})}function Bd({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`,l=qh(i);return a("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[a("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:o}),a(Eo,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"}),l?a(eR,{...l}):null]})}function iR({values:e,onTextInput:t,getObserverModelLabel:n,getObserverModelTooltip:r,modelDefaults:i}){const o=e.observerTierRoutingEnabled;return a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:o?"Fallback model":n()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":r(),type:"button",children:"?"})]}),a(be,{id:"observerModel",list:"observerModel-catalog",onInput:t("observerModel"),placeholder:nR(e,i),value:e.observerModel}),o?a("div",{className:"small",children:"Used only when a tier has no selected or built-in model."}):null,["api_http","api_key","opencode_v2"].includes(e.observerRuntime)?a(rR,{id:"observerModel",values:e}):null]})}function oR({tier:e,values:t,onTextInput:n,tierProviders:r,modelDefaults:i}){const o=e==="simple"?"observerSimpleModel":"observerRichModel",s=e==="simple"?"Simple model":"Rich model",c=e==="simple"?"Used for shorter, simpler requests.":"Used for larger or more involved requests.";return a(De,{children:[a("label",{htmlFor:o,children:s}),a(be,{id:o,list:`${o}-catalog`,onInput:n(o),placeholder:nR(t,i,e,r?.[e]),value:t[o]}),a("div",{className:"small",children:c}),["api_http","api_key","opencode_v2"].includes(t.observerRuntime)?a(rR,{id:o,values:t,provider:r?.[e]}):null]})}function f5(e){const{values:t,onSwitchInput:n,hiddenUnlessAdvanced:r}=e,i=t.observerTierRoutingEnabled,o=t.observerModel.trim().length>0;return a("div",{className:"settings-group observer-model-settings",children:[a("h3",{className:"settings-group-title",children:"Models"}),a(Bd,{checked:i,className:"field",id:"observerTierRoutingEnabled",label:"Use simple and rich models",onCheckedChange:n("observerTierRoutingEnabled")}),i?a(U,{children:[a(oR,{tier:"simple",...e}),a(oR,{tier:"rich",...e}),o||!r()?a("details",{className:"observer-fallback-details",children:[a("summary",{children:o?"Fallback model · Custom value set":"Fallback model (optional)"}),a(iR,{...e})]}):null]}):a(iR,{...e})]})}function qd({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function m5({runtime:e,onSelectValueChange:t}){let n="Keeps your existing connection rules until you choose a connection below.";e==="claude_sidecar"?n="Uses your local Claude CLI login. Claude chooses the provider.":e==="codex_sidecar"?n="Uses your local Codex CLI login. Codex chooses the provider.":e==="opencode_v2"?n="Uses the selected provider account in OpenCode. OpenCode must be running.":e==="api_key"&&(n="Uses an API key for the selected provider. Does not use subscription sign-ins.");const r=[{label:"Automatic (detect connection)",value:"automatic"},{label:"OpenCode account",value:"opencode_v2"},{label:"API key",value:"api_key"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}];return e==="api_http"&&r.unshift({label:"Existing API connection (legacy)",value:"api_http"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Choose which account handles model requests. An explicit connection never falls back to another account.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Connection mode",id:"observerRuntime",onValueChange:i=>t("observerRuntime")(i==="automatic"?"":i),options:r,value:e}),a("div",{className:"small",children:n})]})}function h5({value:e,providerOptions:t,onSelectValueChange:n}){const r={anthropic:"Anthropic",opencode:"OpenCode",openai:"OpenAI"};return a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Pi setup can also derive a provider and model from an API-key provider.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Model provider",id:"observerProvider",onValueChange:n("observerProvider"),options:[{label:"Auto (infer provider)",value:""},...t.map(i=>({...i,label:r[i.value]??i.label}))],placeholder:"Auto (infer provider)",value:e}),a("div",{className:"small",children:"Use auto unless you need to pin a provider."})]})}function g5({values:e,runtime:t,explicit:n,providerOptions:r,onSelectValueChange:i}){return a(U,{children:[a(m5,{runtime:n?t:"automatic",onSelectValueChange:i}),!n||!(t==="claude_sidecar"||t==="codex_sidecar")?a(h5,{value:e.observerProvider,providerOptions:r,onSelectValueChange:i}):null]})}function v5(e){return e==="claude_sidecar"||e==="codex_sidecar"}function y5(e){return v5(e)||e==="opencode_v2"}function b5({values:e,effectiveObserverRuntime:t=e.observerRuntime,hasExplicitObserverRuntime:n=!0,allowAutomaticAuthChanges:r=!1,tierProviders:i,modelDefaults:o,observerMaxCharsDefault:s,providerOptions:c,showAuthFile:l,showAuthCommand:d,hiddenUnlessAdvanced:u,onTextInput:f,onSelectValueChange:p,onSwitchInput:m,getObserverModelLabel:g,getObserverModelTooltip:b,protectedConfigHelp:_,observerStatusBannerSlot:v}){return a(U,{children:[a("p",{className:"small observer-panel-intro",children:["Shared across ",$k(),"."]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(g5,{values:e,providerOptions:c,onSelectValueChange:p,runtime:t,explicit:n}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(Do,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:_("codex_command")})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(Do,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:_("claude_command")})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(be,{id:"observerMaxChars",min:"1",onInput:f("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:s?`Default: ${s}`:""})]})]}),a(f5,{values:{...e,observerRuntime:t},tierProviders:i,modelDefaults:o,hiddenUnlessAdvanced:u,onTextInput:f,onSwitchInput:m,getObserverModelLabel:g,getObserverModelTooltip:b}),v,a("div",{className:"settings-group",hidden:y5(t)&&!r,children:[a("h3",{className:"settings-group-title",children:"API credentials"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Credential source"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(En,{ariaLabel:"Authentication method",id:"observerAuthSource",onValueChange:p("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],value:e.observerAuthSource}),a("div",{className:"small",children:"API keys are read from your config or environment. File and command sources use the saved protected settings below."})]}),a(De,{hidden:!l,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(be,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:_("observer_auth_file")})]}),a(De,{hidden:!d,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(Do,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:_("observer_auth_command")})]}),a("div",{className:"small",hidden:!d,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(qd,{hidden:u(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(be,{id:"observerAuthTimeoutMs",min:"1",onInput:f("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(be,{id:"observerAuthCacheTtlS",min:"0",onInput:f("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(De,{className:"field settings-advanced",hidden:u(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(Do,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:_("observer_headers")})]})]})]})}function aR({detail:e,title:t}){return a("div",{className:"settings-section-intro",children:[a("div",{className:"settings-section-intro-title",children:t}),a("div",{className:"small settings-section-intro-detail",children:e})]})}function _5({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r}){return a(U,{children:[a(aR,{detail:"Adjust background processing and, if needed, advanced model request controls. Choose models in Connection.",title:"Background processing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(De,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),a("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),a(be,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),a("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),a("div",{className:"settings-group settings-advanced",hidden:!t||n(),children:[a("h3",{className:"settings-group-title",children:"Model tuning"}),a("div",{className:"small",children:"These controls apply only when the selected connection supports them."}),a("div",{children:[a("h4",{children:"Simple tier"}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(be,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),a("div",{className:"settings-advanced",hidden:!t||n(),children:[a("h4",{children:"Shared reasoning defaults"}),a("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),a(De,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(be,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(De,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(be,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),a("div",{children:[a("h4",{children:"Rich tier"}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(be,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(be,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(be,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(be,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),a("div",{className:"settings-group settings-advanced",hidden:n(),children:[a("h3",{className:"settings-group-title",children:"Pack limits"}),a(qd,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(be,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),a("div",{className:"small",children:"Default number of observations to include in a pack."})]}),a(De,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(be,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),a("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function w5({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(U,{children:[a(aR,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Device Sync"}),a(Bd,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a(De,{children:[a("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),a(be,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),a("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncHost",children:"Sync host"}),a(be,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncPort",children:"Sync port"}),a(be,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(Bd,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),a(be,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),a("div",{className:"small",children:i("sync_coordinator_url")})]}),a(De,{children:[a("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),a(be,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),a("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:a(qd,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),a(be,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),a(De,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),a(be,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function S5({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,restartRequired:o=!1,onClose:s,onSave:c,onActiveTabChange:l,onAdvancedToggle:d,onShowGettingStarted:u,observerStatusBannerSlot:f}){const p=!i||r.isSaving,m=i&&!r.isSaving&&!r.statusText.startsWith("Save failed")?"Unsaved changes":r.statusText;return a("form",{className:"modal-card",onKeyDown:g=>ns(g,{onSubmit:c,disabled:p}),onSubmit:g=>g.preventDefault(),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(kr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:s})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(Bd,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:d}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(qd,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),a(Kf,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:l,tabs:l3,triggerClassName:"settings-tab",value:t,children:[a(bi,{className:"settings-panel",forceMount:!0,value:"observer",children:a(b5,{...e,observerStatusBannerSlot:f})}),a(bi,{className:"settings-panel",forceMount:!0,value:"queue",children:a(_5,{...e})}),a(bi,{className:"settings-panel",forceMount:!0,value:"sync",children:a(w5,{...e})})]}),a("details",{className:"settings-config-details",children:[a("summary",{children:"Configuration details"}),a("div",{className:"small mono",id:"settingsPath",children:r.pathText}),a("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."})]})]}),a("div",{className:"modal-footer",children:[a("div",{className:"settings-footer-copy",children:[a("div",{"aria-live":"polite",className:"small",id:"settingsStatus",children:m}),i&&o?a("div",{role:"status",className:"small settings-restart-required",children:"Restart required"}):null,a("button",{className:"settings-link-button",onClick:u,type:"button",children:"Show getting started"})]}),a("button",{className:"settings-save","data-primary-action":"true",disabled:p,id:"settingsSave",onClick:c,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function sR(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};Object.entries(t).forEach(([l,d])=>{o(l)||Kt(r,l)&&!i.has(l)||b3(d,n[l])||(s[l]=d)});const c="observer_tier_routing_enabled";return(["observer_runtime","observer_provider","observer_model","observer_auth_source"].some(l=>Kt(s,l))||i.has(c))&&typeof t[c]=="boolean"&&!Kt(r,c)&&!o(c)&&(s[c]=t[c]),s}function C5(e){const t=s=>{const c=md[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.onValuesChanged?.(),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 k5(e,t,n,r){return r||t.length>0||n.length>0||e.sync?.ok===!1}function I5(e){return Array.isArray(e.applying_keys)&&e.applying_keys.length>0}function R5(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=>mh(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>mh(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>mh(String(p))):[],s=I5(n),c=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],l=Array.isArray(n.manual_actions)?n.manual_actions:[],d=n.sync&&typeof n.sync=="object"?n.sync:{},u=[];r.length&&u.push(`Applied now: ${hd(r)}.`),i.length&&u.push(`Live settings updated: ${hd(i)}.`),s&&u.push("Observer settings saved. Applying them now; new events will wait."),d.attempted&&typeof d.message=="string"&&d.message?u.push(`Sync: ${d.message}.`):Array.isArray(d.affected_keys)&&d.affected_keys.length&&typeof d.reason=="string"&&d.reason&&u.push(`Sync: ${d.reason}.`),o.length&&u.push(`Restart required for ${hd(o)}. Run: codemem serve restart`),c.forEach(p=>{u.push(p)}),l.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&u.push(`If needed: ${p.command}.`)}),u.length||u.push("Saved.");const f=k5(n,o,c,s);return{message:u.join(" "),type:f?"warning":"success"}}function P5(){return[["observer_runtime","observerRuntime"],["observer_provider","observerProvider"],["observer_model","observerModel"],["observer_auth_source","observerAuthSource"]].some(([e,t])=>W.touchedKeys.has(e)&&Ze(jt.value.renderState.values[t])!==W.baseline[e])}function cR(){const e=W.observerApply;if(!e)return;const t=e.active?.tierRoutingEnabled;e.state!=="active"||typeof t!="boolean"||W.observerTierRoutingExplicit||W.touchedKeys.has("observer_tier_routing_enabled")||P5()||(W.baseline.observer_tier_routing_enabled=t,GI({observerTierRoutingEnabled:t}))}function lR(e){if(!e||typeof e!="object")return;const t=e.observer_apply;!t||!["active","applying","failed"].includes(t.state)||(W.observerApply=t,cR(),zr({}))}function N5(){try{const e=sR({current:Fh({allowUntouchedParseErrors:!0}),baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:KI});return Object.keys(e).some(t=>W.restartRequiredKeys.has(t)&&!(t in W.envOverrides))}catch{return!1}}var T5=()=>C6({...zt().renderState.values,observerRuntime:Gs()?Uh():"api_http"},W.envOverrides),A5=()=>k6(zt().renderState.values),E5=()=>I6(zt().renderState.values),x5=()=>R6(zt().renderState.values),D5=()=>P6(zt().showAdvanced),{onTextInput:j5,onSelectValueChange:O5,onSwitchInput:L5}=C5({getTouchedKeys:()=>W.touchedKeys,getValues:()=>zt().renderState.values,updateFormState:GI,setDirty:e=>Od(e),onValuesChanged:cR});async function $5(){try{lR(await zP())}catch{Y("Observer settings could not be applied. Retry from Settings.","warning")}}async function M5(){try{lR(await qg()),WI(await Bg())}catch{Y("Observer status could not be refreshed. Try again.","warning")}}function F5(){const e=jt.value.renderState.observerStatus,t=W.observerApply;return a(U,{children:[a(U6,{status:e,onOpenDiagnostics:q5}),a(M6,{status:t,onRetry:()=>{$5()},onRefresh:()=>{M5()}})]})}function B5(){!W.startPolling||!W.refresh||(ra(W.startPolling,W.refresh),!zt().open&&(WG(),document.getElementById("tabBtn-feed")?.click(),JG()))}function q5(e){if(!W.startPolling||!W.refresh||(ra(W.startPolling,W.refresh),zt().open))return;const t=wl("settingsButton");queueMicrotask(()=>Tr({...e,trigger:t}))}function U5(){return{simple:String(W.effectiveConfig.observer_simple_provider??"").trim(),rich:String(W.effectiveConfig.observer_rich_provider??"").trim()}}function G5(){const e=jt.value,t=e.renderState.values,n=Array.from(new Set(e.renderState.providers.concat(t.observerProvider?[t.observerProvider]:[]))).sort((i,o)=>i.localeCompare(o)).map(i=>({label:i,value:i})),r={values:t,effectiveObserverRuntime:Uh(t.observerRuntime),hasExplicitObserverRuntime:Gs(t.observerRuntime),allowAutomaticAuthChanges:Z6(t.observerRuntime),tierProviders:U5(),observerMaxCharsDefault:String(y.configDefaults?.observer_max_chars||""),modelDefaults:W.observerModelDefaults??void 0,providerOptions:n,showAuthFile:t.observerAuthSource==="file",showAuthCommand:t.observerAuthSource==="command",showTieredRouting:t.observerTierRoutingEnabled,hiddenUnlessAdvanced:D5,onTextInput:j5,onSelectValueChange:O5,onSwitchInput:L5,getObserverModelLabel:A5,getObserverModelTooltip:E5,getObserverModelDescription:x5,getObserverModelHint:T5,protectedConfigHelp:T6};return a(S5,{panelProps:r,activeTab:e.activeTab,showAdvanced:e.showAdvanced,renderState:e.renderState,settingsDirty:e.dirty,restartRequired:N5(),onClose:()=>{W.startPolling&&W.refresh&&ra(W.startPolling,W.refresh)},onSave:()=>{W.startPolling&&W.refresh&&K5(W.startPolling,W.refresh)},onActiveTabChange:HI,onAdvancedToggle:E6,onShowGettingStarted:B5,observerStatusBannerSlot:a(F5,{})})}function H5(){return a(z6,{DialogContent:G5,onClose:ra})}function V5(){const e=Xe("settingsDialogMount");e&&ke(a(H5,{}),e)}function dR(){Xe("settingsDialogMount")&&(W.shellMounted||(V5(),W.shellMounted=!0))}function uR(e){Pi("settings-health"),W.shellMounted||dR(),Ld(!0),W.previouslyFocused=document.activeElement,e()}function ra(e,t){if(zt().dirty&&!globalThis.confirm("Discard unsaved changes?")){Ld(!0);return}Ld(!1),A6(),(W.previouslyFocused&&typeof W.previouslyFocused.focus=="function"?W.previouslyFocused:wl("settingsButton"))?.focus(),W.previouslyFocused=null,W.touchedKeys=new Set,e(),t()}async function K5(e,t){if(!zt().renderState.isSaving){zr({isSaving:!0,statusText:"Saving changes…"});try{const n=Fh({allowUntouchedParseErrors:!0}),r=sR({current:n,baseline:W.baseline,envOverrides:W.envOverrides,touchedKeys:W.touchedKeys,isProtected:KI});if(Object.keys(r).length===0){zr({isSaving:!1,statusText:"No unsaved changes"}),Od(!1),ra(e,t);return}const i=await JP(r),o=R5(i);zr({isSaving:!1,statusText:"Saved changes"}),Od(!1),ra(e,t),Y(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";zr({isSaving:!1,statusText:`Save failed: ${r}`})}}}function W5(e,t,n){W.startPolling=t,W.refresh=n,dR(),wl("settingsButton")?.addEventListener("click",()=>uR(e))}function z5(e){e.dataset.syncRenderRoot="preact"}function J5(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function lt(e,t){z5(e),ke(t,e)}function ia(e){e.dataset.syncRenderRoot==="preact"&&ke(null,e)}function Y5(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 X5(e){return typeof e=="object"&&e!==null}function Q5(e,t){return y.pairingCommandRaw="",{payloadText:e,hintText:t}}function Z5(e){if(!X5(e))return Q5("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 y.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function eJ(){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 tJ(){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 nJ(){const e=y.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 rJ(){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 iJ(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 oJ({items:e}){return a(U,{children:e.map((t,n)=>a("div",{class:"stat",children:a("div",{class:"stat-content",children:[a("div",{class:"value",children:t.value}),a("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function aJ({attempts:e,note:t}){return a(U,{children:[t?a("div",{class:"small",children:t}):null,e.map((n,r)=>a("div",{class:"diag-line",children:[a("div",{class:"left",children:[a("div",{children:[n.peerLabel," — ",n.status]}),n.detail?a("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?a("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null,n.action?a("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function pR({text:e}){return a(U,{children:e})}function sJ({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function cJ(e,t){if(!t.length){ia(e);return}lt(e,a(oJ,{items:t}))}function lJ(e,t,n){if(!t.length){ia(e);return}lt(e,a(aJ,{attempts:t,note:n}))}function Bi(e,t){lt(e,a(sJ,{...t}))}function fR(e,t,n){lt(e,a(pR,{text:n.payloadText})),t&<(t,a(pR,{text:n.hintText}))}function mR({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=x(null),f=x(null),p=x(!1);Ge(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),f.current&&(f.current.id=s)},[s,n,e]),q(()=>{if(!e){p.current=!1;return}p.current||(p.current=!0,queueMicrotask(()=>{f.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(es,{forceMount:!0,asChild:!0,children:a("div",{ref:f,id:s,className:c,hidden:!e,children:d})});return a(Za,{open:e,onOpenChange:t,children:[a(Zf,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?_n(m,l):m]})}function dJ({open:e,onOpenChange:t}){return a(mR,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[a("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),a("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),a("div",{className:"actor-create-row",children:[a("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),a(be,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),a("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),a("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),a("div",{className:"sync-ttl-group",children:[a("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),a(be,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),a("span",{children:"hours"})]}),a("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),a("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),a(Do,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),a("div",{className:"peer-meta",id:"syncInviteAdminHint"}),a("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function uJ({contentHost:e,open:t,onOpenChange:n}){return a(mR,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[a("div",{className:"peer-title",children:[a("strong",{children:"Pairing command"}),a("div",{className:"peer-actions",children:a("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),a("div",{className:"pairing-body",children:a("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),a("div",{className:"peer-meta",id:"pairingHint"})]})}function pJ(e,t){lt(e,a(dJ,{...t}))}function fJ(e,t){lt(e,a(uJ,{...t}))}function ce(e){return String(e??"").trim()}function mJ(e){return ce(e).replace(/\s+/g," ").toLowerCase()}function hJ(e){const t=ce(e);return t?t.slice(0,8):"Unnamed device"}function hR(e){return ce(e?.last_error).toLowerCase()}function gR(e){return e.includes("401")&&e.includes("unauthorized")}function vR(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var gJ={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function yR(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 vJ(e){const t=yR(e),n=ce(e.device?.device_id),r=Number(e.device?.address_count??0),i=Array.isArray(e.device?.addresses)&&e.device.addresses.some(o=>ce(o))||Number.isFinite(r)&&r>0;return!n||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":i}function Gh(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),o=wJ(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${o}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>bR(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=>bR(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:ce(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function bR(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=ce(e.error);return yJ(n)?"trust":bJ(n)?"scope":null}function yJ(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function bJ(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function _J(e){const t=ce(e?.reason);return gJ[t]??(t.replaceAll("_"," ")||"sync filters")}function wJ(e){const t=new Map;for(const n of e){const r=_J(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 _R(e){const t=ce(e.localName);if(t)return t;const n=ce(e.coordinatorName);return n||hJ(ce(e.deviceId))}function SJ(e){const t=ce(e.localName),n=ce(e.coordinatorName);return t||n?!1:!!ce(e.deviceId)}function CJ(e){const t=e.sync_health?.receive?.operations_24h??0,n=e.sync_health?.send?.operations_24h??0;return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function Hs(e){const t=ce(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=hR(e);return gR(n)?"needs-repair":vR(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function Hh(e){const t=e?.status||{},n=ce(t.peer_state),r=hR(e),i=ce(t.sync_status)==="ok"||ce(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}:gR(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}:vR(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 kJ={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 IJ(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,o]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(o??0));if(s===0)continue;const c=i;r.push({reason:c,label:kJ[c]??i,count:s})}return r.sort((i,o)=>o.count-i.count||i.label.localeCompare(o.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function wR(e){return Array.isArray(e)?e.map(t=>ce(t)).filter(t=>!!t):[]}function SR(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 Ud(e,t){return e?e.replaceAll("_"," "):t}function RJ(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=ce(r.scope_id),o=ce(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[Ud(ce(r.kind),"user"),Ud(ce(r.authority_type),"local"),`${Ud(ce(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 PJ(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=ce(n.scope_id),i=ce(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=ce(n.last_applied_cursor),c=ce(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=Ud(ce(n.authority_type),"local"),u=Number(n.membership_epoch??0),f=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(p=>!!p).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:f}}).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 NJ=["personal","private","home","mine","me"],TJ=["oss","open source","opensource","community","public"],AJ=["work","client"],EJ=["local","legacy","review"];function xJ(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>ce(t)??"").join(" ").toLowerCase()}function DJ(e){return[e.scope_id,e.label,e.kind].map(t=>ce(t)??"").join(" ").toLowerCase()}function CR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vh(e,t){const n=xJ(e);return t.some(r=>{const i=CR(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function kR(e){return Vh(e,NJ)||Vh(e,TJ)}function jJ(e){const t=DJ(e);return EJ.some(n=>{const r=CR(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function OJ(e){return!kR(e)&&(!jJ(e)||Vh(e,AJ))}function LJ(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(ce(e.discovered_via_group_id)||ce(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(kR),r=t.some(OJ);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 $J(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function MJ(e){const t=wR(e?.effective_include),n=wR(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${SR(t,"all projects")}`,o=`Exclude filter: ${SR(n,"no exclusions")}`,s=$J(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:o,summary:`${r}. ${i}; ${o}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function FJ(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=ce(n?.display_name),i=ce(n?.actor_id),o=mJ(r);if(!r||!i||!o)return;const s=t.get(o)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(o,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function IR(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=ce(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const o=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>ce(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(ce(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var BJ=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),qJ=new Set(["pending","verifying","waiting"]);function UJ(e){return(Array.isArray(e?.groups)?e.groups.map(t=>ce(t)).filter(Boolean):[]).join(", ")||"none"}function GJ(e){return ce(e?.projects?.[0]?.display_name)||"the shared Project"}function HJ(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=Hh(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function VJ(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 KJ(e){return{status:e.status,coordinator:e.coordinator,peers:Array.isArray(e.peers)?e.peers:[],operations:Array.isArray(e.shareOperations)?e.shareOperations:[],reconciliationItems:Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],shareOperationsLoadError:e.shareOperationsLoadError===!0,label:UJ(e.coordinator)}}function WJ(e){if(e.status?.enabled===!1||e.coordinator?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${e.label}. 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: ${e.label}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const t=e.operations.find(r=>r.lifecycle?.state==="needs_attention"),n=e.reconciliationItems.find(r=>r.state==="needs_attention");return t?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."}:n?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access reconciliation needs review.`,nextAction:"Open Sharing, review this Project's access decision, then sync again."}:null}function zJ(e,t){if(e?.lifecycle?.state==="revoking")return`Keep both devices online, then sync again to finish removing future access for ${t}.`;const n=e?.lifecycle?.primary_action?.kind;return n==="retry_setup"?`Open Project sharing below and retry setup for ${t}.`:n==="copy_invite"?`Copy the invitation for ${t} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${t}.`}function JJ(e){const t=e.operations.find(o=>{const s=o.lifecycle?.state;return s!==void 0&&BJ.has(s)}),n=e.reconciliationItems.find(o=>{const s=o.state;return s!==void 0&&qJ.has(s)});if(!t&&!n)return null;const r=t?GJ(t):"the shared Project",i=t?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:i?"Removal pending":"Setup pending",meta:i?`Team: ${e.label}. Future access removal for ${r} is still pending.`:`Team: ${e.label}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:zJ(t,r)}}function YJ(e){return VJ(e.status)?{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${e.label}. 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."}:HJ(e.peers,e.coordinator)?{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${e.label}. 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."}:null}function XJ(e){const t=ce(e.coordinator?.presence_status);if(t==="not_enrolled")return{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${e.label}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."};if(t!=="posted"){const n=e.coordinator?.configured===!0;return{state:"unreachable",badgeLabel:n?"Unreachable":"Setup needed",meta:n?`Team: ${e.label}. 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:n?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}}return null}function QJ(e){const t=e.status?.sync_health;return{state:t?.state==="exchange_succeeded"?"healthy":"reachable",badgeLabel:jo(t),meta:Rm(t),nextAction:t?.state==="exchange_succeeded"?null:"Review Sending and Receiving on Devices, then retry sync."}}function RR(e){const t=KJ(e);return WJ(t)??JJ(t)??YJ(t)??XJ(t)??QJ(t)}function ZJ(e){return e.discovered?.stale?e.peer?Hs(e.peer)!=="connected":!0:!1}function PR(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 eY(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 tY(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 nY(e){const t=ce(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>ce(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 rY(e,t){const n=new Map,r=i=>{const o=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,o),o};return e.forEach(i=>{const o=ce(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=ce(i?.name)}),t.forEach(i=>{const o=ce(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=ce(i?.display_name)}),[...n.values()]}function iY(e){return e.map(t=>({id:`duplicate:${t.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:t.includesLocal?5:15,title:`Possible duplicate person: ${t.displayName}`,summary:t.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:t.actorIds}))}function oY(e,t){const n=ce(e.discovered?.fingerprint),r=ce(e.peer?.fingerprint);return!e.peer||!n||!r||n===r?null:PR({id:e.deviceId,name:t,title:`${t} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."})}function aY(e,t){if(!e.peer)return[];const n=[],r=Hs(e.peer),i=Hh(e.peer);return r==="needs-repair"&&n.push(PR({id:e.deviceId,name:t,title:i.state==="needs-repairing"?`${t} needs re-pairing`:`${t} needs review`,summary:i.description||"Sync needs review. Check device sync diagnostics, then retry."})),i.state==="trusted-by-you"&&n.push(eY({id:e.deviceId,key:"other-device-trust",name:t,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),SJ({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId})&&n.push(tY({id:e.deviceId,name:t,summary:"Give this device a friendly name so it is easier to recognize later."})),n}function sY(e){const t=_R({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId}),n=oY(e,t);return n?[n]:aY(e,t)}function cY(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=rY(n,r),o=e.duplicatePersonDecisions??{},s=FJ(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[...iY(s),...i.flatMap(sY)];return{primaryStatus:RR({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>Hs(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>ZJ(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var NR={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 Yr(e){const t=document.getElementById(e);t&&t.remove()}var TR=!1;function lY(e){TR=e}var Kh=!1;function dY(e){Kh=e}var uY=new Set,Wh=new Set,zh=new Set,AR="codemem-sync-duplicate-person-decisions";function pY(e){const t=String(e||"").trim();t&&(Wh.add(t),zh.add(t),uY.add(t))}function Jh(e){const t=String(e||"").trim();return!!t&&Wh.has(t)}function fY(e){const t=String(e||"").trim();t&&Wh.delete(t)}function mY(e){const t=String(e||"").trim();return!t||!zh.has(t)?!1:(zh.delete(t),!0)}function Yh(){try{const e=localStorage.getItem(AR);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function ER(e){try{localStorage.setItem(AR,JSON.stringify(e))}catch{}}function xR(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function DR(){return Yh()}function hY(e,t){const n=xR(e);if(!n)return;const r=Yh();r[n]=t,ER(r)}function gY(e){const t=xR(e);if(!t)return;const n=Yh();delete n[t],ER(n)}function jR(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function OR(e){const t=String(e||"");return t?jR(t):""}function vY(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function yY(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Gd(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 Xh(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Gd(e)}function bY(e){return(Array.isArray(y.lastSyncPeers)?y.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function _Y(){return IR({actors:y.lastSyncActors,peers:y.lastSyncPeers,duplicatePeople:y.lastSyncViewModel?.duplicatePeople}).visibleActors}function LR(e){return _Y().filter(t=>String(t?.actor_id||"")!==e)}function wY(e,t){const n=LR(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Xh(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Qh(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=_l("div","sync-action"),i=_l("div","sync-action-text");i.textContent=n.label,i.appendChild(_l("span","sync-action-command",n.command));const o=_l("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Po(n.command,o)),r.append(i,o),e.appendChild(r)})}}function $R(e,t){return t&&e.error_redacted===!0}function SY(e){return e?{action:t=>Tr({severity:"error",subsystem:"sync",trigger:t})}:{}}function MR(){const e=document.getElementById("syncAttempts");if(!e)return;const t=y.lastSyncAttempts,n=String(y.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Bi(e,nJ());return}const r=iJ(n,t.slice(0,5).some(o=>o.status==="error")),i=t.slice(0,5).map(o=>{const s=o.started_at||o.started_at_utc||"",c=String(o.peer_device_id||"").trim(),l=Array.isArray(y.lastSyncPeers)?y.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",f=[],p=Ya();if(u&&o.error){const m=String(o.error);f.push(p?jR(m):m),$R(o,p)&&f.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&f.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!p&&o.address&&f.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:f.join(" · "),startedAt:s?sn(s):"",...SY(u),...$R(o,p)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});lJ(e,i,r)}function CY(){const e=document.getElementById("syncPrimaryStatusDetail");e&&(e.textContent="");const t=document.getElementById("syncStatusGrid"),n=document.getElementById("syncAttempts"),r=document.getElementById("syncMeta"),i=document.getElementById("syncActions");t&&Bi(t,tJ()),n&&Bi(n,rJ()),r&&(r.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."),Qh(i,[])}function oa(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function kY(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=oa(n.would_remove),o=oa(n.ambiguous),s=oa(r.applied),c=oa(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||o>0?`${o} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function IY(e){if(e.syncNoPeers)return[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:e.pending},{label:"Last sync",value:"Waiting for first peer"}];let t="Disabled";return e.retentionEnabled&&(t="Enabled"),e.retentionEnabled&&e.retentionLastRunAt&&(t=`${e.retentionDeleted.toLocaleString()} ops last run (approx)`),[{label:"State",value:e.daemonStateLabel},{label:"Pending events",value:e.pending},{label:"Last sync",value:e.lastSync?`${Ta(po(e.lastSync))} ago`:"never"},{label:"Last peer ping",value:e.lastPing?`${Ta(po(e.lastPing))} ago`:"never"},{label:"Retention",value:t}]}function FR(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Yr("syncDiagSkeleton");const r=y.lastSyncStatus;if(!r){Bi(e,eJ()),Qh(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},o=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=o.last_ping_at||r.last_ping_at||Y5(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",f=Number(r.pending||0),p=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),g=r.retention||{},b=r.cleanup_diagnostics,_=b?.stale_peer_rows??{},v=oa(_.would_remove),S=oa(_.ambiguous),w=g.enabled===!0,k=Number(g.last_deleted_ops||0),P=g.last_run_at||null,T=String(g.last_error||""),E={needs_attention:"Needs attention","offline-peers":"Offline peers",rebootstrapping:"Rebootstrapping"}[m]??yb(m),$=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,A=!$&&F===0;if(t){let H;$?H=["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"]:A?H=["Advanced sync is ready but idle","Pair another device from Devices, then return here for live peer status and recent attempts"]:H=[`Advanced state: ${E}`,`Peers: ${F}`,c?`Last sync: ${Ta(po(c))} ago`:"Last sync: never"],m==="offline-peers"&&H.push("All peers are currently offline; sync will resume automatically"),p&&m==="stopped"&&H.push(`Detail: ${p}`),p&&(m==="needs_attention"||m==="rebootstrapping")&&H.push(`Detail: ${p}`),w&&H.push(P?`Retention last ran ${Ta(po(P))} ago (approx oldest-first)`:"Retention enabled"),v>0?H.push(`${v.toLocaleString()} stale peer rows pending cleanup`):S>0&&H.push(`${S.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=H.join(" · ")}const j=$?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:f},{label:"Last sync",value:"Not running"}]:IY({daemonStateLabel:E,lastPing:l,lastSync:c,pending:f,retentionDeleted:k,retentionEnabled:w,retentionLastRunAt:P,syncNoPeers:A});!$&&!A&&(d||u)&&j.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!$&&!A&&s.seconds_since_last&&j.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!$&&!A&&o.seconds_since_last&&j.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!$&&w&&T&&j.push({label:T,value:"Retention"}),!$&&!A&&b&&j.push({label:"Cleanup",value:kY(b)}),cJ(e,j);const D=[];A||m==="offline-peers"||(m==="stopped"?(D.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),D.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?D.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?D.push({label:"Sync is rebuilding state in the background.",command:"codemem sync peers"}):d||u||m==="error"?(D.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),D.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!$&&!A&&f>0&&D.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!$&&S>0?D.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!$&&v>0&&D.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Qh(n,D)}var RY="syncRedactMount",PY="syncRedactLabel",BR=()=>{};function NY(e){BR=e}var Zh=()=>{};function eg(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;fJ(e,{contentHost:t,open:y.syncPairingOpen,onOpenChange:r=>{if(tF(r),eg(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&fR(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Zh()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=y.pairingCommandRaw;r&&await Po(r,n)})}function tg(){eg();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;fR(e,t,Z5(y.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!y.pairingCommandRaw)}function qR(){const e=document.getElementById(RY);e&<(e,h(Eo,{"aria-labelledby":PY,checked:Ya(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{nF(t),qR(),Zh(),FR(),BR(),MR(),tg()},thumbClassName:"sync-redact-switch-thumb"}))}function TY(e){Zh=e,eg(),qR()}var qi=new Map,ng=null,AY={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 EY(e){const t=e instanceof Error?e.message:String(e);return AY[t]??"Setup could not be retried. Review diagnostics for details."}function xY(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 DY(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function rg(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 jY({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=R(!1),[c,l]=R(()=>qi.get(e.operation_id)??null),d=x(null),u=e.lifecycle.primary_action;q(()=>{ng!==e.operation_id||!d.current||(ng=null,d.current.focus())},[c?.message,e.operation_id]);async function f(b){s(!0);try{let _=b;if(!_&&n){const S=(await n(e.operation_id)).lifecycle.primary_action;S?.kind==="copy_invite"&&(_=S.invite_link)}if(!_)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(S=>navigator.clipboard.writeText(S)))(_);const v={message:"Invite copied.",tone:"success"};qi.set(e.operation_id,v),l(v)}catch(_){const v={message:_ instanceof Error?_.message:"Invite could not be copied.",tone:"warning"};qi.set(e.operation_id,v),l(v)}finally{s(!1)}}async function p(){s(!0);try{const b=await t(e.operation_id),_=b.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:b.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${b.lifecycle.label}.`,tone:"success"};qi.set(e.operation_id,_),ng=e.operation_id,l(_),await r()}catch(b){const _={message:EY(b),tone:"warning"};qi.set(e.operation_id,_),l(_),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const b=e.projects.map(_=>_.project_id?.trim()).filter(_=>!!_);if(b.length!==e.projects.length){const _={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};qi.set(e.operation_id,_),l(_);return}if(!qc(b,e.person.display_name)){const _={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};qi.set(e.operation_id,_),l(_)}}function g(){if(u){if(u.kind==="copy_invite"){f(u.invite_link);return}if(u.kind==="retry_setup"){p();return}m()}}return a("section",{"aria-label":`${rg(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:rg(e.lifecycle.state)}),a("ul",{"aria-label":`${rg(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((b,_)=>a("li",{className:"peer-scope-chip",children:b.display_name},`${b.display_name}:${_}`))}),a("div",{className:"peer-scope-summary",children:e.lifecycle.label}),a("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?a("div",{className:"peer-actions",children:a("button",{"aria-busy":o,className:"settings-button",disabled:o,type:"button",onClick:g,children:o?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?a("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function OY({operations:e,...t}){const n=e[0].person,r=DY(e);return a("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[a("h3",{className:"device-row-name",children:n.display_name}),r.length>0?a("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>a("li",{children:i.display_name},i.device_id))}):null,e.map(i=>a(jY,{operation:i,...t},i.operation_id))]})}function LY(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:xY(e.operations).map(t=>a(OY,{...e,operations:t},t[0].person.actor_id))})}function $Y(e,t){lt(e,a(LY,{...t}))}function UR({title:e,detail:t}){return a("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[a("strong",{children:e}),a("span",{children:t})]})}function MY(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 FY({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Gd(e),c=bY(o),l=LR(o),d=l.map(D=>String(D.actor_id||"")).join("|"),[u,f]=R(s),[p,m]=R(!1),[g,b]=R("Rename"),[_,v]=R(!1),[S,w]=R("Merge into selected person"),[k,P]=R(""),[T,E]=R(!1);q(()=>{f(s),m(!1),b("Rename"),v(!1),w("Merge into selected person"),P(""),E(!1)},[o,c,t,s,d]);const $=l.length?wY(k,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(D=>{const H=String(D.actor_id||"");return{label:D.is_local?Xh(D):Gd(D),value:H}})];async function A(){const D=u.trim();if(!D)return;m(!0),b("Saving…");let H=!1;try{await n(o,D),H=!0}catch{b("Retry rename")}finally{m(!1),H&&b("Rename")}}async function j(){if(!k)return;const D=l.find(V=>String(V.actor_id||"")===k);if(!D||!await Dn({title:`Merge ${s} into ${Gd(D)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;v(!0),w("Merging…");let H=!1;try{await r(k,o),H=!0}catch{w("Retry merge")}finally{v(!1),H&&w("Merge into selected person")}}return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:Xh(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?MY(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:a("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),a("div",{className:"actor-actions",children:e.is_local?a("div",{className:"peer-meta",children:"Rename yourself in config"}):a(U,{children:[a(be,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:p||_,type:"text",value:u,onInput:D=>f(D.currentTarget.value),onKeyDown:D=>ns(D,{onSubmit:()=>{A()},disabled:p||_||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:p||_,onClick:()=>{A()},children:g}),a("button",{type:"button",className:"settings-button danger",disabled:p||_,onClick:async()=>{await Dn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:p||_,onClick:()=>E(D=>!D),children:T?"Hide duplicate cleanup":"Show duplicate cleanup"}),T?a(U,{children:[a("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),a("div",{className:"actor-merge-controls",children:[a(En,{ariaLabel:`Merge ${s} into another person`,disabled:_||l.length===0,onValueChange:P,options:F,placeholder:"Merge into person",triggerClassName:"actor-merge-select",value:k}),a("button",{type:"button",className:"settings-button",disabled:_||l.length===0||!k,onClick:()=>{j()},children:S})]}),a("div",{className:"peer-meta actor-merge-note",children:$})]}):null]})})]})}function BY({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(U,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(FY,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(UR,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function qY(e,t){lt(e,a(BY,{...t}))}function UY(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function GY(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${sn(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function HY({devices:e}){return a(U,{children:GY(e)})}function VY(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 KY(e){const t=UY(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),ia(e.mount),ia(e.meta);return}const n=t.map(VY),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,lt(e.mount,a(En,{ariaLabel:"Legacy device",id:"syncLegacyDeviceSelect",onValueChange:e.onValueChange,options:n,value:r})),lt(e.meta,a(HY,{devices:t}))}function Xr({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}var WY="Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",zY="Review whether explicit Space access matches this device's intended role.";function JY(){return a("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[a("title",{children:"Chevron"}),a("path",{d:"m9 18 6-6-6-6"})]})}function YY(e){switch(Hs(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Hd=null,GR=0,ig=new Set;function HR(e){if(Hd!==e){Hd=e,GR+=1;for(const t of ig)t(GR)}}function XY(){const[,e]=R(0);return q(()=>(ig.add(e),()=>{ig.delete(e)}),[]),Hd}var QY={bidirectional:{glyph:"↕",label:"Applied and acknowledged operations observed (24h)"},publishing:{glyph:"↑",label:"Acknowledged operations observed (24h)"},subscribed:{glyph:"↓",label:"Applied operations observed (24h)"},none:null};function ZY(e){return e?`Initiated exchange: ${sn(e)}`:"Initiated exchange: not recorded"}function VR(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 e9(e,t,n,r=!1,i=!1,o=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||o&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${VR(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: ${VR(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 t9(e){y.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function n9(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 r9(){window.location.hash="advanced/teams/administration"}function og(e=y.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function i9({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),o=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||o,c=Hh(e),l=QY[CJ(e)],d=e.status||{},u=RJ(e),f=Jh(i),p=f&&u.total===0,m=LJ(e),g=IJ(e),b=PJ(e),_=e.project_scope||{},v=MJ(_),S=vY(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(le=>String(le)))):[],k=Number(e.address_count??0),P=Number.isFinite(k)&&k>0?k:0,T=w.length?w.map(le=>Ya()?OR(le):le).join(" · "):P>0?`${P} ${P===1?"address":"addresses"} hidden`:"No addresses",E=y.lastDeviceIdentityInventory?.items.find(le=>le.deviceId===i||le.evidenceDeviceIds.includes(i)),$=e9(E,String(e.actor_id||"")||null,y.lastSyncActors,y.deviceIdentityInventoryLoadError,y.lastDeviceIdentityInventory?.truncated===!0,y.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),A=String(d.last_ping_at||d.last_ping_at_utc||""),j=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,D=mY(i),H=x(null),[V,z]=R(o),[M,C]=R(()=>y.syncPeerFeedbackById.get(i)??null),[O,B]=R(!1),[G,ne]=R("Save name"),[oe,te]=R(!1),[Me,pe]=R(!1),[Be,Te]=R("Remove device");q(()=>{f&&u.total>0&&fY(i)},[u.total,i,f]),q(()=>{z(o),C(y.syncPeerFeedbackById.get(i)??null),B(!1),ne("Save name"),te(!1),pe(!1),Te("Remove device")},[o,e.actor_id,i]),q(()=>{!D||!H.current||queueMicrotask(()=>H.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[D]);async function ae(){if(!i)return;const le=V.trim();if(!le){const kt={message:"Enter a friendly name for this device.",tone:"warning"};C(kt),y.syncPeerFeedbackById.set(i,kt),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}B(!0),ne("Saving…");try{const kt=await n(i,le);C(kt),y.syncPeerFeedbackById.set(i,kt),ne("Save name")}catch{ne("Retry")}finally{B(!1)}}async function _e(){if(p){const le=og();if(!await Dn({title:`Sync ${o} before advanced rule review?`,description:le?"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:le?"Review legacy Team/Space setup first":"Cancel"}))return}te(!0);try{const le=await r(e,S);C(le),le&&y.syncPeerFeedbackById.set(i,le)}finally{te(!1)}}async function Ce(){if(!i||!await Dn({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;pe(!0),Te("Removing…");let le=!1;try{await t(i,s),le=!0}catch{Te("Retry remove")}finally{pe(!1),le&&Te("Remove device")}}const Q=XY()===i&&i!=="",we=`device-drawer-${i||"unknown"}`,se=YY(e),ot=ZY(F),ve=og(),Ot=`${Q?"Collapse":"Expand"} device ${o}`;return a(Za,{asChild:!0,open:Q,onOpenChange:le=>{le?HR(i):Hd===i&&HR(null)},children:a("div",{ref:H,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Zf,{asChild:!0,children:a("button",{"aria-label":Ot,className:"device-row-head device-row-head--trigger",type:"button",children:[a(jn,{state:se}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a(Ne,{variant:"badge",tone:c.isWarning?"badge-offline":"badge-online",children:c.badgeLabel}),p?a(Ne,{variant:"badge",tone:"actor-badge",children:"Review advanced rules"}):null,a(Ne,{variant:"badge",tone:u.isWarning?"badge-offline":"actor-badge",title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),g.badgeLabel?a(Ne,{variant:"badge",tone:"badge-offline",title:WY,children:g.badgeLabel}):null,m.badgeLabel?a(Ne,{variant:"badge",tone:"badge-offline",title:zY,children:m.badgeLabel}):null,e.discovered_via_group_id?a(Ne,{variant:"badge",tone:"actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:ot}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(JY,{})})]})}),a(es,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:we,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:oe,onClick:()=>{_e()},title:S?void 0:"Address details are hidden; sync will target this device by ID.",children:oe?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(be,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:O,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:V,onInput:le=>z(le.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:O,onClick:()=>{ae()},children:G}),a("button",{type:"button",className:"settings-button danger",disabled:Me,onClick:()=>{Ce()},children:Be})]}),a("div",{className:"peer-scope",children:[D?a("div",{className:"peer-meta",children:ve?"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."}):p?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:T}),j?a("div",{className:"peer-meta",children:j}):null,a("div",{className:"peer-meta",children:[ot,A?`Ping: ${sn(A)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(le=>a("li",{className:"peer-scope-chip",title:le.detail,children:le.label},le.scopeId))}):null,m.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:m.title}),a("div",{children:m.message}),a("div",{children:m.detail})]}):null,a("div",{className:"peer-meta",children:v.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:b.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":b.emptyMessage}),b.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:b.rows.map(le=>a("li",{title:le.detail,children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:`badge ${le.status==="received"?"badge-online":"actor-badge"}`,children:le.badgeLabel})]},le.scopeId))}):null,g.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":g.total,children:[a("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),a("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),a("ul",{className:"peer-scope-rejections-list",children:g.reasons.map(le=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:"peer-scope-rejection-count",children:le.count.toLocaleString()})]},le.reason))}),g.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",sn(g.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:$.summary}),a("div",{className:"peer-meta",children:$.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:n9(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>t9(E?.deviceId??i),children:$.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[v.statusLabel,". ",v.summary," ",v.note]}),ve?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:r9,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(Xr,{feedback:M})]})]})]})})}function o9(e){const t=y.syncPeersSectionFeedback,n=y.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(U,{children:[a(Xr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(i9,{peer:i,...e},o)})]}):a(U,{children:[a(Xr,{feedback:t}),a(UR,{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 a9(e,t){lt(e,a(o9,{...t}))}var Qr=async()=>{},Vd="";function ag(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function s9(e){Qr=e}function c9(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Yr("syncActorsSkeleton"),ag(!1);const n=IR({actors:y.lastSyncActors,peers:y.lastSyncPeers,duplicatePeople:y.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.`)),qY(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await jT(i,o),await Qr()},onMerge:async(i,o)=>{try{await uv(i,o),Y("People combined. Assigned devices moved to the selected person."),await Qr()}catch(s){throw Y(ft(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await OT(i),Y("Person removed. Assigned devices have been unassigned."),await Qr()}catch(o){throw Y(ft(o,"Failed to remove person."),"warning"),o}}})}function l9(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");ag(!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&&Bi(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function d9(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;$Y(e,{operations:y.lastShareOperations,onAdvance:n=>kT(n),onLoadOperation:n=>CT(n),onReload:Qr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=y.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":y.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function sg(){const e=document.getElementById("syncPeers");if(!e)return;Yr("syncPeersSkeleton");const t=y.lastSyncPeers,n=Array.isArray(t)?t:[];yY(y.syncPeersSectionFeedback,n)&&(y.syncPeersSectionFeedback=null),a9(e,{peers:n,onRename:async(r,i)=>{try{return await Xg(r,i),await Qr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:ft(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await Tu({address:i,peerDeviceId:o||void 0}),c=Gh(s);let l;c.ok?o&&Jh(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${og()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await Qr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(o){return{message:ft(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Yg(r);const o={message:`Removed peer ${i}.`,tone:"success"};return y.syncPeerFeedbackById.delete(r),y.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await Qr(),o}catch(o){return{message:ft(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function u9(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");ag(!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&&Bi(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&&Bi(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 KR(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(y.lastSyncLegacyDevices)?y.lastSyncLegacyDevices:[];KY({devices:r,meta:n,mount:t,onValueChange:i=>{i!==Vd&&(Vd=i,KR())},panel:e,value:Vd})}function p9(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{ns(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){gi(n,"Enter a name for the person.");return}za(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await DT(i),Y("Person created."),n.value="",await e()}catch(o){Y(ft(o,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(Vd||"").trim();if(!i||!r||!await Dn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const o=r.textContent||"Attach device history";r.textContent="Attaching…";try{await LT(i),Y("Old device history attached to you."),await e()}catch(s){Y(ft(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function f9(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function cg(e=f9()){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 WR=!1;function m9(){WR||(WR=!0,window.addEventListener("hashchange",()=>{cg()}))}var Mn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function h9(e){Mn.loadSyncData=e}var g9=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function v9(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=y.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 lg(){const e=document.getElementById("syncAdminDisclosureMount");e&&pJ(e,{open:TR,onOpenChange:t=>{lY(t),lg(),Wd(),dg()}})}function zR(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function dg(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(y.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(y.lastTeamInvite?.warnings)?y.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Kd(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=y.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 Wd(){const e=document.getElementById("syncInvitePolicyMount");e&<(e,h(En,{ariaLabel:"Join policy",id:"syncInvitePolicy",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==Mn.invitePolicy&&(Mn.invitePolicy=n,Wd())},options:g9,value:Mn.invitePolicy}))}function y9(e){const t=(e.projects??[]).map(n=>`${n.display_name} (${n.existing_memory_count} existing ${n.existing_memory_count===1?"memory":"memories"})`).join(", ");return`${e.inviter_name||"A teammate"} invited you${e.team_name?` through ${e.team_name}`:""} to share ${t||"selected projects"}.`}function b9(e){if(!e.length){Y("Invite created. Copy the text above and share it with your teammate.","success");return}const t=e.length===1?"1 warning":`${e.length} warnings`;Y(`Invite created. Copy it above and review ${t}.`,"warning")}function _9(e){const t=e;if(!(t.restart_required===!0||t.setup_state==="pending_inviter"||e.status==="pending_setup"))return{message:"Project invitation accepted.",tone:"success"};const n=typeof t.detail=="string"?t.detail.trim():"";let r="Project invitation accepted. Setup is still pending.";return t.restart_required===!0?r="Project invitation accepted. Restart codemem to finish setup.":t.setup_state==="pending_inviter"&&(r="Project invitation accepted. Waiting for the inviter to finish setup."),{message:n||r,tone:"warning"}}function w9(e){const t=e;if(t.type==="project_share")return _9(e);if(t.type==="pair"){const n=String(t.peer_device_id??"").trim();return{message:n?`Paired with device ${n.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}return{message:e.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"}}function S9(e,t){lg(),Wd();const n=document.getElementById("operationStatusRoot");n&&Zp(n);const r=document.getElementById("syncNowButton"),i=document.getElementById("syncShareProjectsButton"),o=document.getElementById("syncCreateInviteButton"),s=document.getElementById("syncInviteGroup"),c=document.getElementById("syncInviteTtl"),l=document.getElementById("syncInviteOutput"),d=document.getElementById("syncJoinButton"),u=document.getElementById("syncJoinInvite"),f=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),m=document.getElementById("syncProjectInviteReviewHeading"),g=document.getElementById("syncRecipientName"),b=document.getElementById("syncRecipientDeviceName");let _="",v,S=0;const w=document.getElementById("syncPairingReview"),k=["syncPairingDeviceId","syncPairingFingerprint","syncPairingAddresses"].map(F=>document.getElementById(F)),P=()=>{w&&(w.hidden=!0);for(const F of k)F&&(F.textContent="")},T=F=>{if(!w||k.some(j=>!j))throw new Error("Pairing review unavailable. Refresh and try again.");const A=[F.device_id,F.fingerprint,F.addresses.join(`
|
|
121
|
+
`)];k.forEach((j,D)=>{j&&(j.textContent=A[D]??"")}),w.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},E=(F,A)=>A===S&&u?.value.trim()===F;i?.addEventListener("click",()=>{qc()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const $=async(F,A)=>{const j=await Jg(F);return E(F,A)?(v=j.kind,j.kind==="pair"?(T(j),"other"):j.kind!=="project_share_invite"||!f||!g||!b?"other":(p&&(p.textContent=y9(j)),g.value=mo(j.recipient_name),b.value=mo(j.device_name),f.hidden=!1,_=F,d&&(d.textContent="Accept and start syncing"),m?.focus(),"project")):"stale"};u?.addEventListener("input",()=>{S+=1,u.value.trim()!==_&&(_="",v=void 0,f&&(f.hidden=!0),P(),d&&(d.textContent="Review invite"))}),o?.addEventListener("click",async()=>{if(!o||!s||!c||!l||o.disabled)return;const F=s.value.trim(),A=Number(c.value);let j=!0;if(F?za(s):j=gi(s,"Team name is required."),!A||A<1?j=gi(c,"Must be at least 1 hour."):za(c),!!j){o.disabled=!0,o.textContent="Creating…";try{const D=await Vg({group_id:F,policy:Mn.invitePolicy,ttl_hours:A||24});y.lastTeamInvite=D,dg(),l.value=String(D.encoded||""),l.hidden=!1,l.focus(),l.select(),b9(Array.isArray(D.warnings)?D.warnings:[])}catch(D){Y(ft(D,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),o.textContent="Retry",o.disabled=!1;return}finally{o.disabled&&(o.disabled=!1,o.textContent="Create invite")}}}),u?.addEventListener("keydown",F=>{ns(F,{onSubmit:()=>d?.click(),disabled:!d||d.disabled})}),d?.addEventListener("click",async()=>{if(!d||!u||d.disabled)return;const F=u.value.trim();if(!F){gi(u,"Paste a team invite or pairing payload.");return}if(za(u),_!==F){const j=S;d.disabled=!0;try{const D=await $(F,j);if(D==="project"||D==="stale")return}catch(D){if(!E(F,j))return;gi(u,ft(D,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{d.disabled=!1}if(!E(F,j))return;_=F,d.textContent="Accept invite";return}const A=f&&!f.hidden?{recipient_name:g?.value.trim()??"",device_name:b?.value.trim()??""}:void 0;if(A){const j=D=>mo(D)==="";if(j(A.recipient_name)){g&&gi(g,"Enter a human-readable name using 120 characters or fewer.");return}if(j(A.device_name)){b&&gi(b,"Enter a human-readable device name using 120 characters or fewer.");return}}d.disabled=!0,d.textContent="Accepting…";try{const j=await Su(F,A,v);y.lastTeamJoin=j;let D=w9(j);y.syncJoinFlowFeedback=D,Kd(),u.value="",S+=1,_="",v=void 0,P(),f&&(f.hidden=!0);try{await t()}catch(H){D={message:ft(H,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},y.syncJoinFlowFeedback=D,Kd()}}catch(j){y.syncJoinFlowFeedback={message:ft(j,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Kd(),d.textContent="Retry",d.disabled=!1;return}finally{d.disabled&&(d.disabled=!1,d.textContent="Review invite")}}),C9(r,e)}function C9(e,t){let n=!1;e&&(e.disabled=y.viewerActorId===null||e.getAttribute("aria-busy")==="true"),e?.addEventListener("click",async()=>{if(!e||n||e.disabled)return;const r=y.viewerActorId;if(r===null)return;n=!0,e.disabled=!0,e.setAttribute("aria-busy","true"),e.textContent="Syncing…";const i=SL("Syncing devices…","You can keep browsing."),o=(c,l)=>{i?i.finish(c,l):Y(c,l)};let s=!1;try{const c=await Tu();if(!I9(c)||r!==y.viewerActorId)throw new Error("Unconfirmed sync result");const l=Gh(c);o(l.message,l.warning?"warning":"success"),s=!0}catch(c){o(k9(c,r),"warning")}finally{n=!1,e.disabled=y.viewerActorId===null,e.removeAttribute("aria-busy"),e.textContent="Sync now"}s&&t()})}function k9(e,t){return t===y.viewerActorId&&e instanceof Error&&e.message==="sync_disabled"?"Sync is disabled. Enable device sync in Settings before trying again.":"Couldn’t confirm whether sync finished. Check device sync status before retrying."}function I9(e){return!e||typeof e!="object"||!("items"in e)||!Array.isArray(e.items)?!1:e.items.every(t=>t&&typeof t=="object"&&typeof t.peer_device_id=="string"&&typeof t.ok=="boolean"&&ug(t.opsIn)&&ug(t.opsOut)&&(t.opsSkipped===void 0||ug(t.opsSkipped))&&(t.error===void 0||typeof t.error=="string")&&Array.isArray(t.addressErrors))}function ug(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function R9({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(jn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ne,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state!=="needs-attention"?a(ZS,{health:y.lastSyncStatus?.sync_health}):a("div",{className:"advanced-sync-status-label",children:[a(jn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ne,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function pg({element:e,hidden:t=!1,restoreParent:n=null}){const r=x(null);return Ge(()=>{e&&(e.hidden=t)},[e,t]),Ge(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function P9({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(U,{children:[a("div",{className:"sync-action",children:a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide team setup":"Set up a new team instead"})}),e?a(pg,{element:e,hidden:!t,restoreParent:n}):null]})}function N9({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(U,{children:[c?a(U,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(pg,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(U,{children:[r?a(pg,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(P9,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function zd({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function T9({item:e,onAction:t}){const[n,r]=R(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function A9({request:e,onApprove:t,onDeny:n}){const[r,i]=R(null),[o,s]=R(null),[c,l]=R("Approve"),[d,u]=R("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(Xr,{feedback:o})]})}function E9({onReview:e,row:t}){const[n,r]=R(!1),[i,o]=R(null),s=t.actionLabel||"Pair with this device",[c,l]=R(s);return a(U,{children:[a("button",{"aria-label":`${c} for ${t.displayName}`,className:"settings-button",disabled:n,onClick:async()=>{r(!0),l("Pairing…"),o({message:`Pairing ${t.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const d=await e(t)||null;o(d),l(d?.tone==="warning"?"Retry":t.actionLabel||s)}catch{o({message:`Pairing ${t.displayName} failed. Try again.`,tone:"warning"}),l("Retry")}finally{r(!1)}},type:"button",children:c}),a(Xr,{feedback:i})]})}function x9({onInspect:e,onRemove:t,row:n}){const[r,i]=R(!1),[o,s]=R(null),[c,l]=R("Remove broken device record");return a(U,{children:[a("button",{"aria-label":`Open details for ${n.displayName}`,className:"settings-button",disabled:r,onClick:()=>e(n),type:"button",children:"Open device details"}),a("button",{"aria-label":`${c} for ${n.displayName}`,className:"settings-button danger",disabled:r,onClick:async()=>{i(!0),l("Removing…");try{s(await t(n)||null),l("Remove broken device record")}catch{l("Retry")}finally{i(!1)}},type:"button",children:c}),a(Xr,{feedback:o})]})}function D9({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a(Ne,{variant:"badge",tone:e.availabilityLabel==="Offline"?"actor-badge":"actor-badge local",children:e.availabilityLabel}),a(Ne,{variant:"badge",tone:"actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a(Ne,{variant:"badge",tone:"actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(E9,{onReview:r,row:e}):null,e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(x9,{onInspect:t,onRemove:n,row:e}):null]})]})}function j9(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(U,{children:[r?a(zd,{label:"Needs attention"}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(T9,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null]})}function O9({children:e}){return e?a(U,{children:[a(zd,{label:"Add devices & teammates"}),e]}):null}function L9({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!y.syncDiscoveredFeedback?null:_n(a(U,{children:[a(zd,{count:t.length||void 0,label:"Devices waiting for review"}),a(Xr,{feedback:y.syncDiscoveredFeedback}),t.map(o=>a(D9,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function $9({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!y.syncJoinRequestsFeedback?null:_n(a(U,{children:[a(zd,{count:t.length||void 0,label:"Join requests to review"}),a(Xr,{feedback:y.syncJoinRequestsFeedback}),t.map(i=>a(A9,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function JR(e){return a(U,{children:[a(j9,{...e}),a(O9,{children:e.children}),a($9,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(L9,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function YR(e){e&&(e.textContent="")}function Jd(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 M9(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vs(){return M9()?"auto":"smooth"}var fg="syncTeamActionsMount",F9="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function B9(e,t,n=!1){return e.length>1&&(!t||n)}function q9(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 U9(e,t){const n=document.createElement("div");n.id=fg,e.appendChild(n),lt(n,h(JR,{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 XR(e,t){const n=document.getElementById(fg);n&&(ia(n),n.remove()),YR(e),t.forEach(r=>{YR(r)})}function G9(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");XR(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,U9(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function Ks(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;lg(),Wd(),dg(),Kd(),v9();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Yr("syncTeamSkeleton"),zR();const f=y.lastSyncCoordinator,p=V9();H9(p.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},g=C=>{if(m(),C.kind==="possible-duplicate-person"){const ne=document.getElementById("syncActorsList");ne instanceof HTMLElement&&(ne.scrollIntoView({block:"center",behavior:Vs()}),Jd(ne));return}const O=String(C.deviceId||"").trim();if(!O)return;if(C.kind==="name-device"){const ne=document.querySelector(`[data-device-name-input="${CSS.escape(O)}"]`);if(ne instanceof HTMLInputElement){ne.scrollIntoView({block:"center",behavior:Vs()}),ne.focus(),ne.select(),Jd(ne);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(O)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:Vs()}),Jd(B);return}const G=document.querySelector(`[data-discovered-device-id="${CSS.escape(O)}"]`);G instanceof HTMLElement&&(G.scrollIntoView({block:"center",behavior:Vs()}),Jd(G))},b=async C=>{const O=Array.isArray(C.actorIds)?C.actorIds.map(te=>String(te||"").trim()).filter(Boolean):[],B=(Array.isArray(y.lastSyncActors)?y.lastSyncActors:[]).filter(te=>O.includes(String(te?.actor_id||"").trim()));if(B.length<2){Y("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const G=await p2({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(te=>({actorId:String(te?.actor_id||""),label:String(te?.display_name||te?.actor_id||"Unknown person"),isLocal:!!te?.is_local}))});if(G.action==="different-people"){hY(O,"different-people"),Y("Okay. I will keep these people separate on this device."),await Mn.loadSyncData();return}if(G.action!=="merge")return;const ne=B.find(te=>String(te?.actor_id||"")===G.primaryActorId),oe=B.find(te=>String(te?.actor_id||"")===G.secondaryActorId);if(!ne?.actor_id||!oe?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await uv(String(ne.actor_id),String(oe.actor_id)),gY(O),Y(`Combined duplicate people into ${String(ne.display_name||ne.actor_id)}.`),await Mn.loadSyncData()}catch(te){try{await Mn.loadSyncData()}catch{}Y(ft(te,"Failed to combine these people."),"warning")}},_=async C=>await mm({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:C,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:O=>O.trim()?null:"Enter a device name to pair this device."}),v=!!f?.configured,S=nY(f);e.title=v?String(f.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?q9(w,e,p.primaryStatus):e.textContent=p.primaryStatus.meta,!v){G9({actions:n,setupPanel:t,primaryStatus:p.primaryStatus});return}t.hidden=!0,n.hidden=!1;const k=String(f.presence_status||""),P=Array.isArray(y.lastSyncPeers)?y.lastSyncPeers:[],T=Array.isArray(p.attentionItems)?p.attentionItems:[],E=Array.isArray(f.discovered_devices)?f.discovered_devices:[],$=String(f.coordinator_url||"").trim(),F=E.map(C=>{const O=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),G=_R({coordinatorName:B,deviceId:O})||"Discovered device",ne=O&&G!==O?O:null,oe=String(C.fingerprint||"").trim(),te=String(C.incoming_reciprocal_request_id||"").trim(),Me=Array.isArray(C.groups)?C.groups.map(vr=>String(vr||"").trim()).filter(Boolean):[],pe=P.find(vr=>String(vr?.peer_device_id||"")===O),Be=B9(Me,!!pe,C.needs_local_approval===!0),Te=yR({device:C,pairedLocally:!!pe}),ae=String(pe?.fingerprint||"").trim(),_e=!!pe&&!!oe&&!!ae&&ae!==oe,Ce=y.pendingCoordinatorApprovalsByDeviceId.get(O),Q=C.needs_local_approval===!0&&Ce?.coordinatorUrl===$&&Ce?.incomingRequestId===te,we=Q?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",se=!Q&&!S&&vJ({device:C,hasAmbiguousCoordinatorGroup:Be,pairedLocally:!!pe}),ot=Array.isArray(C.addresses)?C.addresses:[],ve=Number(C.address_count??0),Ot=Number.isFinite(ve)&&ve>0?ve:0,at=W9({pairedLocally:!!pe,device:C,addressCount:ot.length+Ot}),le=[ot.length?ot.map(vr=>Ya()?OR(String(vr||"")):String(vr||"")).filter(Boolean).join(" · "):Ot>0?`${Ot} ${C.stale?"last-known":"fresh"} ${Ot===1?"address":"addresses"} hidden`:"No fresh addresses"];!ot.length&&ne&&le.push(`device id: ${O}`);let kt=null,tt=se?"accept":"none",Xs=null;_e?tt="conflict":Q?(kt="Waiting for refreshed coordinator status. You do not need to approve again.",tt="approval-pending"):S&&(!pe||Te.state==="needs-your-approval")?(kt=S.message,tt="setup-blocked"):Be?(kt="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",tt="ambiguous"):at?(kt=at.actionMessage,tt=at.mode):pe&&Jh(O)?(kt="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",tt="scope-pending"):pe?.last_error?(le.push(`error: ${String(pe.last_error)}`),se||(tt="paired")):pe?.status?.peer_state?(le.push(`status: ${String(pe.status.peer_state)}`),se||(tt="paired")):pe&&!se&&(tt="paired"),tt==="paired"&&(Xs=z9(Te.state,Te.description,pe?.last_error));const Qs=J9(_e,!!pe);return{actionMessage:kt,actionLabel:Te.actionLabel||(pe?"Review device":"Pair with this device"),approvalBadgeLabel:Q?"Approval sent":Te.badgeLabel,approvalState:we,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:Qs,coordinatorUrl:$,deviceId:O,displayName:G,displayTitle:ne,fingerprint:oe,groupId:Me[0]??"",incomingRequestId:te,mode:tt,note:le.join(" · "),pairedMessage:Xs}}),A=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),j=T.filter(C=>!C.deviceId||!A.has(C.deviceId)),D=[],H=F.filter(C=>C.mode!=="paired"&&C.mode!=="none"&&C.mode!=="scope-pending"),V=F.filter(C=>C.mode==="accept"||C.mode==="scope-pending").length,z=j.length+D.length+V;l&&(l.hidden=H.length===0&&!y.syncDiscoveredFeedback),d&&(d.textContent=H.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=D.length===0&&!y.syncJoinRequestsFeedback),XR(n,[c,u]);const M=document.createElement("div");M.id=fg,n.appendChild(M),lt(M,h(JR,{actionItems:j,actionableCount:z,children:h(N9,{invitePanel:r,invitePanelOpen:Kh,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(dY(!Kh),Ks())},presenceStatus:k}),discoveredListMount:u,discoveredRows:H,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async C=>{if(C.kind==="possible-duplicate-person"){await b(C);return}g(C)},onDenyJoinRequest:async()=>null,onInspectConflict:C=>{m();const O=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(O instanceof HTMLElement){O.scrollIntoView({block:"center",behavior:Vs()}),Y(`Opened the conflicting local device record for ${C.displayName}.`,"warning");return}Y("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async C=>{if(!await Dn({title:`Remove ${C.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 Yg(C.deviceId);const O={message:`Removed the broken local device record for ${C.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return y.syncDiscoveredFeedback=O,await Mn.loadSyncData(),O}catch(O){return{message:ft(O,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async C=>{try{const O=await _(C.displayName);return O?await K9(C,O):null}catch(O){return{message:ft(O,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:D,presenceStatus:k,primaryStatus:p.primaryStatus}))}function H9(e){const t=document.getElementById("syncAdvancedStatusMount");t&<(t,h(R9,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function V9(){return y.lastSyncViewModel||{primaryStatus:RR({status:y.lastSyncStatus,coordinator:y.lastSyncCoordinator,peers:y.lastSyncPeers,shareOperations:y.lastShareOperations,shareOperationsLoadError:y.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function K9(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await VN(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&y.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(y.pendingAcceptedSyncPeers)?y.pendingAcceptedSyncPeers.filter(f=>String(f?.peer_device_id||"").trim()!==e.deviceId):[];y.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],pY(e.deviceId);let u=n?{message:F9,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"};y.syncDiscoveredFeedback=u,n&&Ks();try{t.trim()!==l.trim()&&(await Xg(e.deviceId,t.trim()),y.pendingAcceptedSyncPeers=y.pendingAcceptedSyncPeers.map(f=>String(f?.peer_device_id||"").trim()===e.deviceId?{...f,name:t.trim()}:f),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(f){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ft(f,"Device connected, but naming did not finish."),tone:"warning"}}y.syncDiscoveredFeedback=u;try{await Mn.loadSyncData()}catch(f){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ft(f,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},y.syncDiscoveredFeedback=u}return u}function W9({pairedLocally:e,device:t,addressCount:n}){return e&&t.needs_local_approval!==!0?null:t.stale?{actionMessage:"Wait for a fresh coordinator presence update, then review this device again here.",mode:"stale"}:e||n>0?null:{actionMessage:"Wait for this device to publish a fresh address, then refresh and review it.",mode:"waiting-address"}}function z9(e,t,n){if(e==="waiting-for-other-device")return t||"Waiting on the other device.";const r=String(n||"").toLowerCase();return r.includes("401")&&r.includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null}function J9(e,t){return e?NR.conflicts:t?NR.pairedLocally:"Not connected on this device"}function Y9(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 aa(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function QR(e){return aa(e)?"Unclear project identity":e.displayProject}function rn(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function X9(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function Q9(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Z9(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function e8(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function t8(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 n8(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function r8({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",t8(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:n8(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function ZR(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${Q9(t)}\\b`,"g"),Z9(t,n))),r}function i8(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 o8({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function a8({group:e,disabled:t,onChange:n,scopes:r,value:i}){const o=ht();return a("label",{className:"legacy-review-target",htmlFor:o,children:[a("span",{children:"Destination Space"}),a(Pn,{className:"peer-scope-input",disabled:t,id:o,onChange:s=>n(e,s.currentTarget.value),value:i,children:[a("option",{value:"",children:"Choose Space…"}),r.map(s=>a("option",{value:s.scopeId,children:[s.label," · ",e8(s.authorityType),s.scopeId===e.suggestedScopeId?" · suggested":""]},s.scopeId))]})]})}function s8({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=R({}),[l,d]=R({}),[u,f]=R(o),[p,m]=R({}),[g,b]=R("all"),[_,v]=R(""),[S,w]=R(null),k=r.length,P=e.totalGroupCount??k,T=r.filter(aa).length,E=r.filter(C=>C.suggestedScopeId&&!aa(C)&&rn(C)).length,$=r.filter(C=>p[C.workspaceIdentity]&&rn(C)).length,F=r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).length,A=r.filter(C=>{const O=aa(C);return g==="suggested"&&(!C.suggestedScopeId||O)||g==="cleanup"&&!O||g==="no-suggestion"&&(C.suggestedScopeId||O)||g==="selected"&&!p[C.workspaceIdentity]?!1:!_.trim()||i8(C,i).includes(_.trim().toLowerCase())});async function j(C){const O=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!O||!t||S)){w(C.workspaceIdentity),d(B=>{const G={...B};return delete G[C.workspaceIdentity],G});try{const B=await t(C,O,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?G=>({...G,[C.workspaceIdentity]:B}):G=>{const ne={...G};return delete ne[C.workspaceIdentity],ne})}catch(B){d(G=>({...G,[C.workspaceIdentity]:ZR(B,O,i)}))}finally{w(null)}}}function D(C,O){f(B=>({...B,[C.workspaceIdentity]:O})),c(B=>{const G={...B};return delete G[C.workspaceIdentity],G}),d(B=>{const G={...B};return delete G[C.workspaceIdentity],G})}function H(C,O){m(B=>({...B,[C.workspaceIdentity]:O}))}function V(C){m(O=>({...O,...Object.fromEntries(A.filter(rn).map(B=>[B.workspaceIdentity,C]))}))}function z(){m(C=>({...C,...Object.fromEntries(r.filter(O=>O.suggestedScopeId&&!aa(O)&&rn(O)).map(O=>[O.workspaceIdentity,!0]))}))}async function M(){if(!t||S||F===0)return;const C=r.filter(O=>p[O.workspaceIdentity]&&rn(O)&&!!u[O.workspaceIdentity]);if(!C.every(O=>s[O.workspaceIdentity])){w("bulk");try{for(const O of C){if(s[O.workspaceIdentity])continue;const B=u[O.workspaceIdentity]||O.suggestedScopeId||"";if(B)try{const G=await t(O,B,!1);d(ne=>{const oe={...ne};return delete oe[O.workspaceIdentity],oe}),G&&c(ne=>({...ne,[O.workspaceIdentity]:G}))}catch(G){d(ne=>({...ne,[O.workspaceIdentity]:ZR(G,B,i)}))}}}finally{w(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[P.toLocaleString()," older"," ",P===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",k<P?` Showing ${k.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${k.toLocaleString()}`],["suggested",`Suggested ${E.toLocaleString()}`],["cleanup",`Needs cleanup ${T.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,O])=>a("button",{className:g===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:O},C))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>v(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:_}),a("button",{className:"settings-button",onClick:()=>V(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:z,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>V(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:S!=null||F===0||r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{M()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&$>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>p[C.workspaceIdentity]&&rn(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:A.map(C=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${QR(C)}`,checked:!!p[C.workspaceIdentity],className:"cm-checkbox",disabled:!rn(C),onChange:O=>H(C,O.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:QR(C)}),a("div",{className:"legacy-review-group-meta",children:[Y9(C.identitySource),X9(C,i)]}),rn(C)?C.peerOwnedMemoryCount?a("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:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),aa(C)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?a("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?a("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,a(r8,{group:C}),i.length>0&&t&&rn(C)?a(a8,{group:C,disabled:S!=null,onChange:D,scopes:i,value:u[C.workspaceIdentity]||""}):null,i.length>0&&t&&rn(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{j(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function c8({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(U,{children:[t?a(s8,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(o8,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function l8(){xf("mine"),y.feedQuery="",window.location.hash="feed"}function d8(){window.location.hash="projects"}async function u8(e,t,n,r){try{const i=await AT({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return y.lastSyncLegacySharedReview=i.legacy_shared_review??null,Y(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),eP(),null}catch(i){if(i instanceof Zg)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function eP(){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(y.lastSyncSharingReview)?y.lastSyncSharingReview:[],o=y.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const f=u;return{displayProject:String(f.display_project||f.project||"Unknown project"),identitySource:String(f.identity_source||"unknown"),lastUpdatedAt:typeof f.last_updated_at=="string"?f.last_updated_at:null,memoryCount:Number(f.memory_count||0),memorySamples:Array.isArray(f.memory_samples)?f.memory_samples.map(p=>{const m=p,g=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:g,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(f.peer_owned_memory_count||0),reassignableMemoryCount:Number(f.reassignable_memory_count||0),suggestedScopeId:typeof f.suggested_scope_id=="string"?f.suggested_scope_id:null,suggestionReason:typeof f.suggestion_reason=="string"?f.suggestion_reason:null,workspaceIdentity:String(f.workspace_identity||f.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const f=u;return{authorityType:String(f.authority_type||"unknown"),label:String(f.label||f.scope_id||"Unknown domain"),scopeId:String(f.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){ia(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=y.currentProject?`current project (${y.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));lt(n,h(c8,{items:d,legacyReview:c,onLegacyReassign:u8,onLegacyReview:d8,onReview:l8}))}var Ws="";function p8(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of y.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){y.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||y.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function f8(){return[...y.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var sa=null,mg=0,hg=null,gg=0,vg=null,m8=15e3;function tP(e){return`project:${e||""}|includeJoinRequests:false`}function h8(e){const t=tP(e);return!sa||sa.key!==t||Date.now()>=sa.expiresAtMs?null:sa.payload}function g8(e,t){sa={key:tP(e),expiresAtMs:Date.now()+m8,payload:t}}function v8(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function y8(){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 b8(e,t){if(y.activeTab==="health"&&!t.requireFreshSyncStatus){const r=h8(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!Ya();return{payload:await sc(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function _8(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}function w8(){return{actorsPayload:{items:y.lastSyncActors},coordinatorAdminStatus:y.lastSyncCoordinatorAdminStatus,deviceIdentityInventory:y.lastDeviceIdentityInventory,shareOperations:y.lastShareOperations,actorLoadError:!1,coordinatorAdminLoadError:!1,deviceIdentityInventoryLoadError:y.deviceIdentityInventoryLoadError,shareOperationsLoadError:y.shareOperationsLoadError,duplicatePersonDecisions:DR()}}async function S8(e){if(e.requiredSurface!=="all")return w8();const t=DR();let n=null,r=null,i=y.lastDeviceIdentityInventory,o=y.lastShareOperations,s=!1,c=!1,l=y.deviceIdentityInventoryLoadError,d=!1;try{n=await UN({signal:e.signal})}catch{s=!0}try{r=await vu({signal:e.signal})}catch{c=!0}if(y.activeTab==="advanced"){l=!1;try{i=await Nu({signal:e.signal})}catch{l=!0}}try{const u=await dv({signal:e.signal});o=Array.isArray(u.items)?u.items:[]}catch{d=!0}return{actorsPayload:n,coordinatorAdminStatus:r,deviceIdentityInventory:i,shareOperations:o,actorLoadError:s,coordinatorAdminLoadError:c,deviceIdentityInventoryLoadError:l,shareOperationsLoadError:d,duplicatePersonDecisions:t}}function Yd(e={}){const t=C8(++mg,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return hg=t,t}async function C8(e,t){try{const n=y.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await b8(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:f,shareOperationsLoadError:p,duplicatePersonDecisions:m}=await S8(t);if(e!==mg)return hg??!1;if(t.signal?.aborted)return!1;const g=_8({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:p,requiresDeviceIdentityInventory:y.activeTab==="advanced",deviceIdentityInventoryLoadError:f});i&&g8(n,v8(r)),p8(r.coordinator);const b=JSON.stringify([r,o,s,c,f,l,p,m,f8()]);if(b===Ws)return g;Ws=b;const _=k8(r);Array.isArray(o?.items)?y.lastSyncActors=o.items:y.lastSyncActors=[];const v=Array.isArray(r.peers)?r.peers:[],S=new Set(v.map(k=>String(k?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(y.pendingAcceptedSyncPeers)?y.pendingAcceptedSyncPeers.filter(k=>{const P=String(k?.peer_device_id||"").trim();return P&&!S.has(P)}):[];return y.pendingAcceptedSyncPeers=w,y.lastSyncPeers=[...v,...w],f||(y.lastDeviceIdentityInventory=c),y.deviceIdentityInventoryLoadError=f,y.lastShareOperations=l,y.shareOperationsLoadError=p,y.lastSyncSharingReview=r.sharing_review||[],y.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,y.lastSyncCoordinator=r.coordinator||null,y.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,y.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],y.lastSyncAttempts=r.attempts||[],y.lastSyncLegacyDevices=r.legacy_devices||[],y.lastSyncDuplicatePersonDecisions=m,y.lastSyncViewModel=cY({actors:y.lastSyncActors,peers:y.lastSyncPeers,coordinator:y.lastSyncCoordinator,status:_,shareOperations:y.lastShareOperations,shareOperationsLoadError:p,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:y.lastSyncDuplicatePersonDecisions}),FR(),Ks(),c9(),d9(),eP(),sg(),KR(),MR(),nP(),d&&l9(),u&&(y.lastSyncCoordinatorAdminStatus=null,Ks()),g}catch{return t.signal?.aborted?!1:e!==mg?hg??!1:(Ws="",y.deviceIdentityInventoryLoadError=!0,R8(),!1)}}function k8(e){const t=e.status;return!t||typeof t!="object"?null:(y.lastSyncStatus={...t,sync_health:e.sync_health??null},y.lastSyncStatus)}function I8(){sa=null,Ws="",y.lastSyncStatus&&(y.lastSyncStatus={...y.lastSyncStatus,sync_health:null}),y.lastSyncPeers=y.lastSyncPeers.map(e=>({...e,sync_health:null})),y.lastSyncViewModel=null,Ks(),nP()}function R8(){I8(),Yr("syncTeamSkeleton"),Yr("syncActorsSkeleton"),Yr("syncPeersSkeleton"),Yr("syncDiagSkeleton"),y8(),zR();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),u9(),CY()}function nP(){if(y.activeTab==="health"){gh();return}Fk()}function P8(){Ws="",y.lastSyncPeers?.length&&sg()}async function Xd(){await Yd()}function N8(e={}){const t=T8(++gg,e.signal);return vg=t,t}async function T8(e,t){try{const n=await GN(!1,{signal:t});return t?.aborted?!1:e!==gg?vg??!1:(y.pairingPayloadRaw=n||null,tg(),!0)}catch{return t?.aborted?!1:e!==gg?vg??!1:(y.pairingPayloadRaw=null,tg(),!1)}}function A8(e){J5(),Ml(),h9(Xd),s9(Xd),NY(sg),S9(e,Xd),p9(Xd),TY(e),cg(),m9()}function E8(e,t){const n=Xe("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function x8(){try{const e=await bN();if(!e?.version)return;E8(e.version,"bce20cb")}catch{}}var yg=null,rP=1500,zs=V1(),iP="codemem-legacy-upgrade-notice-dismissed",Zr=null,Jt=!1,Qd=!1,bg=!1;function oP(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function aP(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=oP(n.total_group_count,r.length),o=oP(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function sP(){try{return localStorage.getItem(iP)==="1"}catch{return!1}}function D8(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(iP,"1")}catch{}}function j8(e,t){e&&t?lL(t):dL()}function cP(e){!e||bg||sP()||(bg=!0,d_(()=>j8(!0,e)))}async function O8(){if(!(bg||sP()))try{cP(aP(await sc(!1,"",{includeJoinRequests:!1})))}catch{}}function Ui(e,t){y.viewerReconnectOpen=e;const n=Xe("viewerReconnectOverlay"),r=Xe("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",y.activeTab==="feed"&&Ln(!0))}async function _g(){try{return await yN(),!0}catch{return!1}}function Js(){return document.visibilityState!=="hidden"&&!VI()}function lP(){return`${y.activeTab}:${y.advancedSection}:${y.syncPairingOpen}`}function L8(e){y.refreshQueued||e.surface!==lP()||!e.refreshSucceeded||!Qd||Jt||(Qd=!1,Gp("connection_restored"))}function dP(){if(Jt)return;Jt=!0,Qd=!0,Gp("connection_lost"),Ys(),d_(),ei("error","(reconnecting)"),Ui(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await _g()){if(Zr&&(clearTimeout(Zr),Zr=null),Jt=!1,Ui(!0,"Viewer responded. Restoring your session…"),Js()){ei("refreshing"),Gi();try{await nu()}catch{}}else ei("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");Jt||Ui(!1);return}Ui(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Zr=setTimeout(e,rP)};Zr=setTimeout(e,rP)}function ei(e,t){y.refreshState=e;const n=Xe("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=Xe("refreshAnnouncer");!s||yg===e||(s.textContent=o,yg=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}`,yg=null}var $8=5e3,M8=3e4,F8=3e4,wg=null;function Ys(){vd(),zs.cancel(),ti&&(clearTimeout(ti),ti=null),y.refreshQueued=!1,y.refreshTimer&&(clearInterval(y.refreshTimer),y.refreshTimer=null)}function uP(){Ys(),ei("paused")}function Gi(){if(y.refreshTimer||!Js()||Jt)return;const e=document.hasFocus()?$8:M8;y.refreshTimer=setInterval(()=>gr({automatic:!0}),e)}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(Ys(),ei("paused","(tab hidden)")):!VI()&&!Jt&&(Gi(),gr({automatic:!document.hasFocus()}))}),window.addEventListener("blur",()=>{Ys(),Gi()}),window.addEventListener("focus",()=>{!Js()||Jt||(Ys(),Gi(),gr())});var Zd=!1;function pP(){const e=y.advancedSection==="sync",t=Xe("advancedSyncContent"),n=Xe("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=Xe("advancedTabsMount");r&&jF(r,y.advancedSection,B8),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&Zd){Zd=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}cg(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function B8(e,t={}){Lw(e,!0),pP(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var q8=oF();function fP(e){const t=new Set(J1(y.lastCoordinatorAdminStatus));vi.forEach(r=>{const i=Xe(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),vi.forEach(r=>{const i=Xe(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=Xe(`tabBtn-${e}`);n&&q8(n),e==="advanced"&&pP()}function Fn(e,t={}){vd(),zs.cancel();const n=Ja(e,y.lastCoordinatorAdminStatus);n==="advanced"&&Lw(t.advancedSection??Ef()??y.advancedSection),$w(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&Pi("settings-health"),fP(n),gr()}function U8(){window.addEventListener("codemem:navigate-advanced-sync",V8),vi.forEach(e=>{Xe(`tabBtn-${e}`)?.addEventListener("click",()=>Fn(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),Xe("syncTurnOnButton")?.addEventListener("click",()=>{HI("sync"),uR(uP)}),Xe("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),Mp("teams"),Fn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),Xe("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),Mp("invitations"),Fn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=Af();if(e){const t=Ef();Zd=Ow(),Fn(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),Zd=Ow(),Fn(y.activeTab)}async function G8(){try{const e=await rc();y.knownProjects=e,P8(),Nf(e,y.currentProject)}catch{}}function H8(e){y.pendingDeviceIdentityFocus=e?.trim()||null,Fn("devices",{canonicalHash:!0})}function V8(){Fn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var eu=eO({},{onOpenTeamSetup:aI,onReviewDevices:H8}),mP={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Sg=0,Cg=null,Yt=null;async function K8(e={}){const t=[];let n=0;for(;;){const r=await ma({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return xc(t)}function W8(){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 y.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of y.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=Hs(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function z8(){return y.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 hP(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function J8(e){return y.lastSyncPeers.flatMap(t=>{const n=String(t.peer_device_id??"").trim();if(!n)return[];const r=t.has_error?"error":t.status?.sync_status,i=["ok","error","stale"].includes(r??"")?r:"unknown";return[{deviceId:n,paired:t.pinned===!0,status:i,lastSyncAt:t.last_sync_at??t.status?.last_sync_at??null,recentIn:hP(t.recent_ops?.in),recentOut:hP(t.recent_ops?.out),syncHealth:t.sync_health,statusAvailable:e}]})}async function Y8(e){try{const t=await Tu({peerDeviceId:e});if(t.items.length!==1||t.items[0]?.peer_device_id!==e)return{message:"This device is no longer paired here. Refresh Devices before retrying.",tone:"warning"};const n=Gh(t),r=await tu();return{message:r?n.message:`${n.message} Refresh Devices to see the latest sync status.`,tone:n.ok&&!n.warning&&r?"success":"warning"}}catch(t){return t instanceof Error&&/\bsync_disabled\b/.test(t.message)?{message:"Device sync is off. Turn it on in Settings → Device Sync, then try again.",tone:"warning"}:{message:ft(t,"Could not sync this device. Check its pairing and try again."),tone:"warning"}}}function X8(e){if(e==="advanced_sync"){Fn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){Fn("sharing",{canonicalHash:!0}),Mp("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}Fn(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function tu(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=eX(t,++Sg,e);return Cg=n,n}async function Q8(){const[e,t]=await Promise.all([tu(),eu()]);return e&&t}function gP(){return{localDeviceId:y.lastSyncStatus?.device_id??void 0,onCommitted:Q8,onNavigate:X8,onRetry:()=>{tu()},onSyncDevice:Y8}}function Z8(e){if(!Yt){Xl(e,mP,{version:1,items:[]},[],[],{loadError:!0});return}Xl(e,Yt.intent,Yt.reconciliation,Yt.projects,Yt.availability,{...gP(),coordinatorEnrollmentIssueCount:Yt.coordinatorEnrollmentIssueCount,inventory:Yt.inventory,inventoryUnavailable:Yt.inventoryUnavailable,peerRuntimeMetadata:Yt.peerRuntimeMetadata,peerSyncMetadata:Yt.peerSyncMetadata,refreshError:!0})}async function eX(e,t,n){Yt||Xl(e,mP,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([K8(n),Pu(n),pT(n),Nu(n).then(p=>({inventory:p,unavailable:!1})).catch(()=>({inventory:Yt?.inventory,unavailable:!0})),Yd({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==Sg)return Cg??!1;const l=W8(),d=z8(),u=J8(c),f=pv(y.lastSyncStatus);return!s.unavailable&&s.inventory&&(y.lastDeviceIdentityInventory=s.inventory),y.deviceIdentityInventoryLoadError=s.unavailable,Xl(e,i,o,r,l,{...gP(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:f,peerRuntimeMetadata:d,peerSyncMetadata:u,syncStatusUnavailable:!c}),Yt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,peerSyncMetadata:u,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:f},c}catch{return n.signal?.aborted?!1:t!==Sg?Cg??!1:(Z8(e),!1)}}Xe("projectFilterMount")?.addEventListener(bw,e=>{const t=e.detail;typeof t=="string"&&(zs.cancel(),vd(),y.currentProject=t,Nf(y.knownProjects,t),Pi("scope"),Ln(!0),gr())});var ti=null;async function tX(e){await Promise.all([lW({signal:e.signal}),L6({signal:e.signal}),rL().catch(()=>{})])}async function nX(e,t){const n=Date.now();t.automatic&&wg!==null&&n-wg<F8||(wg=n,await dW({signal:e.signal}))}function rX(e,t,n,r,i){if(t!=="health"&&Fk(),t==="feed"){const c=G2();e.push(RS(c,{signal:r.signal}),Cs({signal:r.signal}))}if(t==="projects"&&e.push(ta({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(eu({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(tu({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(nX(r,i),Yd({requiredSurface:"health",requireFreshSyncStatus:Qd,signal:r.signal}).then(n)),t==="advanced"&&y.advancedSection==="sync"&&e.push(Yd({signal:r.signal}).then(n)),t==="advanced"&&y.advancedSection==="teams"&&e.push(ql({deferWhileRenaming:!0,signal:r.signal}).then(n)),!y.syncPairingOpen)return;const o=t==="advanced"&&y.advancedSection==="sync",s=N8({signal:r.signal});e.push(o?s.then(n):s)}async function gr(e={}){Jt||e.automatic&&(y.refreshInFlight||ti)||(ti&&clearTimeout(ti),ti=setTimeout(()=>{ti=null,nu(e)},80))}async function iX(e,t){if(!t.isCurrent()&&!gu(e))return;const n=await _g();t.isOwned()&&(n?ei("error"):dP())}function oX(e){zs.finish(e),y.refreshInFlight=!1,!(!y.refreshQueued||Jt||!Js())&&(y.refreshQueued=!1,nu())}function aX(e){return y.refreshInFlight?(e.automatic||(y.refreshQueued=!0),!0):!1}async function nu(e={}){if(Jt||!Js()||aX(e))return;y.refreshInFlight=!0;const t=zs.begin();try{ei("refreshing");const n=y.activeTab,r=lP(),i=[tX(t)];let o=!0;const s=!e.automatic||document.hasFocus();if(s&&rX(i,n,l=>{o=o&&l},t,e),await Un(Promise.all(i),t.signal),!t.isCurrent()){if(gu(t.signal.reason))throw t.signal.reason;return}cP(aP(y.lastSyncLegacySharedReview)),s&&n==="feed"&&Ln(!0);const c=Ja(y.activeTab,y.lastCoordinatorAdminStatus);c!==y.activeTab&&(vd(),$w(c)),fP(y.activeTab),ei(o?"idle":"error"),L8({refreshSucceeded:s&&o,surface:r})}catch(n){await iX(n,t)}finally{oX(t)}}rF(),Nf(y.knownProjects,y.currentProject);var vP=document.getElementById("toastRoot");vP&&i$(vP);var yP=document.getElementById("operationStatusRoot");yP&&Zp(yP);var bP=document.getElementById("diagnosticsDrawerMount");bP&&nL(bP);var _P=document.getElementById("legacyTeamSetupMount");_P&&vz(_P,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(y.activeTab==="sharing"?(t=await ta(n),e=await eu(n)):(e=await eu(n),t=await ta(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var wP=document.getElementById("legacyUpgradeDialogMount");wP&&cL(wP,{onDismiss:D8,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),H1(),aF(wl("themeToggle")),qw(jf()),U8(),GK(),iL(),v6(()=>gr(),{onOpenTeamSetup:aI}),A8(()=>gr()),Y2(),W5(uP,Gi,()=>gr()),G8(),Xe("viewerReconnectRetry")?.addEventListener("click",async()=>{if(Gp("reconnect_requested"),Ui(!0,"Checking whether the viewer server is back…"),!await _g()){dP();return}Zr&&(clearTimeout(Zr),Zr=null),Jt=!1,Ui(!0,"Viewer responded. Restoring your session…"),Gi();try{await nu()}catch{}Jt||Ui(!1)}),x8(),O8(),gr(),Gi()})();
|