@codemem/server 0.46.0-rc.2 → 0.46.0-rc.3
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/package.json +2 -2
- package/static/app.js +1 -1
- package/static/app.js.br +0 -0
- package/static/app.js.gz +0 -0
- package/static/index.html +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codemem/server",
|
|
3
|
-
"version": "0.46.0-rc.
|
|
3
|
+
"version": "0.46.0-rc.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"exports": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"static/"
|
|
16
16
|
],
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@codemem/core": "^0.46.0-rc.
|
|
18
|
+
"@codemem/core": "^0.46.0-rc.3",
|
|
19
19
|
"@hono/node-server": "^2.1.1",
|
|
20
20
|
"drizzle-orm": "^0.45.2",
|
|
21
21
|
"hono": "^4.13.5",
|
package/static/app.js
CHANGED
|
@@ -115,4 +115,4 @@ ${t}
|
|
|
115
115
|
`:t}function OB(e){const[t,n]=A(!1);return ot(()=>{const r=co(_.feedQuery),i=e.current?.querySelector(".feed-detail"),o=()=>{const c=i?cS(i):"";n(!!(r&&c.toLowerCase().includes(r)))};o();const s=i?.querySelectorAll(".feed-observation-context");return s?.forEach(c=>{c.addEventListener("toggle",o)}),()=>{s?.forEach(c=>{c.removeEventListener("toggle",o)})}}),t}function lS(e){return e==="shared"?"shared":e==="private"?"private":"unknown"}function $B(e,t,n){const r=String(e.visibility||n.visibility||"").trim(),i=mf(e),o=String(e.trust_state||n.trust_state||"").trim(),s=String(e.workspace_kind||n.workspace_kind||"").trim(),c=IM(e.origin_source||n.origin_source),l=["Observer","Session summary"].includes(c)?"":c,d=NM(e,n);let u="";return!i&&o!=="trusted"&&(u=o?CM(o):"Trust unknown"),{actor:kM(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:jT(e.created_at||e.created_at_utc),trustLabel:u,visibility:r,workspaceKind:s}}function MB(e){const[t,n]=A(_.newItemKeys.has(e));return q(()=>{if(!t)return;const r=window.setTimeout(()=>{_.newItemKeys.delete(e),n(!1)},700);return()=>window.clearTimeout(r)},[t,e]),t}function FB(e){const[t,n]=A(_.itemExpandState.get(e)!==!1);return{cardRef:D(null),expanded:t,isNew:MB(e),setExpanded:n}}function BB(e,t){const n=e.current?.querySelector(".feed-disclosure")===document.activeElement;ot(()=>{n&&!t&&document.activeElement===document.body&&e.current?.focus()},[e,n,t])}async function qB(e){e.setSelectedVisibility(e.nextVisibility),e.setSavingVisibility(!0);try{const t=await HI(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 UB(e){try{return(await ks()).filter(t=>t&&t!==e)}catch{return[]}}function GB(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 HB(e){const t=await sf({title:"Assign to project",description:GB(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 VI(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 e.onReload(),e.onViewRefresh()}catch(r){Y(r instanceof Error?r.message:"Failed to move memory.","warning")}finally{e.setMovingProject(!1)}}}async function VB(e){const t=e.title.length>80?`${e.title.slice(0,79).trimEnd()}…`:e.title;if(await bn({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 KI(e.memoryId),e.onRemove(e.memoryId),e.onViewRefresh(),await e.onReload(),Y("Memory forgotten and removed from the active feed.")}catch(n){Y(n instanceof Error?n.message:"Failed to forget memory.","warning")}finally{e.setDeletingMemory(!1)}}}function KB(e){const[t,n]=A(!1),[r,i]=A(!1),[o,s]=A(!1),c=String(e.item.project||"").trim(),l=String(e.model.displayTitle||"this memory").trim();return{deletingMemory:r,movingProject:o,savingVisibility:t,forget:()=>VB({memoryId:e.memoryId,onReload:e.onReload,onRemove:e.onRemove,onViewRefresh:e.onViewRefresh,setDeletingMemory:i,title:l}),moveProject:async()=>HB({currentProject:c,memoryId:e.memoryId,onReload:e.onReload,onViewRefresh:e.onViewRefresh,setMovingProject:s,suggestions:await UB(c),title:l}),saveVisibility:d=>qB({memoryId:e.memoryId,nextVisibility:d,onReplace:e.onReplace,onViewRefresh:e.onViewRefresh,previousVisibility:e.selectedVisibility,setSavingVisibility:n,setSelectedVisibility:e.setSelectedVisibility})}}function zB(e){return h("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:Y_(e.model.displayTitle,_.feedQuery)}})}function WB(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:Y_(e.searchMatch.excerpt,_.feedQuery)}}))}function JB(e){const{details:t}=e,n=t.memoryId>0?h(xa,{label:`Memory database id ${t.memoryId}`,side:"top"},h(Ln,{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(xa,{label:DT(t.createdAtRaw),side:"top"},h("span",{className:"feed-age mono"},t.relative)),h(Ln,{label:t.actor,variant:t.ownedBySelf?"mine":"author"}),h(Ln,{label:e.visibilityKnown?e.selectedVisibility:"Visibility unknown",variant:e.visibilityKnown?e.selectedVisibility:"unknown"}),n,t.trustLabel?h(Ln,{label:t.trustLabel,variant:"trust"}):null)}function YB(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 QB(e){const t=[e.workspaceKind?h(Ln,{label:`Workspace ${e.workspaceKind}`,variant:"workspace"}):null,e.originSource?h(Ln,{label:e.originSource,variant:"source"}):null,e.device?h(Ln,{label:e.device,variant:"device"}):null].filter(Boolean);return t.length?h("div",{className:"feed-expanded-provenance"},t):null}function dS(e,t,n="feed-pack-facts"){return e.length?h("div",{className:n},h("div",{className:"feed-pack-facts-label"},t),z1(e)):null}function XB(e){const{body:t,facts:n,narrative:r}=e.model.content;if(!e.model.isSessionSummary&&n.length){const i=r||t;return h(H,null,dS(n,"Key points","feed-pack-facts feed-observation-points"),i?h("details",{className:"feed-observation-context"},h("summary",{"aria-label":`Full context for ${e.model.displayTitle}`},"Full context"),Uf(i,"feed-body narrative")):null)}return h(H,null,r?Uf(r,"feed-body narrative"):null,t?Uf(t,"feed-body narrative"):null,dS(n,"Facts included in pack"))}function ZB(e){return!e.expanded||!e.hasDisclosure?null:h("section",{"aria-label":`${e.model.displayTitle} content`,className:"feed-detail",id:e.details.detailId},XB(e),YB(e.model.files),QB(e.details))}function eq(e){return h("div",{className:"feed-card-body"},zB(e),!e.expanded&&e.hasDisclosure?h("div",{className:"feed-collapsed-note"},"Memory content collapsed"):null,WB(e),JB(e),ZB(e),nq(e))}function tq(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(Wn,{ariaLabel:`Who can see ${e.model.displayTitle}`,contentClassName:"sync-radix-select-content feed-visibility-content",disabled:e.savingVisibility||!e.visibilityKnown,id:t,itemClassName:"sync-radix-select-item",onValueChange:r=>{const i=r==="shared"?"shared":"private";e.onSaveVisibility(i)},options:n,triggerClassName:"sync-radix-select-trigger feed-visibility-select",value:e.visibilityKnown?e.selectedVisibility:"unknown",viewportClassName:"sync-radix-select-viewport"}))}function nq(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(sy,{key:`${String(t)}-${n}`,tag:t})))):null}function rq(e){const t=tq(e),n=e.details.ownedBySelf&&e.details.memoryId>0?h(LB,{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(xa,{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 iq(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(Ue,{variant:"kind",tone:e.model.displayKind},e.model.displayKind.replace(/_/g," "))),eq(e),rq(e))}function oq(e){return co(_.feedQuery)&&e.displayTitle.toLowerCase().includes(co(_.feedQuery))?null:DM(e,_.feedQuery)}function aq(e){const[t,n]=A(lS(e));return q(()=>{n(lS(e))},[e]),{selectedVisibility:t,setSelectedVisibility:n,visibilityKnown:e==="private"||e==="shared"}}function sq({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=W_(e),s=$B(e,o,sl(e.metadata_json)),c=FB(o.rowKey),l=oq(o),d=OB(c.cardRef),u=aq(s.visibility),p=KB({item:e,memoryId:s.memoryId,model:o,onReload:i,onRemove:n,onReplace:t,onViewRefresh:r,selectedVisibility:u.selectedVisibility,setSelectedVisibility:u.setSelectedVisibility}),f=!!(o.content.searchText||s.hasSupplementalDetail);BB(c.cardRef,f);const m=()=>{if(!f)return;const g=!c.expanded;_.itemExpandState.set(o.rowKey,g),c.setExpanded(g)};return iq({cardRef:c.cardRef,deletingMemory:p.deletingMemory,details:s,expanded:c.expanded,hasDisclosure:f,isNew:c.isNew,model:o,movingProject:p.movingProject,onForget:p.forget,onMoveProject:p.moveProject,onSaveVisibility:p.saveVisibility,onToggleDetail:m,savingVisibility:p.savingVisibility,searchMatch:l,renderedSearchMatch:d,selectedVisibility:u.selectedVisibility,visibilityKnown:u.visibilityKnown})}function cq({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 uS(e){document.getElementById(e)?.click()}function Sl(){uS("tabBtn-health"),queueMicrotask(()=>document.getElementById("healthSystemCard")?.focus())}function lq(e){fb("all"),op("all");const t=document.getElementById("projectFilter");if(t){t.value="",t.dispatchEvent(new Event("change",{bubbles:!0})),queueMicrotask(()=>t.focus());return}_.currentProject="",e.updateFeedView(!0),e.loadFeedData().catch(()=>{})}function dq(){const e=_.feedProcessingStatus;if(e.kind==="pending"){const t=e.count===1?"event":"events";return{actions:[{label:"Open Health",run:Sl}],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:Sl}],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:Sl}],detail:"The Feed is connected, but processing status could not be checked.",status:!0,title:"Processing status is unavailable."}:{actions:[{label:"Open Settings",run:()=>uS("settingsButton")},{label:"Open Health",run:Sl}],detail:"Use codemem while you work. Captured memories and session summaries will appear here.",title:"No memories yet."}}function uq(e){const t=_.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}”.`}:_.feedTypeFilter!=="all"||_.feedScopeFilter!=="all"||_.currentProject?{actions:[{label:"Clear filters",run:()=>lq(e)}],detail:"Clear the Feed and project filters to see memories from every scope.",title:"No memories match the current filters."}:dq()}function pq({ops:e}){const t=uq(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 fq({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(cq,{index:r,key:`skeleton-${r}`}))):e.length?h(H,null,e.map(r=>h(sq,{item:r,key:Pt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData}))):h(pq,{ops:n})}function pS({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 fS(e){document.getElementById(e)?.click()}function Jf(e){document.querySelector(e)?.focus()}function mq(){fS("tabBtn-health"),queueMicrotask(()=>Jf("#healthSystemCard"))}function hq(){const e=document.querySelector(".feed-item button.feed-title");e?.getAttribute("aria-expanded")!=="true"&&e?.click(),e?.focus(),e&&ai("inspect")}function gq(){Jf("#feedSearch")}function vq(e){return[{id:"capture",label:"Capture a memory",actionLabel:"Check capture health",action:mq},{id:"inspect",label:"Inspect its details",actionLabel:"Inspect first memory",action:hq,actionAvailable:e},{id:"find",label:"Find it again",actionLabel:"Search memories",action:gq},{id:"scope",label:"Choose project scope",actionLabel:"Choose a project",action:()=>Jf("#projectFilter")},{id:"settings-health",label:"Check settings or health",actionLabel:"Open Settings",action:()=>fS("settingsButton")}]}function yq({completed:e,hasMemories:t,onAction:n}){return a("ol",{className:"first-run-guide-list",children:vq(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 bq({hasMemories:e,hasQueuedEvents:t}){const[n,r]=A(Ta),[i,o]=A(""),[s,c]=A(!1);if(ot(()=>{c(document.querySelector(".feed-item button.feed-title")!==null)}),q(()=>{const d=()=>{const p=Ta();r(p),o(`${p.completed.length} of 5 getting started steps completed.`)},u=p=>{p.key==="codemem-first-run-guide-v1"&&d()};return window.addEventListener(gf,d),window.addEventListener("storage",u),()=>{window.removeEventListener(gf,d),window.removeEventListener("storage",u)}},[]),q(()=>{(e||t)&&ai("capture")},[e,t]),!$M(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:()=>LM(),type:"button",children:"Skip getting started"})]}),a(yq,{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 _q({text:e}){return h("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function wq({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 Sq(e,t){return!e&&!t}function Cq({inspectorOpen:e,items:t,loadingText:n,onInspectorToggle:r,ops:i}){return h("div",{className:"feed-controls"},h(_q,{text:n||fF(t.length,i.hasMorePages())}),h("div",{className:"feed-controls-right"},h(wq,{query:_.feedQuery,onQuery:i.updateFeedQuery}),h(pS,{active:_.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==_.feedScopeFilter&&(op(o),i.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),h(pS,{active:_.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==_.feedTypeFilter&&(fb(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 Rq({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(H,null,i,h(fq,{items:t,loadingText:n,ops:r}))}function Iq({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=A(!1);return h(H,null,h(Cq,{inspectorOpen:i,items:t,loadingText:n,onInspectorToggle:()=>{o(c=>!c)},ops:r}),h(mF,{open:i}),Sq(n,_.viewerReconnectOpen)?h(bq,{hasMemories:t.length>0,hasQueuedEvents:_.feedProcessingStatus.kind==="pending"}):null,h("div",{className:"feed-list",id:"feedList"},h(Rq,{errorText:e,items:t,loadingText:n,ops:r})))}function mS(e){return _.feedTypeFilter==="observations"?e.filter(t=>!cl(t,sl(t?.metadata_json))):_.feedTypeFilter==="summaries"?e.filter(t=>cl(t,sl(t?.metadata_json))):e}function kq(e){const t=e.map(n=>`${K_(n)}:${JSON.stringify(n)}`);return`${_.feedTypeFilter}|${_.feedScopeFilter}|${_.currentProject}|${_.viewerActorId??""}|${ia(_.feedQuery)}|${t.join("|")}`}var hS="",Ha=0,Va=0,ho=!0,go=!0,Cl=null,Nq=0,Sr=null,gS=!1,vS=!1,Ka=0,Yf="all",yS="",za=null,vo="",nY=250;function bS(e){hS=e,Yf=_.feedScopeFilter,yS=_.feedQuery.trim(),vo="",Ka+=1,Ha=0,Va=0,ho=!0,go=!0,_.lastFeedItems=[],_.pendingFeedItems=null,_.lastFeedFilteredCount=0,_.lastFeedSignature="",_.newItemKeys.clear()}function Qf(){return ho||go}function Pq(e){const t=Pt(e);_.lastFeedItems=_.lastFeedItems.map(n=>Pt(n)===t?e:n)}function Tq(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Pt(r)),i};_.lastFeedItems=_.lastFeedItems.filter(n),Array.isArray(_.pendingFeedItems)&&(_.pendingFeedItems=_.pendingFeedItems.filter(n));for(const r of t){_.newItemKeys.delete(r),_.itemExpandState.delete(r);for(const i of Array.from(_.itemExpandState.keys()))i.startsWith(`${r}:`)&&_.itemExpandState.delete(i)}}function _S(e,t){return mS(e).some(n=>xM(n,t))&&ai("find"),e.sort((n,r)=>new Date(r.created_at||0).getTime()-new Date(n.created_at||0).getTime())}async function Aq(){if(!Qf())return;const e=Ka;if(Cl===e)return;const t=_.currentProject||"",n=_.feedQuery.trim(),r=Ha,i=Va;Cl=e;try{const[o,s]=await Promise.all([ho?Ah(t,{limit:20,offset:r,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),go?Eh(t,{limit:50,offset:i,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==Ka||t!==(_.currentProject||"")||n!==_.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(f=>!V_(f));_.lastFeedFilteredCount+=l.length-d.length,go=ll(s,c.length,50),ho=ll(o,l.length,20),Va=dl(s,i+c.length),Ha=dl(o,r+l.length);const u=_S([...c,...d],n),p=z_(_.lastFeedItems,u);_.lastFeedItems=p,wn()}finally{Cl===e&&(Cl=null)}}function wS(){_.activeTab==="feed"&&(za||Sr||Qf()&&FM()&&Aq())}var Eq={replaceFeedItem:Pq,removeFeedItem:Tq,updateFeedView:e=>wn(e),loadFeedData:()=>em(),updateFeedQuery:e=>Dq(e),hasMorePages:Qf};function Xf(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;dF(n,h(Iq,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:Eq}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function Zf(e="Loading selected project..."){Xf([],{loadingText:e})}function xq(){lF(),Xf(_.lastFeedItems,_.lastFeedItems.length||_.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),gS||(window.addEventListener("scroll",()=>{wS()},{passive:!0}),gS=!0),vS||(document.getElementById("tab-feed")?.addEventListener("click",e=>{e.target?.closest(".feed-item button.feed-title")&&ai("inspect")}),vS=!0)}function Dq(e){if(e===_.feedQuery)return;const t=_.feedQuery.trim();_.feedQuery=e,e.trim()!==t&&(bS(_.currentProject||""),Zf("Searching memories…"),za&&clearTimeout(za),za=setTimeout(()=>{za=null,em().catch(()=>{})},250))}function wn(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=mS(_.lastFeedItems),r=kq(n),i=e||r!==_.lastFeedSignature;_.lastFeedSignature=r,i&&Xf(n,{errorText:vo||void 0}),window.scrollTo({top:t}),_.viewerReconnectOpen||wS()}function SS(e,t,n,r){return CS(e,t)&&e===Ka&&n===(_.currentProject||"")&&r===_.feedQuery.trim()}function CS(e,t){return Sr?.generation===e&&Sr.requestId===t}async function em(e={}){const t=_.currentProject||"",n=_.feedScopeFilter!==Yf,r=_.feedQuery.trim(),i=r!==yS;(t!==hS||n||i)&&(bS(t),Zf(i?"Searching memories…":void 0));const o=Ka,s=++Nq;Sr={generation:o,requestId:s};const c=!!vo;c&&(vo="",_.lastFeedItems.length>0?wn(!0):Zf(r?"Searching memories…":void 0));try{const[u,p]=await Promise.all([Ah(t,{limit:20,offset:0,scope:_.feedScopeFilter,q:r||void 0,signal:e.signal}),Eh(t,{limit:50,offset:0,scope:_.feedScopeFilter,q:r||void 0,signal:e.signal})]);if(e.signal?.aborted||!SS(o,s,t,r))return;const f=p.items||[],m=u.items||[],g=r?m:m.filter(w=>!V_(w)),b=m.length-g.length,v=_S([...f,...g],r),y=PM(_.lastFeedItems,v),S=_.lastFeedItems;if(BM(y,S)&&S.length>0){const w=new Set(S.map(Pt));y.forEach(R=>{w.has(Pt(R))||_.newItemKeys.add(Pt(R))})}_.pendingFeedItems=null,_.lastFeedItems=y,vo="",_.lastFeedFilteredCount=Math.max(_.lastFeedFilteredCount,b),go=ll(p,f.length,50),ho=ll(u,m.length,20),Va=Math.max(Va,dl(p,f.length)),Ha=Math.max(Ha,dl(u,m.length)),Yf=_.feedScopeFilter,Sr?.generation===o&&Sr.requestId===s&&(Sr=null),wn(c)}catch(l){if(e.signal?.aborted)return;throw SS(o,s,t,r)&&(ho=!1,go=!1,vo="Feed unavailable. Refresh and try again.",wn(!0)),l}finally{CS(o,s)&&(Sr=null)}}function rY(e){return e}function jq(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 Lq(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function Oq(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=Lq(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:`~${ra(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 $q(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]=jq(e);return h(H,null,h("div",{class:"grid-2 automatic-recall-grid"},Oq(e).map(r=>h(RS,{...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 Mq(e,t){e&&(ke(h(pl,null,h("details",{class:"automatic-recall"},h("summary",null,"Automatic recall"),h("section",{"aria-label":"Automatic recall measurements"},$q(xh(t))))),e),Wa())}function yo(e,t){return t.error?`${e} ${t.error}`:e}function Rl(e,t){return t.recommended_action?`${e} ${t.recommended_action}`:e}function Fq(e){return e.unavailable?{label:"Update check unavailable",title:Rl(yo("Could not check for updates.",e),e),tone:"badge-offline"}:e.install_kind==="repo-dev"?{label:`Source build · ${e.current_version}`,title:Rl(yo(`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:yo(`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:yo(`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:Rl(yo("Could not check for updates.",e),e),tone:"badge-offline"}:{label:"Unsupported channel",title:Rl(yo("The installed version is not on a supported release channel.",e),e),tone:"badge-offline"}}function Bq({command:e}){return h("code",{class:"health-update-command",id:"healthUpdateCommand"},e)}function qq({status:e}){const t=Fq(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||Ji(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(Ue,{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(Bq,{command:e.recommended_action}):null,e.stale?h(Ue,{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 Uq(e,t){e&&(e.hidden=!t,ke(t?h(qq,{status:t}):null,e))}function Gq({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(xa,{label:o},c):c}function Hq({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||Ji(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 Vq(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function RS({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"},Vq(t)),h("div",{class:"label"},e)));return r?h(xa,{label:r},i):i}function IS(e,t){e&&ke(h(pl,null,t.map(n=>h(RS,{...n,key:`${n.label}-${n.icon}`}))),e)}function Il(e,t){e&&ke(h(H,null,t),e)}function Wa(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function Kq({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(tn,{state:n,size:6}),t))}function kS(e,t,n){e&&ke(h(pl,null,h("div",{class:"health-tile-grid"},t.map(r=>h(Kq,{...r,key:r.key}))),n.length?h("div",{class:"grid-2 health-maintenance-grid"},n.map(r=>h(Gq,{...r,key:r.key??r.label}))):null),e)}function zq({label:e,message:t,stale:n,state:r,statusClass:i}){return h("div",{class:"health-status-summary"},h(tn,{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(Ue,{variant:"badge"},"Stale data"):null)))}function NS(e,t){e&&ke(h(zq,t),e)}function PS(e,t){if(e){if(!t.length){e.hidden=!0,ke(null,e);return}e.hidden=!1,ke(h(H,null,t.slice(0,3).map((n,r)=>h(Hq,{item:n,key:`${n.label}-${r}`}))),e)}}var TS="codemem-settings-advanced",AS="gpt-5.1-codex-mini",ES="claude-4.5-haiku",Wq=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],tm={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"},Jq=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),Yq={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 nm(e){return String(e||"").replace(/_/g," ")}function kl(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 Qq(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function Xq(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 Zq(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var eU=["opencode","claude","codex","pi"];function xS(){return kl([...eU])}function tU(){try{return globalThis.localStorage?.getItem(TS)==="1"}catch{return!1}}function nU(e){try{globalThis.localStorage?.setItem(TS,e?"1":"0")}catch{}}function Qn(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ce(e,t,n){if(Qn(t,n))return t[n];if(Qn(e,n))return e[n]}function Pe(e){return e==null?"":String(e)}function Nl(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 rU(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function iU(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function ct(e){const t=e.trim();return t===""?"":t}function oU(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:ES,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:AS,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:ES,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:"opencode/gpt-5.1-codex-mini",source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:AS,source:"Recommended (direct API)"}}function aU(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return ct(Pe(n[t]));case"observer_runtime":return ct(Pe(n.observer_runtime));case"observer_auth_source":return ct(Pe(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(!Qn(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(!Qn(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Qn(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 Nl(n[t]);default:return Qn(n,t)?n[t]:""}}function sU(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Qn(r,i)&&(r[i]=aU(t,i))}),r}function rm(e,t){let n=e.events_global;return t&&(n=e.events_filtered??e.events),n.find(r=>r.event==="pack")??null}var DS="scope_id_backfill",cU=new Set(["error","needs_attention","stopped","degraded","stale","offline-peers","rebootstrapping"]),lU=new Set(["starting","stopping"]),dU={"offline-peers":"Offline peers",needs_attention:"Needs attention",rebootstrapping:"Rebootstrapping"};function jS(){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&&Il(t,"")}function uU(){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 pU(e,t){const n=[`${e} ${e===1?"issue":"issues"}`];return e>0&&t.length>0&&n.push(t.join(", ")),n.join(" · ")}function fU(e){return e==="status-healthy"?"online":e==="status-degraded"?"degraded":e==="status-attention"?"attention":"unknown"}function mU(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 hU(e){return dU[e]??ay(e)}function gU(e){const t=new Map,n=new Set(e.map(r=>r.peer_device_id));for(const r of _.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 LS(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 vU(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 yU(e,t){return t.size>0||e.some(n=>n.status?.recent_failed_attempt===!0)}function bU(){const e=_.lastSyncStatus??{},t=String(e.daemon_state||"unknown"),n=t==="disabled"||e.enabled===!1,r=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],i=gU(r),o=Ui(e.last_sync_at||e.last_sync_at_utc||null);return{syncState:t,syncIssueCode:e.daemon_issue_code??null,syncStateLabel:hU(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:yU(r,i),syncProblemPeers:LS(r,s=>vU(s,i)),syncOfflinePeersNames:LS(r,s=>s.status?.peer_state==="offline")}}function _U(e,t,n){const r=rm(t,t.events_filtered!=null),i=t.recent_packs[0]?.created_at??null,o=r?Tu(r.total_tokens_saved,r.total_tokens_read):"n/a",s=e.maintenance_jobs;return{maintenanceJobs:s,scopeBackfillJob:s.find(c=>c.kind===DS),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:OT(o),hasPackUsage:r!==null,lastPackAt:i,packAgeSeconds:Ui(i),...bU(),hasBacklog:n.pending>=200}}function Ke(e,t,n){e.score+=t,e.drivers.push(n)}function wU(e,t){t.rawPending>=1e3?Ke(e,40,"high raw-event backlog"):t.rawPending>=200&&Ke(e,24,"growing raw-event backlog"),t.erroredBatches>0&&t.rawPending>=200&&Ke(e,t.erroredBatches>=5?10:6,"batch errors during backlog pressure"),t.flushSuccessRate<.95&&Ke(e,20,"lower flush success"),t.droppedRate>.02?Ke(e,24,"high dropped-event rate"):t.droppedRate>.005&&Ke(e,10,"non-trivial dropped-event rate")}function SU(e,t){t.syncState==="error"&&Ke(e,36,t.syncIssueCode==="coordinator_timeout"?"coordinator sync requests timed out":"background sync failed"),t.syncState==="needs_attention"&&Ke(e,40,"sync needs manual attention"),t.syncState==="stopped"&&Ke(e,22,"sync daemon stopped"),t.syncState==="stale"&&Ke(e,20,"sync daemon stale"),t.syncState==="rebootstrapping"&&Ke(e,20,"sync daemon rebootstrapping"),t.syncState==="degraded"&&(!t.syncRecentlyOk||t.syncHasRecentFailedAttempt||t.syncProblemPeers.length>0)&&Ke(e,t.syncRecentlyOk?26:20,"sync with paired devices failed"),t.syncState==="ok"&&t.syncHasRecentFailedAttempt&&Ke(e,26,"sync with paired devices failed")}function CU(e,t){if(t.syncOfflinePeers){Ke(e,4,"all peers currently offline"),t.syncLooksStale&&Ke(e,4,"offline peers and sync not recent");return}if(t.syncLooksStale){Ke(e,26,"sync looks stale");return}t.syncAgeSeconds!==null&&t.syncAgeSeconds>1800&&Ke(e,12,"sync not recent")}function RU(e){const t={score:0,drivers:[]};return wU(t,e),e.hasLowTagCoverage&&Ke(t,8,"low tag coverage"),e.hasFailedMaintenance&&Ke(t,30,"maintenance job failed"),!e.syncDisabled&&(!e.syncNoPeers||e.syncState==="error")&&(SU(t,e),CU(t,e)),e.reductionPercent!==null&&e.reductionPercent<10&&Ke(t,8,"low retrieval reduction"),e.packAgeSeconds!==null&&e.packAgeSeconds>86400&&Ke(t,12,"memory pack activity is old"),t}function IU(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 kU(e){const t=IU(e),n=String(e.title||"Maintenance"),r=e.kind===DS;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 NU(e){if(!e.hasReliability)return Ye("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 Ye("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?Ye("pipeline","Pipeline",`${n}Events dropped`,"attention","Raw-event queue pressure and flush reliability"):t?Ye("pipeline","Pipeline",`${n}Reliability degraded`,"degraded","Raw-event queue pressure and flush reliability"):Ye("pipeline","Pipeline",`${e.rawPending.toLocaleString()} pending`,"degraded","Raw-event queue pressure and flush reliability")}function PU(e){return e.syncDisabled?Ye("sync","Sync","Off","unknown","Daemon state and sync recency"):e.syncState==="unknown"?Ye("sync","Sync","Unknown","unknown","Daemon state and sync recency"):e.syncNoPeers&&e.syncState!=="error"?Ye("sync","Sync","No peers","unknown","Daemon state and sync recency"):e.syncState==="ok"&&e.syncHasRecentFailedAttempt?Ye("sync","Sync","Degraded","degraded","Daemon state and sync recency"):e.syncState==="degraded"&&e.syncRecentlyOk&&!e.syncHasRecentFailedAttempt&&e.syncProblemPeers.length===0?Ye("sync","Sync","Syncing","online","Daemon state and sync recency"):cU.has(e.syncState)?Ye("sync","Sync",e.syncStateLabel,"degraded","Daemon state and sync recency"):lU.has(e.syncState)?Ye("sync","Sync",e.syncStateLabel,"unknown","Daemon state and sync recency"):e.syncLooksStale?Ye("sync","Sync","Stale","degraded","Daemon state and sync recency"):Ye("sync","Sync","On","online","Daemon state and sync recency")}function TU(e){if(!e.hasPackUsage)return Ye("retrieval","Retrieval","No packs yet","unknown","Reduction from memory reuse across recent usage");if(e.reductionPercent===null)return Ye("retrieval","Retrieval","Unknown","unknown","Reduction is unavailable for the recorded pack usage");const t=e.reductionPercent!==null&&e.reductionPercent<10;return Ye("retrieval","Retrieval",e.reductionLabel,t?"degraded":"online","Reduction from memory reuse across recent usage")}function AU(e){if(!e.lastPackAt)return Ye("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 Ye("freshness","Data freshness","Unknown","unknown","The last memory pack timestamp is unavailable");const t=e.packAgeSeconds!==null&&e.packAgeSeconds>86400;return Ye("freshness","Data freshness",na(e.packAgeSeconds),t?"degraded":"online","Recency of last memory pack activity")}function Ye(e,t,n,r,i){return{key:e,label:t,value:n,state:r,title:i}}function EU(e){return[NU(e),PU(e),TU(e),AU(e)]}function xU(e){return e.hasBacklog?[{label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status",action:t=>dr({subsystem:"capture",trigger:t}),actionLabel:"View diagnostics"},{label:`Then retry failed batches for impacted sessions (${xS()}).`,command:"codemem db raw-events-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?LU(e):[]}function OS(e){const t=e.slice(0,2).join(", ");return e.length>2?`${t} +${e.length-2} more`:t}function DU(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 jU(e){const t=OS(e.syncProblemPeers);if(e.syncState==="error")return DU(e,t);if(e.syncState==="offline-peers"){const n=OS(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 LU(e){return[{label:jU(e),command:"codemem sync doctor",action:t=>dr({subsystem:"sync",trigger:t}),actionLabel:"View diagnostics"}]}function OU(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>dr({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function $U(e){const t=xU(e);OU(t,e.hasFailedMaintenance),e.hasLowTagCoverage&&t.length<2&&t.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db 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 $S(e,t){e&&(e.className=`health-dot ${t.className}`,e.title=t.label)}function MU(e,t,n,r,i){const o=$U(t),s=t.maintenanceJobs.map(kU);$S(e.healthDot,r),kS(e.healthGrid,EU(t),s),PS(e.healthActions,o),NS(e.healthStatus,{label:r.label,message:pU(n.drivers.length,n.drivers),stale:i,state:fU(r.className),statusClass:r.className}),Wa()}function MS(){const e=uU();if(!e)return;Uq(document.getElementById("healthUpdateBanner"),_.lastUpdateStatus);const t=Fn(_.healthStats),n=Fn(_.healthUsage,_.currentProject),r=Fn(_.healthRawEvents);if(!t||!n||!r){FU(e);return}const i=_U(t,n,r),o=RU(i),s=[_.healthStats,_.healthUsage,_.healthRawEvents].some(c=>Sc(c));MU(e,i,o,mU(o.score,s),s)}function FU(e){const t=[_.healthStats,_.healthUsage,_.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…"),kS(e.healthGrid,[],[]),PS(e.healthActions,[]),NS(e.healthStatus,{label:o,message:s,stale:!1,state:i?"syncing":"unknown",statusClass:"status-unknown"}),$S(e.healthDot,{label:o,className:"status-unknown"}),Wa()}function BU(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=Fn(_.healthUsage,_.currentProject),r=Fn(_.healthSession,_.currentProject),{latestPack:i,packCount:o,packLine:s}=qU(n),c=i?.created_at||"",l=c?`Last pack: ${Vr(c)}`:"",d=_.currentProject?"Project":"All projects",u=UU(r,_.healthSession.status==="failed"),p=HU(i,o),f=GU(n,r)?"Showing stale data":"";Il(t,[d,s,l,u,f].filter(Boolean).join(" · ")),IS(e,p),Wa()}function qU(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 UU(e,t){return e?`${e.total.toLocaleString()} stored items`:t?"Stored-item totals unavailable":""}function GU(e,t){return!!e&&Sc(_.healthUsage,_.currentProject)||!!t&&Sc(_.healthSession,_.currentProject)}function HU(e,t){const n=e?.metadata_json||{},r=e?.tokens_read??0,i=e?.tokens_saved??0,o=n.exact_duplicates_collapsed??0,s=Tu(i,r);let c="n/a";return e&&(c=n.exact_dedupe_enabled?"On":"Off"),[{label:"Last pack savings",value:e?`${ra(i)} (${s})`:"n/a",tooltip:e?`Estimate: ${i.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:e?ra(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 VU(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 KU(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=Fn(_.healthStats),r=Fn(_.healthUsage,_.currentProject),i=Fn(_.healthRawEvents),o=n?.database,s=_.currentProject,c=r?.totals_filtered??null,l=!!(s&&c),d=r?rm(r,!1):null,u=r?rm(r,l):null,p=i?.sessions??0,f=i?.pending??0,m=l&&d?`
|
|
116
116
|
Global: ${d.total_tokens_read.toLocaleString()} estimated injected`:"",g=l&&d?`
|
|
117
117
|
Global: ${d.total_tokens_saved.toLocaleString()} estimated saved`:"",b=[{label:l?"Savings (project)":"Savings",value:u?ra(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?ra(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?Tu(u.total_tokens_saved,u.total_tokens_read):"n/a",tooltip:u?`Estimated percent reduction from reuse. Factor: ${LT(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?oy(o.vector_coverage):"n/a",tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:o?oy(o.tags_coverage):"n/a",tooltip:"Share of active memories with tags",icon:"tag"}];i&&VU(b,f,p),IS(e,b),t&&zU(t,o,s),Wa()}function zU(e,t,n){if(!t){Il(e,WU(_.healthStats,"Database metrics"));return}const r=n?` · project: ${n}`:"",i=Sc(_.healthStats)?" · showing stale data":"",o=MT(t.path);Il(e,`DB: ${o} · ${FT(t.size_bytes)}${r}${i}`)}function WU(e,t){return e.status==="loading"?`Loading ${t.toLowerCase()}…`:e.status==="failed"?`${t} failed to load`:`${t} not loaded`}async function JU(e={}){const t=_.viewerActorId,n=await YI(e);e.signal?.aborted||(_.viewerActorId=n.identity.actor_id,t!==_.viewerActorId&&wn(!0))}async function YU(e={}){const t=_.currentProject;_.healthStats=wc(_.healthStats),_.healthUsage=wc(_.healthUsage,t),_.healthSession=wc(_.healthSession,t),_.healthRawEvents=wc(_.healthRawEvents),FS();const n=_.activeTab==="health"&&!_.lastUpdateStatus?dN(e).catch(uN):Promise.resolve(_.lastUpdateStatus),[r,i,o,s,c]=await Promise.all([Pl(sk(e)),Pl(ck(t,e)),Pl(lk(t,e)),Pl(dk(t,e)),n]);e.signal?.aborted||(_.healthStats=Tl(_.healthStats,r),_.healthUsage=Tl(_.healthUsage,i,t),_.healthSession=Tl(_.healthSession,o,t),_.healthRawEvents=Tl(_.healthRawEvents,s),_.lastUpdateStatus=c,FS())}function FS(){KU(),Mq(document.getElementById("automaticRecallStats"),Fn(_.healthStats)?.automatic_recall),BU(),MS()}async function Pl(e){try{return{ok:!0,data:await e}}catch(t){return{ok:!1,error:t instanceof Error?t.message:"Health request failed"}}}function Tl(e,t,n=""){return"data"in t?C0(t.data,Date.now(),n):R0(e,t.error)}function im(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function BS(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function qS(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var QU={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function US(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function XU(e){return e.targetIdentityRef??e.existingIdentityRef??""}function ZU({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Yt(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,g=XU(o),b=o.targetIdentityRef??"",[v,y]=A(g);q(()=>y(g),[g]);const S=i.identityChoices.some(x=>x.identityRef===v),w=US(i,o.existingIdentityRef),R=US(i,o.suggestedIdentityRef),k=n?.has(o.deviceRef)??!1,N=e||k||r,$=N||!o.actions.assignIdentity.enabled,E=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!v&&!S,T=!o.actions.include.enabled||E||F||!b||v!==b,M=N||T,L=$||!v||E||F||v===b,G=!o.enabled||T,V=e?t:k?im("device",o.deviceRef):void 0,z=[f,G?m:void 0,V].filter(Boolean).join(" "),O=[f,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:f,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),w?a("span",{children:["Current assignment: ",w,o.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!w&&R?a("span",{children:["Suggested person: ",R]}):null,a("span",{children:["Decision: ",QU[o.decision]]})]}),a("label",{htmlFor:p,children:"Person using this device"}),a("select",{"aria-describedby":z,className:"feed-search legacy-team-device-select",disabled:$,id:p,onChange:x=>y(x.currentTarget.value),value:v,children:[a("option",{value:"",children:"Choose a person"}),v&&!S?a("option",{value:v,children:"Current server assignment"}):null,i.identityChoices.map(x=>a("option",{value:x.identityRef,children:x.displayName},x.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."}):E?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!v||!b||v!==b?a("p",{className:"small",id:m,children:v?"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":L?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{L||c(o,v)},type:"button",children:"Save assignment"}),o.enabled?a(H,{children:[a("button",{"aria-describedby":z,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{M||d(o,"included",b)},type:"button",children:"Include"}),a("button",{"aria-describedby":O,"aria-disabled":N||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":O,"aria-disabled":N||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":O,"aria-disabled":N||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function eG(e){const t=BS(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(ZU,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function tG(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function nG({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=Yt(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=Hr(c.mappingChoices.map(z=>({canonicalId:z.resolvedProjectRef,displayName:z.displayName}))),m=[...new Set(c.mappingChoices.map(z=>z.resolvedProjectRef))],g=[...m].sort((z,O)=>z<O?-1:z>O?1:0),b=new Map(g.map((z,O)=>[z,`project-choice-${O+1}`])),v=new Map(c.mappingChoices.map(z=>[z.resolvedProjectRef,z])),y=m.flatMap(z=>{const O=v.get(z);return O?[{...O,label:f.get(z)??O.displayName,token:b.get(z)??""}]:[]}),S=y.find(z=>z.resolvedProjectRef===p)?.token??"",w=JSON.stringify(g),[R,k]=A(S);q(()=>k(S),[S,w]);const N=y.find(z=>z.token===R)?.resolvedProjectRef,$=n?.has(c.projectRef)??!1,E=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!R,T=e||$||r||!c.actions.map.enabled,M=T||!N||N===p,L=tG(c,f),G=[E||F?u:void 0,e?t:$?im("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(H,{children:[a("p",{className:"small",children:L?`Saved mapping: ${L}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a("select",{"aria-describedby":G||void 0,className:"feed-search legacy-team-project-select",disabled:T,id:d,onChange:z=>k(z.currentTarget.value),value:R,children:[a("option",{value:"",children:"Choose a Project"}),y.map(z=>a("option",{value:z.token,children:z.label},z.resolvedProjectRef))]}),E?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":G||void 0,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!M&&N&&o(c,N)},type:"button",children:"Save mapping"})]})]})]})}function rG(e){const t=qS(e.detail.projects),n=Hr(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(nG,{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 Ja={add:"Add",update:"Update",remove:"Remove"},iG=10;function mt(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function om(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${cr(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 am(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 Ya({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>iG;return a("section",{children:[a("h4",{children:i}),n.length>0?a(H,{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(GS,{items:n,title:i})]}):a(GS,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function GS({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 oG({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]=A(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),f=o.teamChanges.map(C=>{const x=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${Ja[C.change]} ${C.teamDisplayName}: change device access from ${x} to the reviewed device list.`}),m=o.membershipChanges.map(C=>`${Ja[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),g=Hr([...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}]:[]]),v=Hr(b.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),y=new Map(b.map(C=>[C.resolvedProjectRef,v.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),S=Hr([...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=>`${Ja[C.change]} ${g.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?y.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?y.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),R=o.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${Ja[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),k=o.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${Ja[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),N=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,$=om(o.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),E=om(o.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),F=om(o.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),T=n.devices.filter(C=>C.decision==="included").length,M=[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")],L=`${mt(n.projects.length,"Project")} included; ${mt(T,"included device")}.`,G=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,O=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(G,"reviewed Project")}.`:`${mt(N,"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:"})," ",O]}),a("p",{children:[a("strong",{children:mt(N,"exact access change")})," to review."]}),a("ul",{children:M.map(C=>a("li",{children:C},C))}),a("p",{className:"small",children:["Scope: ",L]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(Ya,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),a(Ya,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(Ya,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:w,summaryItems:$.map(C=>`${am(C,"reviewed Project")}, ${mt(C.changeCount,"Project change")}`),title:"Projects"}),a(Ya,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:R,summaryItems:E.map(C=>`${am(C,"canonical Project")}, ${mt(C.changeCount,"recipient change")}`),title:"Recipients"}),a(Ya,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:k,summaryItems:F.map(C=>`${am(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":p||void 0,"aria-disabled":u?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{u||i(n)},type:"button",children:r?"Finishing Team setup…":"Finish Team setup"})]})}function aG(e){let t=null;return async n=>{try{const r=await sG(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){let i,o;try{i=await cG(n,e,r)}catch(s){o=s}return n.kind==="load"&&!n.refresh&&!n.completionOnly&&r instanceof Me&&r.errorCode==="team_setup_confirmation_stale"&&i&&i.state!=="unavailable"?{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:i}:{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}}}async function sG(e,t,n,r){switch(e.kind){case"load":return e.refresh?t.refreshCandidate(e.candidateRef):t.loadDetail(e.candidateRef);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function cG(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Me)||!fi(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 fi(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function HS(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function lG(e,t,n){return KS(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function VS(e,t){return KS(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function KS(e,t){return{id:e,targetId:t}}var sm="Team setup changed since it was last reviewed. Reload the latest details to continue.",zS="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",WS="Team device details are temporarily unavailable. Check the coordinator connection and settings, then retry loading.",dG="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",uG="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.",JS="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",YS="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",pG="Another device completed this Team with different reviewed details. Retry to load the completed setup.",fG="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function mG(){return{status:"closed",generation:0}}function cm(e,t){switch(t.type){case"open":return e.status==="open"&&Xn(e)?e:hG(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Xn(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 gG(e,t.step);case"blocked_navigation":return Al(e,t.step,t.message);case"retry":return vG(e);case"refresh":return bG(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return lm(e,t,"assign_device");case"decide_device":return lm(e,t,"decide_device");case"clear_device":return lm(e,t,"clear_device");case"map_project":return yG(e,t);case"finish":return _G(e);case"command_started":return FG(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return wG(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function hG(e,t){return Cr({status:"open",generation:e,candidateRef:t,view:null,step:"devices",projectsVisitedAttemptId:null,commands:[],nextCommandId:1,errors:[],message:"",focus:null,nextFocusId:1},{kind:"load",candidateRef:t,refresh:!1,focusOnOutcome:!1})}function gG(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return Al(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return Al(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return Al(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:HS(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function Al(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?BS(e.view.devices).findIndex(i=>i.decision==="unresolved"):qS(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:lG(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function vG(e){if(e.status!=="open"||e.step==="completed"||Qa(e)||Xn(e))return e;const t=El(e)??e.errors.find(r=>r.retry),n=t?.retry??"load";return Cr(e,{kind:"load",candidateRef:e.candidateRef,refresh:n==="refresh",completionOnly:n==="completion",readOnlyRecovery:n==="load"&&t?.readOnlyRetry===!0,focusOnOutcome:!0})}function lm(e,t,n){if(e.status!=="open"||e.step==="completed"||!dm(e.view)||El(e)||Qa(e)||Xn(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return Cr(mi(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function yG(e,t){if(e.status!=="open"||e.step==="completed"||!dm(e.view)||El(e)||Qa(e)||Xn(e))return e;const n=e.view.projects.find(r=>r.projectRef===t.projectRef);return!n?.actions.map.enabled||!n.mappingChoices.some(r=>r.resolvedProjectRef===t.resolvedProjectRef)?e:Cr(mi(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 bG(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||Qa(e)||Xn(e)?e:Cr(mi(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function _G(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:Cr(mi(e,{kind:"global"}),{kind:"finish",candidateRef:e.candidateRef,attemptId:e.view.attemptId,input:{attemptId:e.view.attemptId,finishDigest:e.view.finishDigest,confirmedAccessDeltaDigest:e.view.accessDeltaDigest,confirmedViewerAccessDeltaDigest:e.view.viewerAccessDeltaDigest}},"Finishing Team setup.")}function Cr(e,t,n=e.message){const r=`${e.generation}:${e.nextCommandId}`;return{...e,commands:[...e.commands,{...t,generation:e.generation,id:r,status:"pending"}],nextCommandId:e.nextCommandId+1,message:n}}function wG(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"?QS(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new Me(409,"team_setup_confirmation_stale")}):t.status==="failure"?QS(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?CG(r,n.attemptId):t.view?XS({...MG(r,n),message:SG(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function SG(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 QS(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?XS(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=t.kind==="load"&&!t.refresh&&n.recoveredView?.state==="unavailable",o=RG(t,i&&n.recoveredView?.state==="unavailable"?new Me(409,n.recoveredView.unavailableReason):n.cause,i?void 0:n.recoveryCause),s={...r,errors:[...mi(r,o.scope).errors,o],message:""};return t.kind!=="load"||!t.focusOnOutcome?s:{...s,focus:VS(s.nextFocusId,{hasError:!0,recovery:s.view?.state==="unavailable",step:s.step}),nextFocusId:s.nextFocusId+1}}function XS(e,t,n){const r=OG(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:$G(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:VS(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!nC(s,t.attemptId)&&(s=Cr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function CG(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:HS(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return nC(n,t)||(n=Cr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function RG(e,t,n){const r=t instanceof Me&&fi(t.errorCode),i=t instanceof Me&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=DG({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i}),l=c?null:EG(e,t,n),d=r||i||o!==null,u=TG(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null}),p=IG(e,t,n,u);return{scope:kG(e,{globalError:d}),message:l??s,hideStaleView:!!l||e.kind==="load"&&e.completionOnly||p,readOnlyRetry:p,retry:u}}function IG(e,t,n,r){return e.kind!=="load"||r!=="load"?!1:e.readOnlyRecovery?!0:t instanceof Me&&t.errorCode==="team_setup_confirmation_stale"&&!!n}function kG(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 NG(e,t,n){const r=n instanceof Me&&n.errorCode==="team_setup_confirmation_stale",i=t instanceof Me&&t.errorCode==="team_setup_confirmation_stale";return!i&&!r?null:e.kind==="load"&&!e.refresh&&i&&n&&(!(n instanceof Me)||!fi(n.errorCode))?"load":e.kind==="load"&&e.refresh?"completion":"refresh"}function PG(e,t){return e.kind!=="load"||!e.readOnlyRecovery||e.refresh||e.completionOnly?null:t instanceof Me&&fi(t.errorCode)?"refresh":"load"}function TG(e,t,n,r){if(e.kind==="load"&&n instanceof Me&&xl(n.errorCode)!==null)return"completion";if(r.terminalRecovery)return e.kind==="load"?"completion":"load";const i=NG(e,t,n);if(i)return i;if(e.kind==="load"&&e.completionOnly)return AG(t);const o=PG(e,t);return o||(r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load")}function AG(e){return e instanceof Me&&fi(e.errorCode)?"refresh":"completion"}function EG(e,t,n){return e.kind!=="load"||e.refresh||!(t instanceof Me)||t.errorCode!=="team_setup_confirmation_stale"||!n?null:n instanceof Me&&n.errorCode==="team_setup_roster_unavailable"?WS:n instanceof Me&&n.errorCode==="team_setup_completion_unavailable"?JS:n instanceof Me&&fi(n.errorCode)?sm:"The current Team setup could not be loaded. Retry to check the latest details."}function xG(e,t){return e.kind==="load"&&e.readOnlyRecovery?WS:e.kind!=="finish"?zS:t instanceof Me&&t.reason==="local_candidate_scan_budget_exceeded"?uG:dG}function DG(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Me?xl(n.errorCode):null,c=LG(r instanceof Me?xl(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?jG(n):eC(l);return c?{completionCode:l,message:d??ZS(t.kind),terminalRecoveryCode:c}:i?{completionCode:l,message:sm,terminalRecoveryCode:c}:o?{completionCode:l,message:xG(t,n),terminalRecoveryCode:c}:{completionCode:l,message:d??ZS(t.kind),terminalRecoveryCode:c}}function jG(e){return e instanceof Me&&e.reason==="coordinator_route_missing"?`${YS} The coordinator may be running an older version.`:YS}function LG(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function ZS(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 OG(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function dm(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Xn(e){return e.commands.some(t=>t.kind==="load"&&t.refresh||["refresh","assign_device","decide_device","clear_device","map_project","finish"].includes(t.kind))}function Qa(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function El(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function $G(e){if(fi(e))return sm;if(e==="team_setup_roster_unavailable")return zS;const t=eC(xl(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 xl(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function eC(e){return e==="team_setup_completion_unavailable"?JS:e==="team_setup_completion_conflict"?pG:e==="team_setup_completion_invalid"?fG:null}function tC(e){return e.kind==="global"||e.kind==="load"}function mi(e,t){const n=tC(t);return{...e,errors:e.errors.filter(r=>n?!tC(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function MG(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?mi(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?mi(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function FG(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function nC(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var BG={role:"list"},qG={role:"listitem"};function UG(e,t){return e?.state==="unavailable"||t?.retry==="refresh"||(t?.scope.kind==="load"||t?.hideStaleView===!0)&&!!e}function GG(e){const t=e.session,n=t.view,r=El(t),i=t.commands.some(w=>w.kind==="load"),o=Qa(t)||Xn(t),s=t.commands.some(w=>w.kind==="finish"),c=UG(n,r),l=r!=null&&(!n||c),d=!dm(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,p=n?`Set up ${n.candidate.displayName}`:"Set up Team",f=t.errors.filter(w=>w.scope.kind==="device"||w.scope.kind==="project"),m=f.length>0,g=f.some(w=>w.retry==="refresh"),b=new Set(f.flatMap(w=>w.scope.kind==="device"?[w.scope.itemRef]:[])),v=new Set(f.flatMap(w=>w.scope.kind==="project"?[w.scope.itemRef]:[])),y=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(jn,{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(Ru,{children:p})}),a(qr,{ariaDisabled:o,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[f.map(w=>a("p",{"aria-live":"assertive",id:"itemRef"in w.scope?im(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(H,{children:[t.step!=="completed"&&!l?a(HG,{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(eG,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:b,busyDeviceRefs:y,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(rG,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:v,busyProjectRefs:S,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(oG,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(VG,{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 HG(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(H,{children:[a("ol",{...BG,"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",{...qG,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 VG(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 KG={clearDecision:Lk,finish:Mk,loadDetail:xk,onCompleted:()=>{},refreshCandidate:$k,saveAssignment:Dk,saveDecision:jk,saveProjectMapping:Ok},um="codemem:open-legacy-team-setup";function rC(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(um,{detail:t})),t.handled}function zG(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 WG({dependencies:e}){const[t,n]=A(mG),r=D(null),i=_e(()=>aG(e),[e]),o=l=>{n(d=>cm(d,l))};return ot(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Xn(p)?cm(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):cm(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(um,l),()=>{window.removeEventListener(um,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(GG,{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(Xn(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=>YG(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:JG,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var JG=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function YG(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(zG(t.current)?t.current:n)?.focus(),t.current=null}function QG(e,t={}){const n={...KG,...t};ke(a(WG,{dependencies:n}),e)}function pm(e,t){return`${e}-${Array.from(t,n=>(n.codePointAt(0)??0).toString(16).padStart(6,"0")).join("")||"empty"}`}function Dl(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function bo(e){return e.identity_source!=="unmapped"&&!Dl(e)}function iC(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function XG(e){return e.git_remote||e.repository_identity||e.cwd||""}function ZG(e){return e==="git_repository"?"git repository":e.replaceAll("_"," ")}function fm(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 jl(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`${fm(r,n.scopes)} · ${n.label}`}return"Unknown Space"}function oC(e,t){return e?t.scopeGroups.some(n=>n.scopes.some(r=>r.scope_id===e)):!1}function aC(e,t,n){for(const r of[t,e.suggested_scope_id,e.resolved_scope_id])if(oC(r,n))return r??"";return e.resolved_scope_id||""}function sC(e,t){return Dl(e)?"From other devices":jl(e.resolved_scope_id,t)}function e2(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 t2(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 mm(e){return(e.guardrail_warnings??[]).filter(t=>t.severity==="warning").length}function n2(e){const t=[];return(mm(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"}),Dl(e)&&t.push({label:"From another device"}),e.identity_source==="unmapped"&&t.push({label:"No stable identity",tone:"badge-offline"}),t}function r2(e,t){return[["Workspace identity",e.workspace_identity],["Repository identity",e.repository_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",sC(e,t)],["Suggested Space",e.suggested_scope_id?jl(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],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]]}function i2({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 o2({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:t2(n)})," — ",n.lifecycle.label,"."," ",n.lifecycle.explanation]},n.person.actor_id))})]}):null}function a2({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 s2({model:e,view:t}){const{project:n}=e,r=Dl(n),i=(n.guardrail_warnings??[]).filter(o=>o.severity==="warning");return a(H,{children:[a("div",{className:"project-inventory-domain",children:sC(n,t)}),a("div",{className:"project-inventory-meta",children:[r?"source-owned project":e2(n.resolution_reason)," ·"," ",ZG(n.identity_source)," · ",iC(n.latest_session_at)]}),a(o2,{model:e}),a(a2,{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 ${jl(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:r2(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 c2(e){const{callbacks:t,currentAssignable:n,model:r,scopeId:i,selectRef:o,setScopeId:s,view:c}=e,{project:l}=r,d=pm("project-domain",r.key),u=!i||i===l.resolved_scope_id&&!n,p=l.suggested_scope_id&&i===l.suggested_scope_id?"Confirm suggestion":"Save Space";return a(H,{children:[a("label",{className:"sr-only",htmlFor:d,children:["Space for ",l.display_project]}),a("select",{className:"project-domain-select",id:d,onBlur:t.onSpaceSelectBlur,onChange:f=>{s(f.currentTarget.value),t.setProjectScopeDraft(l.workspace_identity,f.currentTarget.value)},ref:o,value:i,children:[!n&&l.resolved_scope_id?a("option",{disabled:!0,value:l.resolved_scope_id,children:[jl(l.resolved_scope_id,c)," — not assignable"]}):null,c.scopeGroups.map(f=>a("optgroup",{label:f.label,children:f.scopes.map(m=>a("option",{value:m.scope_id,children:fm(m,f.scopes)},m.scope_id))},f.key))]}),a("button",{className:"settings-button",disabled:u,onClick:()=>{t.saveProjectScope(l.workspace_identity,i)},type:"button",children:p})]})}function l2({callbacks:e,model:t}){const{project:n}=t;return a(H,{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 d2({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(i2,{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 u2({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 p2(e){const{callbacks:t,model:n,view:r}=e,{project:i}=n,o=bo(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(H,{children:[a(c2,{...e}),a(l2,{callbacks:t,model:n}),a(d2,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n}),a(u2,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n})]}):null]})}function f2(e){const{model:t,onOpenChange:n,open:r,view:i}=e,{project:o}=t,s=bo(o),[c,l]=A(()=>aC(o,t.draftScopeId,i));q(()=>{l(aC(o,t.draftScopeId,i))},[t.draftScopeId,o,i]);const d=i.scopeGroups.some(u=>u.scopes.some(p=>p.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"}),mm(o)>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",mm(o)]}):null]}),a("div",{className:"project-inventory-details-body",children:[a(s2,{model:t,view:i}),a(p2,{...e,currentAssignable:d,scopeId:c,setScopeId:l})]})]})})})}function m2(e,t,n){if(n.length===0)return null;if(e==="Home")return n[0]??null;if(e==="End")return n.at(-1)??null;const r=Math.max(0,n.indexOf(t));return e==="ArrowDown"?n[(r+1)%n.length]??null:e==="ArrowUp"?n[(r-1+n.length)%n.length]??null:null}function h2({actions:e,close:t,dismiss:n,enabled:r,itemRefs:i,label:o,menuId:s}){return a("div",{"aria-label":o,className:"feed-menu-panel project-row-menu-panel",id:s,onKeyDown:l=>{if(l.key==="Tab"){n();return}if(l.key==="Escape"){l.preventDefault(),t();return}const d=i.current.indexOf(document.activeElement),u=m2(l.key,d,r);u!=null&&(l.preventDefault(),i.current[u]?.focus())},role:"menu",children:e.map((l,d)=>a("button",{className:`feed-menu-item${l.danger?" danger":""}`,disabled:l.disabled,onClick:()=>{t(),l.onSelect()},ref:u=>{i.current[d]=u},role:"menuitem",tabIndex:-1,type:"button",children:l.label},l.label))})}function cC({actions:e,label:t}){const[n,r]=A(!1),i=D("first"),o=D([]),s=Yt(),c=D(null),l=D(null),d=e.flatMap((m,g)=>m.disabled?[]:[g]),u=()=>{r(!1),queueMicrotask(()=>l.current?.focus())},p=()=>r(!1);return q(()=>{if(!n)return;const m=i.current==="last"?d.at(-1):d[0];queueMicrotask(()=>(m==null?l.current:o.current[m])?.focus());const g=b=>{c.current?.contains(b.target)||r(!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[n]),a("div",{className:"project-row-menu",ref:c,children:[a("button",{"aria-controls":s,"aria-expanded":n,"aria-haspopup":"menu","aria-label":t,className:"feed-menu-trigger","data-state":n?"open":"closed",onClick:()=>{i.current="first",r(m=>!m)},onKeyDown:m=>{m.key!=="ArrowDown"&&m.key!=="ArrowUp"||(m.preventDefault(),i.current=m.key==="ArrowUp"?"last":"first",r(!0))},ref:l,type:"button",children:"⋯"}),n?a(h2,{actions:e,close:u,dismiss:p,enabled:d,itemRefs:o,label:t,menuId:s}):null]})}function g2(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(cC,{actions:t,label:`More actions for ${e.label}`})}function v2({label:e,onOpenSpaceAssignment:t}){return a(cC,{actions:[{label:"Space assignment for all…",onSelect:t}],label:`More actions for ${e}`})}function lC({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:"Not shared"});const r=n.slice(0,2),i=n.length-r.length;return a("div",{className:"project-recipient-summary",children:[a("ul",{"aria-label":"Active recipients",className:"project-recipient-chips",children:[r.map(o=>a("li",{className:`project-recipient-chip project-recipient-chip-${o.kind.toLowerCase()}`,children:[o.kind,": ",o.displayName]},o.key)),i>0?a("li",{className:"project-recipient-chip",children:["+",i]}):null]}),t?a("span",{className:"project-recipient-status",children:[n.length," recipients"]}):null]})}function y2({model:e,view:t}){const{project:n}=e;return a(H,{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:iC(n.latest_session_at)}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(lC,{available:t.recipientPolicyReady,recipients:e.recipients})})]})}function b2({callbacks:e,model:t,onOpenDetails:n,view:r}){const{project:i}=t;return!bo(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,bo(i)?a(g2,{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 _2(e){const{callbacks:t,child:n,model:r,titleId:i,view:o}=e,{project:s}=r,c=XG(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:n2(s).map(l=>a(Ue,{tone:l.tone,variant:"badge",children:l.label},l.label))})]}),a(y2,{model:r,view:o}),a(b2,{...e})]})}function dC({callbacks:e,child:t=!1,clusterKey:n,model:r,view:i}){const{project:o}=r,[s,c]=A(r.detailsOpen),l=D(null),d=D(null),u=g=>{c(g),e.setProjectDetailsOpen(r.detailKey,g)};q(()=>{r.detailsOpen&&c(!0)},[r.detailsOpen]);const p=!!(r.pendingConfirmation||r.pendingForgetConfirmation);q(()=>{p&&(u(!0),queueMicrotask(()=>d.current?.focus()))},[p]);const f=()=>{u(!0),queueMicrotask(()=>l.current?.focus())},m=pm("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(bo(o)),"data-project-workspace-identity":o.workspace_identity,children:[a(_2,{callbacks:e,child:t,model:r,onOpenDetails:f,titleId:m,view:i}),a(f2,{callbacks:e,confirmationActionRef:d,model:r,onOpenChange:u,open:s,selectRef:l,view:i})]})}function w2(e){const t=e.projects.filter(o=>bo(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 S2(e){const t=D(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 C2({model:e,summary:t,view:n}){return a(H,{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(lC,{available:n.recipientPolicyReady,cluster:!0,recipients:e.recipients})})]})}function R2({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(v2,{label:t.label,onOpenSpaceAssignment:n}):null]})}function I2(e){const{callbacks:t,model:n,onToggleWorktrees:r,summary:i,titleId:o,worktreesOpen:s}=e,c=S2(n),l=e.view.rows.filter(p=>p.kind==="cluster"&&p.label===n.label),d=l.length>1?` (group ${l.findIndex(p=>p.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 identities 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 identities 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(Ue,{variant:"badge",children:[n.projects.length," worktrees"]}),a("button",{"aria-expanded":s,"aria-label":`${s?"Hide":"Show"} worktrees for ${n.label}${d}`,className:"settings-button project-worktrees-toggle",onClick:p=>{s&&p.currentTarget.focus(),r()},type:"button",children:s?"Hide worktrees":"Show worktrees"}),i.warningTotal>0?a(Ue,{tone:"badge-offline",variant:"badge",children:["Needs attention · ",i.warningTotal]}):null]})]}),a(C2,{...e}),a(R2,{...e})]})}function k2(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 identities were received from other devices. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.";return a("div",{className:"settings-note",children:d})}const l=oC(r,c);return a(H,{children:[a("select",{"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:fm(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?"identity":"identities"]})]})}function N2({summary:e}){return e.blocking.length>0?a("div",{className:"settings-note project-attention-note",children:["One or more identities in this group need individual review before bulk assignment.",a("ul",{children:e.blocking.map(({project:t,warning:n})=>a("li",{children:[a("strong",{children:["Blocked identity: ",t.project.workspace_identity]})," —"," ",n.message]},`${t.key}:${n.code}`))})]}):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 P2(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(k2,{...e}),a(N2,{summary:r})]})})]})})})}function T2(e){const{callbacks:t,model:n}=e,[r,i]=A(n.detailsOpen),[o,s]=A(n.draftScopeId??""),c=D(null);q(()=>{n.detailsOpen&&i(!0)},[n.detailsOpen]),q(()=>s(n.draftScopeId??""),[n.draftScopeId]);const l=w2(n),d=f=>{i(f),t.setClusterDetailsOpen(n.key,f)},u=()=>{d(!0),queueMicrotask(()=>c.current?.focus())},p=pm("project-cluster-title",n.key);return a(H,{children:[a("tbody",{"aria-labelledby":p,className:"project-inventory-row project-inventory-cluster","data-project-cluster-key":n.key,children:[a(I2,{...e,onOpenAssignment:u,onToggleWorktrees:()=>t.setClusterWorktreesOpen(n.key,!n.worktreesOpen),summary:l,titleId:p,worktreesOpen:n.worktreesOpen}),a(P2,{...e,onOpenChange:d,open:r,scopeId:o,selectRef:c,setScopeId:s,summary:l})]}),n.worktreesOpen?n.projects.map(f=>a(dC,{callbacks:t,child:!0,clusterKey:n.key,model:f,view:e.view},`${f.project.read_only?"received":"local"}:${f.key}`)):null]})}function A2({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(T2,{callbacks:e,model:r,view:n},r.key):a(dC,{callbacks:e,model:r,view:n},r.detailKey))]})}function E2(e,t,n,r){ke(a(A2,{callbacks:n,error:r,view:t}),e)}function x2(e){if(e?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement)return document.activeElement.dataset.teamSetupCandidateRef}function D2(e,t,n){if(t){for(const r of e.querySelectorAll("button"))if(r.dataset.teamSetupCandidateRef===t){r.focus();return}n()}}function j2(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 L2(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(j2(o,t.onOpenTeamSetup));return n}function O2(e,t,n){const r=t?.candidates??[],i=e.querySelector(":scope > .project-team-setup-entry");i?.querySelector(".project-team-setup-status")?.remove();const o=x2(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=L2(t,n);e.appendChild(c),D2(c,o,n.onFocusFallback)}function uC(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 Zn=new Set,Ll=new Set,Xa=new EventTarget,Za=new Set,pC=100,At="";function _o(e,t,n){n?e.add(t):e.delete(t),Xa.dispatchEvent(new Event("change"))}function fC(e,t){const[n,r]=A(e.has(t));return q(()=>{const i=()=>r(e.has(t));return Xa.addEventListener("change",i),i(),()=>Xa.removeEventListener("change",i)},[e,t]),n}function $2(){const[e,t]=A(()=>new Set(Zn));return q(()=>{const n=()=>t(new Set(Zn));return Xa.addEventListener("change",n),n(),()=>Xa.removeEventListener("change",n)},[]),e}function M2(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 mC(e,t){return e.options.find(n=>n.decision===t)}function F2(e){const t=e.items[0];return mC(t,t.recommendedDecision)?.label??t.recommendedDecision.replaceAll("_"," ")}function hC(e){return[...new Map(e.map(t=>[t.id,t.label])).values()]}function hm(e,t){return e.items.flatMap(n=>{const r=mC(n,t);return r?[r]:[]})}function B2(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 gC(e){const t=hC(e.flatMap(n=>n.preview.projects.map(r=>({id:r.canonicalIdentity,label:`${r.displayName} — ${r.canonicalIdentity}`}))));return{devices:hC(e.flatMap(n=>n.preview.effectiveDevices.map(r=>({id:r.deviceId,label:`${r.displayName} (${r.assignment})`})))),memoryCount:B2(e),projects:t}}function Rr(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function q2(e){return e==="unassigned_effective_device"?"Set up Identity or devices first":"Choose recipients first (Update sharing, below)"}async function U2(e){try{return await Vk(e),{stale:!1,failed:!1}}catch(t){if(!(t instanceof Fh))throw t;return Za.add(e.reviewItemId),{stale:!0,failed:!1}}}function G2(e,t){if(t.status==="stale"){Za.add(t.reviewItemId),e.stale=!0;return}t.status!=="applied"&&(e.failed=!0)}async function vC(e){const t={failed:!1,stale:!1};for(let n=0;n<e.length;n+=pC){const r=e.slice(n,n+pC),i=await Kk(r);for(const o of i.results)G2(t,o)}return t}async function H2(e,t){const n=yC(e,t),r=n[0];return n.length===1&&r?U2(r):vC(n)}function yC(e,t){return e.items.map(n=>({decision:t,reviewItemId:n.reviewItemId,sourceFingerprint:n.sourceFingerprint}))}function V2(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)Za.delete(n.reviewItemId);return"Applied"}function Ol(e,t){return e instanceof Error?e.message:t}function es(e,t){const n=hm(e,t);return n.length!==e.items.length||n.some(r=>r.preview.requiresDecisionInput)}function K2({options:e}){const{devices:t,memoryCount:n,projects:r}=gC(e);return a("div",{className:"recipient-policy-preview",children:[a("strong",{children:["Affected: ",Rr(r.length,"Project")," ·"," ",Rr(n,"memory","memories")," · ",Rr(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 bC(e,t){try{await e.onRefresh?.()}catch(n){const r=Ol(n,"Unable to refresh review items.");At=`${At} Refresh failed: ${r}`,t(At)}}function z2(e,t,n,r){const i=fC(Zn,e.key);async function o(){const s=t.current;if(!(i||es(e,s)||Zn.has(e.key))){_o(Zn,e.key,!0),At="Applying…",n(At);try{try{At=V2(e,await H2(e,s))}catch(c){At=Ol(c,"Unable to apply decision. Try again.")}n(At),await bC(r,n)}finally{_o(Zn,e.key,!1)}}}return{apply:o,pending:i}}function W2(e){const t=e.items[0],n=gC(hm(e,t.recommendedDecision)),r=[`Suggested: ${F2(e)}`,Rr(n.memoryCount,"memory","memories"),Rr(n.devices.length,"device")];return e.items.length>1&&r.push(Rr(e.items.length,"worktree")),r.join(" · ")}function J2({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:[W2(t),o?a(Ue,{variant:"badge",tone:"badge-offline",children:"Changed since loaded"}):null]})]})}function Y2(e){return a(H,{children:[a("select",{"aria-label":`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.decision,children:e.group.items[0].options.map(t=>a("option",{value:t.decision,children:t.label},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:"Details"})]})]})}function Q2({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:q2(s.conditionCode)}),a(K2,{options:i})]})}function X2({decision:e,group:t,onDecisionChange:n,onSelectedChange:r,onStatus:i,options:o,selected:s}){const c=`recipient-policy-details-${Yt()}`,[l,d]=A(!1),u=D(e),p=D(null);u.current=e;const f=hm(t,e),{apply:m,pending:g}=z2(t,u,i,o),b=es(t,e),v=f.some(S=>S.preview.requiresDecisionInput),y=t.items.some(S=>Za.has(S.reviewItemId));return a("article",{className:"recipient-policy-review-item","data-review-group":t.key,children:[a(J2,{blocked:b,group:t,onSelectedChange:r,pending:g,selected:s,stale:y}),a(Y2,{applyButtonRef:p,blocked:b,decision:e,detailsId:c,detailsOpen:l,group:t,onApply:()=>{m()},onDecisionChange:S=>{u.current=S,p.current&&(p.current.disabled=es(t,S)),n(S)},onDetailsToggle:()=>d(S=>!S),pending:g}),a(Q2,{detailsId:c,group:t,open:l,requiresInput:v,selected:f,stale:y})]})}function Z2(e){const t=D(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 actionable sharing 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 actionable"})]}),a("span",{className:"small recipient-policy-review-selection-count",children:[e.selectedCount," selected · ",e.actionableCount," actionable"]}),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 eH(e){return Object.fromEntries(e.map(t=>[t.key,t.items[0].recommendedDecision]))}function tH(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)Za.delete(r.reviewItemId);return`Applied ${Rr(e.length,"decision")}`}async function nH(e,t){return vC(e.flatMap(n=>yC(n,t[n.key]??n.items[0].recommendedDecision)))}function rH({item:e,options:t}){const n=`recipient-policy-blocked-details-${Yt()}`,r=`recipient-policy-repair-help-${Yt()}`,[i,o]=A(!1),s=fC(Ll,e.blockedItemId),c=!!(t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0));async function l(){if(!(!t.onRepair||Ll.has(e.blockedItemId))){_o(Ll,e.blockedItemId,!0);try{await t.onRepair(e.repair)}finally{_o(Ll,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(Ue,{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 iH(e){const[t,n]=A(()=>eH(e)),r=D(t),[i,o]=A(()=>new Set),s=m=>t[m.key]??m.items[0].recommendedDecision,c=e.filter(m=>!es(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),es(m,g)&&u(m.key,!1)}function u(m,g){o(b=>{const v=new Set(b);return g?v.add(m):v.delete(m),v})}function p(m){o(m?new Set(c.map(g=>g.key)):new Set)}function f(m){o(g=>{const b=new Set(g);for(const v of m)b.delete(v.key);return b})}return{actionableGroups:c,allSelected:c.length>0&&l.length===c.length,clearSelected:f,decisionFor:s,decisionsRef:r,selectAll:p,selectedGroups:l,selectedKeys:i,setDecision:d,setGroupSelected:u}}function oH(e,t,n,r){const[i,o]=A(!1),s=D(!1);async function c(l){if(!(s.current||l.length===0||l.some(d=>Zn.has(d.key)))){s.current=!0,o(!0);for(const d of l)_o(Zn,d.key,!0);At=`Applying ${Rr(l.length,"decision")}…`,n(At);try{try{const d=await nH(l,e.current);At=tH(l,d),!d.failed&&!d.stale&&r(l)}catch(d){At=Ol(d,"Unable to apply decisions. Try again.")}n(At),await bC(t,n)}finally{for(const d of l)_o(Zn,d.key,!1);s.current=!1,o(!1)}}}return{apply:c,applying:i}}function aH({options:e,review:t}){const n=M2(t.reviewItems),[r,i]=A(At),o=iH(n),s=$2(),c=oH(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 decisions ",a("span",{className:"recipient-policy-review-count",children:n.length})]}),a(Ue,{variant:"badge",tone:"badge-offline",children:"Unapplied"})]}),a("div",{className:"section-meta recipient-policy-review-status",role:"status","aria-live":"polite",children:r}),n.length>0?a(H,{children:[a(Z2,{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(X2,{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(rH,{item:l,options:e},l.blockedItemId))})]}):null]})}function sH(e,t,n={}){if(t.reviewItems.length===0&&t.blockedItems.length===0){ke(null,e),e.hidden=!0;return}e.hidden=!1,ke(a(aH,{options:n,review:t}),e)}function cH(e,t){e.hidden=!1,ke(a("section",{className:"card recipient-policy-review",children:[a("h2",{children:"Sharing decisions"}),a("p",{className:"settings-note project-attention-note",role:"status",children:Ol(t,"Unable to load sharing decisions. Try again.")})]}),e)}var _C=[["","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"]],_t=null,Kt=0,ts=250,lH=100,gm=[],ns=new Set,rs=new Set,is=new Set,os=new Map,as=new Map,Ir=new Map,ss=new Map,wo=new Map,$l=!1,So=new Map,cs=!1,hi=!1,vm=0,wC=null,er=0,ls=0,Co=null,ds=null,Et=new Set,Ml={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},Ro=Ml,Fl=!1,ym=!1,Io=!1,SC,kr={projects:[],total:0,offset:0,has_more:!1},CC=new Set;function Qe(){if(CC.size===0)return;const e=AC();for(const t of CC)t(e)}function dH(e=!1,t={}){if(!e&&ds)return ds;const n=Gh(t).then(r=>({ok:!0,summary:r})).catch(()=>({ok:!1}));return ds=n,n.then(()=>{ds===n&&(ds=null)}),n}function bm(e){return dH(e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0,e)}function Ee(e){return document.getElementById(e)}function ko(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Bl(e){return e.identity_source!=="unmapped"&&!ko(e)}function RC(e){return Bl(e)&&e.memory_count!=null&&e.guardrail_warnings.every(t=>!t.requires_confirmation)}function uH(e){return`${ko(e)?"peer-received":"local"}:${e.workspace_identity}`}function pH(e){const t=So.get(e.workspace_identity);(!t||ko(t)&&!ko(e))&&So.set(e.workspace_identity,e)}function fH(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function gi(){const e=Et.size,t=Ee("projectsShareSelected");t&&(t.textContent=e===0?"Add Teams or Identities":`Add Teams or Identities (${e})`,t.disabled=e===0||!hi||!Fl,t.classList.add("project-selection-target"));const n=Ee("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`),Nr()}function mH(e){const t=e.every(n=>Et.has(n));for(const n of e)t?Et.delete(n):Et.add(n);gi(),Qe()}function IC(e){const t=new Set(e),n=new Map(Ro.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(Ro.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of Ro.projectRecipients)if(!(o.status!=="active"||!t.has(o.canonicalProjectIdentity)))if(o.recipientKind==="team"){const s=n.get(o.teamId);s&&i.set(`team:${o.teamId}`,{key:`team:${o.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(o.identityId);s&&i.set(`identity:${o.identityId}`,{key:`identity:${o.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((o,s)=>`${o.kind}:${o.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function us(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function hH(e){return e.project||e.display_project||"Unnamed Project"}function kC(e){const t=String(e||"").trim();return t?_.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function gH(){return new Set(_.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function vH(e){return!cs||e.authority_type!=="coordinator"||!e.group_id?!1:!gH().has(String(e.group_id).trim())}function ql(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function yH(){$l&&($l=!1,_t?.())}async function bH(){let e;try{const t=await Rd();e=t&&typeof t=="object"?t:null}catch{_.lastProjectCoordinatorAdminGroups=[],cs=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){_.lastProjectCoordinatorAdminGroups=[],cs=!1;return}try{const t=await kh(!1);_.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],cs=!0}catch{_.lastProjectCoordinatorAdminGroups=[],cs=!1}}function _H(e){const t=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space",n=kC(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 wH(){return gm.filter(e=>e.scope_id!=="legacy-shared-review"&&!vH(e))}function SH(e){const t=kC(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function CH(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function RH(){const e=new Map;for(const t of wH()){const n=CH(t),r=SH(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 _m(e,t,n=[]){try{await Xk({...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}),Ir.delete(e.workspace_identity),os.delete(e.workspace_identity),Qe(),Y("Space assignment updated. Device access unchanged."),_t?.()}catch(r){if(r instanceof Ni){Ir.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),Nr(),Qe(),_t?.();return}Y(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function IH(e,t){const n=e.filter(Bl);if(n.length!==0)try{await Zk({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.`),as.delete(us(n[0])),Qe(),_t?.()}catch(r){Y(kH(r),"warning")}}function kH(e){return e instanceof Ni?"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 NH(e){if(e.mapping_id!=null)try{await eN(e.mapping_id,ss.get(e.mapping_id)??[]),ss.delete(e.mapping_id),Ir.delete(e.workspace_identity),os.delete(e.workspace_identity),Qe(),Y("Project Space assignment removed. The next fallback now applies."),_t?.()}catch(t){if(t instanceof Ni){ss.set(e.mapping_id,t.requiredGuardrailTokens),Y(`${t.guardrailWarnings[0]?.message??"Review the fallback access change."} Select Remove again to confirm.`,"warning");return}ss.delete(e.mapping_id),Y(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function PH(e,t={}){const n=t.confirmed===!0;try{const r=wo.get(e.workspace_identity),i=await nN({...n&&r?{confirmation_token:r.confirmationToken}:{},confirmed:n,workspace_identity:e.workspace_identity});wo.delete(e.workspace_identity),Qe(),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.`),_t?.()}catch(r){if(r instanceof $h){wo.set(e.workspace_identity,{confirmationToken:r.preview.confirmation_token,localOwnedMemoryCount:r.preview.local_owned_memory_count,peerOwnedMemoryCount:r.preview.peer_owned_memory_count}),Nr(),Qe(),_t?.();return}Y(r instanceof Error?r.message:"Unable to forget project memories.","warning")}}async function NC(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await ks()).filter(i=>i&&i!==t)}catch{}const r=await sf({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 tN({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"}.`),_t?.()}catch(i){Y(i instanceof Error?i.message:"Unable to change project.","warning")}}async function TH(e){const t=So.get(e);if(t&&!ko(t))return{offset:Kt,project:t};try{let n=0,r=0;for(;;){const i=await qo({limit:ts,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!ko(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>=lH)return null;n=s}}catch{return null}}function wm(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(".project-inventory-details");if(o){o.open=!0;const c=i?.dataset.projectClusterKey;c&&rs.add(c)}n.open=!0;const s=t.dataset.projectRowKey;return s&&ns.add(s),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}function PC(){return{generation:er,search:Ee("projectsSearch")?.value??"",status:Ee("projectsStatusFilter")?.value??"",offset:Kt}}function AH(e){return er!==e.generation||(Ee("projectsSearch")?.value??"")!==e.search||(Ee("projectsStatusFilter")?.value??"")!==e.status||Kt!==e.offset}async function EH(e){const{project:t}=e;if(wm(t.workspace_identity)||(is.add(us(t)),Nr(),Qe(),wm(t.workspace_identity)))return;const n=Ee("projectsSearch"),r=Ee("projectsStatusFilter"),i=PC(),o=t.workspace_identity;n&&(n.value=o),r&&(r.value=""),Kt=e.offset;const s=er;await No(),!wm(t.workspace_identity)&&(er!==s||n&&n.value!==o||r&&r.value!==""||Kt!==e.offset||(n&&(n.value=i.search),r&&(r.value=i.status),Kt=i.offset,await No(),Y("Project administration could not be opened. Refresh Projects and try again.","warning")))}async function xH(e){if(ql()){Y("Finish the open Space assignment, then try Repair again.","warning");return}const t=PC(),n=await TH(e.projectIdentity);if(AH(t))return;if(ql()){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 NC(r);return}await EH(n)}function DH(e){const t=er,n=(Co?.catch(()=>{})??Promise.resolve()).then(async()=>{if(er===t)try{await xH(e)}catch(r){Y(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Co=n,n.then(()=>{Co===n&&(Co=null)},()=>{Co===n&&(Co=null)}),n}function jH(e){const t=new Map;for(const n of e){const r=us(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function TC(e){const t=Nu(e),n=Bl(e),r=uH(e),i=n?Ir.get(e.workspace_identity):void 0,o=n?wo.get(e.workspace_identity):void 0;return{kind:"project",key:r,detailKey:r,project:e,manageable:t,selected:t&&Et.has(e.workspace_identity),shareEligible:RC(e),shareReady:hi,detailsOpen:ns.has(r),draftScopeId:n?os.get(e.workspace_identity)??null:null,pendingConfirmation:i?{requiredGuardrailTokens:[...i.requiredGuardrailTokens],scopeId:i.scopeId,warnings:[...i.warnings]}:null,pendingForgetConfirmation:o?{...o}:null,recipients:n?IC([e.workspace_identity]):[]}}function LH(e){if(e.length===1)return TC(e[0]);const t=us(e[0]),n=fH(e.filter(Nu));return{kind:"cluster",key:t,label:hH(e[0]),projects:e.map(TC),projectIds:n,selectedProjectIds:n.filter(r=>Et.has(r)),worktreesOpen:is.has(t),detailsOpen:rs.has(t),draftScopeId:as.get(t)??null,recipients:IC(n)}}function AC(){const e=[...Et].sort();return{rows:jH(kr.projects).map(LH),recipientPolicyReady:ym,shareInventoryReady:hi,scopeLabels:Object.fromEntries(gm.map(t=>[t.scope_id,_H(t)])),selection:{projectIds:e,count:e.length,ready:hi&&Fl},pagination:{offset:kr.offset,limit:ts,total:kr.total,hasMore:kr.has_more},scopeGroups:RH().map(t=>({key:t.key,label:t.label,scopes:[...t.scopes]})),statusOptions:_C.map(([t,n])=>({label:n,value:t}))}}function EC(){document.getElementById("projectsInventorySkeleton")?.remove()}function OH(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 Nr(e){if(!Io)return;const t=Ee("projectsInventoryList");t&&E2(t,AC(),XH,e)}function xC(e){Io=!0,kr={projects:[...e.projects],total:e.total,offset:e.offset,has_more:e.has_more};const t=Ee("projectsInventoryMeta"),n=Ee("projectsInventoryList");if(!t||!n)return;EC(),So.clear();for(const o of e.projects)pH(o);Nr(),t.textContent=OH(e);const r=Ee("projectsPrevPage"),i=Ee("projectsNextPage");r&&(r.disabled=e.offset===0),i&&(i.disabled=!e.has_more),gi(),Qe()}function $H(e,t,n){bH().then(()=>{if(t===vm&&Sm(n)){if(ql()){Qe();return}xC(e)}})}async function MH(e={}){const t=new Map;let n=0;for(;;){const r=await qo({limit:250,offset:n,signal:e.signal});for(const i of r.projects)t.set(i.workspace_identity,i);if(!r.has_more)break;n+=r.limit}return[...t.values()]}function DC(){return{query:Ee("projectsSearch")?.value.trim()??"",status:Ee("projectsStatusFilter")?.value??"",offset:Kt}}function Sm(e){const t=DC();return t.query===e.query&&t.status===e.status&&t.offset===e.offset}function FH(e,t){return qo({limit:ts,offset:t.offset,q:t.query||void 0,status:t.status||void 0,signal:e.signal})}function jC(e,t,n){const r=Ee("recipientPolicyManagementMount");r&&ry(r,Zs(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Et.clear(),gi(),Qe(),_t?.()}})}function BH(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 LC(e,t){O2(e,t,{onOpenTeamSetup:SC,onFocusFallback:()=>Ee("projectsSearch")?.focus()})}function No(e={}){const t=QH(e);return wC=t,t}async function OC(e,t){return e.signal?.aborted?!1:!e.awaitTeamSetupSummary&&!e.requireTeamSetupSummary?wC??!1:(await t,!1)}function Ul(e,t){return!t.signal?.aborted&&e===vm}function Gl(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}async function qH(e){if(!Gl(e))return!0;const t=await bm(e);return e.signal?.aborted?!1:!e.requireTeamSetupSummary||t.ok}async function UH(e){if($l=!0,!Gl(e))return!0;const t=++ls,n=await bm(e);if(e.signal?.aborted||t!==ls)return!1;const r=Ee("recipientPolicyReviewMount");return n.ok?(r&&LC(r,n.summary),!0):(r&&uC(r),!e.requireTeamSetupSummary)}function GH(e){return Gl(e.options)?e.teamSetupSummaryPromise.then(t=>!Ul(e.loadGeneration,e.options)||e.entryLoadGeneration!==ls?!1:e.requiredLoadSucceeded&&(!e.options.requireTeamSetupSummary||t.ok)):e.requiredLoadSucceeded}async function HH(e,t){return Gl(e)&&await t,!1}function VH(e){const t=Ee("recipientPolicyReviewMount");if(!t)return;const n=BH(t);"review"in e?sH(n,e.review,{isRepairAvailable:r=>!r.projectIdentity.startsWith("unmapped:"),onRefresh:async()=>{await No()},onRepair:DH}):cH(n,e.error),t.hidden=n.hidden&&!t.querySelector(".project-team-setup-entry")}async function KH(e,t){const[n,r,i,o,s]=await Promise.all([FH(e,t),zk(e),MH(e).then(c=>({ok:!0,projects:c})).catch(()=>({ok:!1,projects:[]})),Hk(e).then(c=>({ok:!0,review:c})).catch(c=>({ok:!1,error:c})),xd(e).then(c=>({ok:!0,intent:c})).catch(c=>({ok:!1,error:c}))]);return{intentResult:s,recipientPolicyReview:o,result:n,settings:r,shareInventory:i}}function zH(e){if(!e.ok)return;const t=new Set(Zs(e.projects).map(n=>n.canonicalProjectIdentity));for(const n of Et)t.has(n)||Et.delete(n)}function WH(e,t,n){const{intentResult:r,recipientPolicyReview:i,result:o,settings:s,shareInventory:c}=e;gm=s.scopes,hi=c.ok,Fl=r.ok,ym=r.ok,Ro=r.ok?r.intent:Ml,zH(c);const l=Ee("projectShareFlowMount");return l&&dy(l,c.projects,{inventoryError:!c.ok}),VH(i),jC(c.projects,Ro,!c.ok||!r.ok),xC(o),$H(o,t,n),c.ok&&"review"in i&&r.ok}function JH(e){e.teamSetupSummaryPromise.then(t=>{if(!Ul(e.loadGeneration,e.options)||e.entryLoadGeneration!==ls)return;const n=Ee("recipientPolicyReviewMount");if(n){if(!t.ok){uC(n);return}LC(n,t.summary)}})}function YH(e,t){Io=!0,So.clear(),kr={projects:[],total:0,offset:Kt,has_more:!1},hi=!1,Fl=!1,ym=!1,Ro=Ml;const n=Ee("projectShareFlowMount");n&&dy(n,[],{inventoryError:!0}),jC([],Ml,!0),gi(),Qe(),EC(),t.textContent="Project inventory failed to load.",Nr(e instanceof Error?e.message:"Unable to load project inventory.")}async function QH(e){const t=Ee("projectsInventoryMeta"),n=Ee("projectsInventoryList");if(!t||!n)return qH(e);if(ql())return UH(e);$l=!1;const r=++vm,i=DC();Io||gi(),(!Io||!t.textContent?.trim())&&(t.textContent="Loading project inventory…");let o=null;try{const s=++ls;o=bm(e);const c=await KH(e,i);if(!Ul(r,e))return OC(e,o);if(!Sm(i))return!1;const l=WH(c,r,i);return JH({entryLoadGeneration:s,loadGeneration:r,options:e,teamSetupSummaryPromise:o}),GH({entryLoadGeneration:s,loadGeneration:r,options:e,requiredLoadSucceeded:l,teamSetupSummaryPromise:o})}catch(s){return Ul(r,e)?Sm(i)?(YH(s,t),HH(e,o)):!1:OC(e,o)}}function vi(e){return So.get(e)??kr.projects.find(t=>t.workspace_identity===e)??null}var XH={toggleSelection(e){mH(e)},shareProject(e){const t=vi(e);!t||!RC(t)||!hi||tc([t.workspace_identity])},manageRecipients(e){const t=[...new Set(e)].sort();if(t.length!==0){if(t.length===1){Zo({mode:"project-manage",projectId:t[0]});return}for(const n of t)Et.add(n);gi(),Qe(),Zo({mode:"project-add",projectIds:t})}},setProjectDetailsOpen(e,t){t?ns.add(e):ns.delete(e),Qe()},setClusterDetailsOpen(e,t){t?rs.add(e):rs.delete(e),Qe()},setClusterWorktreesOpen(e,t){t?is.add(e):is.delete(e),Nr(),Qe()},setProjectScopeDraft(e,t){os.set(e,t),Ir.delete(e),Nr(),Qe(),_t?.()},setClusterScopeDraft(e,t){t?as.set(e,t):as.delete(e),Qe()},async saveProjectScope(e,t){const n=vi(e);n&&await _m(n,t)},async saveClusterScope(e,t){const n=kr.projects.filter(r=>us(r)===e).filter(Bl);n.length>0&&await IH(n,t)},async removeProjectScope(e){const t=vi(e);t&&await NH(t)},async keepProjectLocal(e){const t=vi(e);t&&await _m(t,"local-default")},async reassignProject(e){const t=vi(e);t&&await NC(t)},async forgetProject(e,t={}){const n=vi(e);n&&await PH(n,t)},async confirmProjectScope(e){const t=vi(e),n=Ir.get(e);!t||!n||await _m(t,n.scopeId,n.requiredGuardrailTokens)},cancelProjectScopeConfirmation(e){Ir.delete(e),Qe(),_t?.()},cancelProjectForgetConfirmation(e){wo.delete(e),Qe(),_t?.()},onSpaceSelectBlur(){yH()}};function ZH(e,t={}){_t=e,SC=t.onOpenTeamSetup,Et.clear(),ns.clear(),rs.clear(),is.clear(),os.clear(),as.clear(),Ir.clear(),ss.clear(),wo.clear(),Io=!1;const n=Ee("projectsStatusFilter");n&&n.options.length===0&&n.append(..._C.map(([o,s])=>new Option(s,o)));const r=()=>{er+=1,Kt=0,_t?.()};Ee("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),Ee("projectsPrevPage")?.addEventListener("click",()=>{er+=1,Kt=Math.max(0,Kt-ts),_t?.()}),Ee("projectsNextPage")?.addEventListener("click",()=>{er+=1,Kt+=ts,_t?.()});const i=Ee("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Et.size!==0&&Zo({mode:"project-add",projectIds:[...Et].sort()})})),gi()}function Cm(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 eV(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 tV(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Cm(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("claude_command"))throw R;const k=r.claude_command;o=Array.isArray(k)?k.filter(N=>typeof N=="string").map(N=>N.trim()).filter(N=>N.length>0):[]}let s=[];try{s=Cm(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("codex_command"))throw R;const k=r.codex_command;s=Array.isArray(k)?k.filter(N=>typeof N=="string").map(N=>N.trim()).filter(N=>N.length>0):[]}let c=[];try{c=Cm(t.observerAuthCommand,{label:"observer auth command"})}catch(R){if(!i||n.has("observer_auth_command"))throw R;const k=r.observer_auth_command;c=Array.isArray(k)?k.filter(N=>typeof N=="string"):[]}let l={};try{l=eV(t.observerHeaders)}catch(R){if(!i||n.has("observer_headers"))throw R;const k=r.observer_headers;k&&typeof k=="object"&&!Array.isArray(k)&&Object.entries(k).forEach(([N,$])=>{typeof N=="string"&&N.trim()&&typeof $=="string"&&(l[N]=$)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),f=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),g=d===""?"":Number(d),b=u===""?"":Number(u),v=p===""?"":Number(p),y=f===""?"":Number(f),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(p!==""&&(typeof v!="number"||!Number.isFinite(v)||v<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof y!="number"||!Number.isFinite(y)||y<=0||!Number.isInteger(y)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(S)||S<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:ct(t.observerProvider),observer_model:ct(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:ct(t.observerSimpleModel),observer_simple_temperature:b,observer_reasoning_effort:ct(t.observerReasoningEffort),observer_reasoning_summary:ct(t.observerReasoningSummary),observer_rich_model:ct(t.observerRichModel),observer_rich_temperature:v,observer_rich_reasoning_effort:ct(t.observerRichReasoningEffort),observer_rich_reasoning_summary:ct(t.observerRichReasoningSummary),observer_rich_max_output_tokens:y,observer_runtime:ct(t.observerRuntime||"api_http")||"api_http",observer_auth_source:ct(t.observerAuthSource||"auto")||"auto",observer_auth_file:ct(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s: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:ct(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:ct(t.syncCoordinatorUrl),sync_coordinator_group:ct(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function nV(e){return e.resolved_observer_runtime||Pe(Ce(e.config,e.effective,"observer_runtime"))||"api_http"}function rV(e){const t=e.config||{},n=e.effective||{},r=Ce(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,f])=>typeof p=="string"&&p.trim()&&typeof f=="string")):{},o=Ce(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=Ce(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ce(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Pe(Ce(t,n,"observer_provider")),observerModel:Pe(Ce(t,n,"observer_model")),observerTierRoutingEnabled:Nl(Ce(t,n,"observer_tier_routing_enabled")),observerSimpleModel:Pe(Ce(t,n,"observer_simple_model")),observerSimpleTemperature:Pe(Ce(t,n,"observer_simple_temperature")),observerReasoningEffort:Pe(Ce(t,n,"observer_reasoning_effort")),observerReasoningSummary:Pe(Ce(t,n,"observer_reasoning_summary")),observerRichModel:Pe(Ce(t,n,"observer_rich_model")),observerRichTemperature:Pe(Ce(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Pe(Ce(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Pe(Ce(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Pe(Ce(t,n,"observer_rich_max_output_tokens")),observerRuntime:nV(e),observerAuthSource:Pe(Ce(t,n,"observer_auth_source"))||"auto",observerAuthFile:Pe(Ce(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Pe(Ce(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Pe(Ce(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Pe(Ce(t,n,"observer_max_chars")),packObservationLimit:Pe(Ce(t,n,"pack_observation_limit")),packSessionLimit:Pe(Ce(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Pe(Ce(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Nl(Ce(t,n,"sync_enabled")),syncHost:Pe(Ce(t,n,"sync_host")),syncPort:Pe(Ce(t,n,"sync_port")),syncInterval:Pe(Ce(t,n,"sync_interval_s")),syncMdns:Nl(Ce(t,n,"sync_mdns")),syncCoordinatorUrl:Pe(Ce(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Pe(Ce(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Pe(Ce(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Pe(Ce(t,n,"sync_coordinator_presence_ttl_s"))}}function iV(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection now lives in Processing.";const n=oU(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),ct(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Qn(t,r))?"Env override":n.source}: ${n.model}`}function oV(e){return e.observerTierRoutingEnabled?"On: codemem routes simpler batches to Luna and richer batches to Terra with medium reasoning by default. Official OpenAI and OAuth Codex consumer requests always use Responses. The observer_openai_use_responses=false compatibility setting selects chat completions only for an explicitly configured custom OpenAI-compatible base URL. Sidecar runtimes route both tiers through their local CLI.":"Off: codemem uses the base observer settings from the Connection tab for all batches. Explicit user settings always win over built-in routing defaults."}function aV(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function sV(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Processing controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function cV(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while the Processing tab owns simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-5.4-mini` for Direct API (including pi-derived API-key providers), `gpt-5.1-codex-mini` for Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function lV(e){return!e}function dV(e,t,n){return t.has(e)||n.has(e)}function uV(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var re={previouslyFocused:null,baseline:{},effectiveConfig:{},resolvedObserverRuntime:null,observerRuntimeByAuthSource:{},envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,hideTooltip:null},Sn=uc({open:!1,activeTab:"observer",dirty:!1,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...Yq}},showAdvanced:tU()});function xt(){return Sn.value}function ps(e){Sn.value={...Sn.value,...e}}function pV(){re.hideTooltip?.()}function yi(e){ps({renderState:{...Sn.value.renderState,...e}})}function fV(e){yi({values:{...Sn.value.renderState.values,...e}})}function $C(e){ps({activeTab:["observer","queue","sync"].includes(e)?e:"observer"})}function Hl(e){ps({dirty:e})}function Vl(e){ps({open:e})}function mV(e){nU(e),ps({showAdvanced:e})}function MC(){return xt().open}function hV(e){return dV(e,re.protectedKeys,Jq)}function FC(e={}){return tV({values:xt().renderState.values,touchedKeys:re.touchedKeys,baseline:re.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors})}function gV(e){const t=_.feedProcessingStatus,n=vV(e);_.feedProcessingStatus=n,(t.kind!==n.kind||t.kind==="pending"&&n.kind==="pending"&&t.count!==n.count)&&wn(!0),yi({observerStatus:e&&typeof e=="object"?e:null})}function vV(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 yV(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. Runtime behavior may apply automatic provider defaults. Restart-dependent changes are labeled below.":"Effective values are unavailable. Reload Settings; if this persists, restart the viewer and inspect its configuration."}function bV(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=rV(t);re.envOverrides=i,re.effectiveConfig={...r,...t.effective},re.resolvedObserverRuntime=t.resolved_observer_runtime??null,re.observerRuntimeByAuthSource=t.observer_runtime_by_auth_source??{},re.protectedKeys=new Set(o),_.configDefaults=n,_.configPath=t.path||"",re.touchedKeys=new Set,yi({effectiveText:yV(t.effective,Object.keys(i).length>0),overridesVisible:Object.keys(i).length>0,pathText:_.configPath?`Config path: ${_.configPath}`:"Config path: n/a",providers:rU(t.providers),statusText:"No unsaved changes",values:s});try{const c=FC({allowUntouchedParseErrors:!0});re.baseline=sU(c,r,i)}catch{re.baseline={}}Hl(!1)}async function _V(e={}){if(xt().open)return;const[t,n]=await Promise.allSettled([PI(e),NI(e)]);e.signal?.aborted||(t.status==="fulfilled"&&bV(t.value),gV(n.status==="fulfilled"?n.value:null))}function wV({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function SV({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=e.available_credentials||{},i=e.latest_failure,o=Object.entries(r).filter(([,s])=>s&&typeof s=="object");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[n?a(H,{children:[a("div",{className:"status-label",children:"Active observer"}),a("div",{className:"status-active",children:[String(n.provider||"unknown")," → ",String(n.model||"")," via"," ",Qq(n.auth?.method||"none")," ",a("span",{"aria-label":n.auth?.token_present===!0?"token present":"token missing",className:n.auth?.token_present===!0?"cred-ok":"cred-none",role:"img",children:a("i",{"aria-hidden":"true","data-lucide":n.auth?.token_present===!0?"check":"x"})})]})]}):a(H,{children:[a("div",{className:"status-label",children:"Observer status"}),a("div",{className:"status-active",children:"Not yet initialized (waiting for first session)"})]}),o.length?a(H,{children:[a("div",{className:"status-label",children:"Available credentials"}),a("div",{children:o.map(([s,c],l)=>{const d=c,u=Object.values(d).some(Boolean);return a("span",{className:"status-cred",children:[l>0?" · ":null,a("span",{"aria-label":u?"credential available":"no credential",className:u?"cred-ok":"cred-none",role:"img",children:u?a("i",{"aria-hidden":"true","data-lucide":"check"}):"–"})," ",String(s),": ",Xq(d)]},s)})})]}):null,i&&typeof i=="object"?a(H,{children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue",children:[a("div",{className:"status-issue-message",children:typeof i.error_message=="string"&&i.error_message.trim()?i.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof i.observer_provider=="string"?i.observer_provider.trim():"",typeof i.observer_model=="string"&&i.observer_model.trim()?`→ ${i.observer_model.trim()}`:"",typeof i.observer_runtime=="string"&&i.observer_runtime.trim()?`(${i.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${Zq(i.updated_at)}`,typeof i.attempt_count=="number"&&Number.isFinite(i.attempt_count)?`Attempts ${i.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof i.impact=="string"&&i.impact.trim()?a("div",{className:"status-issue-impact",children:i.impact.trim()}):null,a(wV,{onOpenDiagnostics:t})]})]}):null]})}function BC(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 fs(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function CV(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 RV(){const e=tt("settingsModal");(CV(e)[0]||e)?.focus()}function IV(){const[e,t]=A({anchor:null,content:"",visible:!1}),n=D(null);return q(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},o=u=>{const p=fs(u.target);p&&r(p)},s=u=>{const p=fs(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=fs(u.target);p&&r(p)},l=u=>{fs(u.target)&&i()},d=u=>{const p=fs(u.target);p&&(u.preventDefault(),t(f=>{if(f.anchor===p&&f.visible)return{anchor:null,content:"",visible:!1};const m=p.dataset.tooltip?.trim()||"";return m?{anchor:p,content:m,visible:!0}:f}))};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),ot(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&BC(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),q(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&BC(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:_e(()=>typeof document>"u"?null:un(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function kV({DialogContent:e,onClose:t}){const{open:n}=Sn.value,{tooltipPortal:r,setTooltip:i}=IV();q(()=>{const s=()=>i({anchor:null,content:"",visible:!1});return re.hideTooltip=s,()=>{re.hideTooltip===s&&(re.hideTooltip=null)}},[]),q(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const o=ne(()=>{re.startPolling&&re.refresh&&t(re.startPolling,re.refresh)},[t]);return a(H,{children:[a(jn,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:s=>{s.preventDefault()},onOpenAutoFocus:s=>{s.preventDefault(),RV()},onOpenChange:s=>{if(s){Vl(!0);return}o()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),r]})}function qC(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 Rm(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 UC(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 Cn(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 NV(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 PV=new Set(["observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"]);function Kl(e){return e==="claude_sidecar"||e==="codex_sidecar"}var TV=Object.fromEntries([...["observerProvider","observerModel","observerRuntime","observerMaxChars","observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"].map(qC),...["observerTierRoutingEnabled","observerSimpleModel","observerSimpleTemperature","observerReasoningEffort","observerReasoningSummary","observerRichModel","observerRichTemperature","observerRichReasoningEffort","observerRichReasoningSummary","observerRichMaxOutputTokens"].map(Rm),UC("packObservationLimit"),UC("packSessionLimit"),{controlId:"rawEventsSweeperIntervalS",existingData:"Processed events stay unchanged; no backfill runs.",scope:"Background queue on this viewer",stage:"Queue processing",timing:"Immediately after save"},Cn("syncEnabled","Future sync cycles on this device"),Cn("syncInterval","Future sync cycles on this device"),Cn("syncHost","Incoming peer connections to this device"),Cn("syncPort","Incoming peer connections to this device"),Cn("syncMdns","Advertise this device on the local network; this does not scan for peers"),Cn("syncCoordinatorGroup","Fallback coordinator discovery when no coordinator group list is configured"),Cn("syncCoordinatorTimeout","Future coordinator requests"),Cn("syncCoordinatorPresenceTtl","Future coordinator presence checks")].map(e=>[e.controlId,e]));function Im(e,t={}){let n=TV[e];if(!n)return;const r=AV(t.observerRuntime);if(PV.has(e)&&Kl(r))return NV(e);if(n=xV(e,r)??n,n.scope==="No current effect")return n;const i=tm[e],o=i?re.envOverrides[i]:void 0;return typeof o!="string"||!o.trim()?n:{...n,timing:`After removing ${o.trim()} and restarting the viewer`}}function AV(e){const t=re.envOverrides.observer_runtime,n=bi("observerRuntime",e),r=re.touchedKeys.has("observer_runtime")&&n!==re.baseline.observer_runtime;if(t||!r){const o=EV();if(o)return o;if(re.resolvedObserverRuntime)return re.resolvedObserverRuntime}const i=String(n??"").trim().toLowerCase();return Kl(i)?i:"api_http"}function EV(){if(!re.touchedKeys.has("observer_auth_source"))return;const e=String(bi("observerAuthSource"));return re.observerRuntimeByAuthSource[e]}function bi(e,t){const n=tm[e];return n&&re.envOverrides[n]?re.effectiveConfig[n]:t??Sn.value.renderState.values[e]}function Po(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 xV(e,t){const n=Kl(t),r=String(bi("observerProvider"));if(e==="observerProvider"&&n)return Po(e,"Local Claude and Codex sessions select their own provider");if(e==="observerModel")return LV(t,r);const i=DV(bi("observerAuthSource"));if(e==="observerAuthTimeoutMs"&&!["auto","command"].includes(i))return Po(e,"Only command authentication uses this timeout");if(e==="observerAuthCacheTtlS"&&!["file","command"].includes(i))return Po(e,"Only explicit file or command authentication uses this cache");if(/Temperature$/.test(e))return $V(e,t,GC(e,r));if(/Reasoning(Effort|Summary)$/.test(e)||e==="observerRichMaxOutputTokens")return MV(e,n);if(e==="syncEnabled"&&!jV(bi(e)))return{...Cn(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{...Cn(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 DV(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return["auto","env","file","command","none"].includes(t)?t:"auto"}function jV(e){return typeof e=="boolean"?e:typeof e!="string"?!1:["1","true","yes","on"].includes(e.trim().toLowerCase())}function LV(e,t){const n="observerModel",r=bi("observerTierRoutingEnabled");return(r===!0||r==="true"||r==="1")&&OV(e,t)?Po(n,"Tier models or built-in tier defaults take precedence over the base model"):{...qC(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 GC(e,t){const n=e.startsWith("observerSimple")?"observer_simple_provider":"observer_rich_provider",r=String(re.effectiveConfig[n]??"").trim().toLowerCase(),i=t.trim().toLowerCase();return["openai","anthropic"].includes(r)?r:["openai","anthropic"].includes(i)?i:r||i}function OV(e,t){return e==="claude_sidecar"?!0:["observerSimpleModel","observerRichModel"].every(n=>String(bi(n)??"").trim()?!0:e==="codex_sidecar"?!1:["openai","anthropic"].includes(GC(n,t)))}function $V(e,t,n){return Kl(t)||n==="anthropic"?Po(e,"Anthropic and local Claude/Codex sessions do not send sampling temperature"):{...Rm(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 MV(e,t){if(t)return Po(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{...Rm(e),scope:n,timing:"After viewer restart, only when the effective request transport consumes this setting"}}function HC({controlId:e,existingData:t,scope:n,stage:r,timing:i}){let o=i;return i==="After viewer restart"?o="Restart required":i.startsWith("After removing ")?o=`Environment-controlled · ${i}`:n==="No current effect"||r==="Sidecar authentication"?o=`Inactive · ${i}`:i.startsWith("After viewer restart,")&&(o="Restart required · Conditional"),a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:o}),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 VC(e,t){for(const n of dn(e)){if(!n||typeof n!="object"||!("props"in n))continue;const r=n.props;if(typeof r.id=="string"&&Im(r.id,t))return r.id;const i=VC(r.children,t);if(i)return i}}function Te({children:e,className:t="field",hidden:n=!1,id:r}){const i={observerRuntime:Sn.value.renderState.values.observerRuntime},o=VC(e,i),s=o?Im(o,i):void 0;return a("div",{className:t,hidden:n,id:r,children:[e,s?a(HC,{...s}):null]})}function ms({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function km({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 FV({values:e,observerMaxCharsDefault:t,providerOptions:n,showAuthFile:r,showAuthCommand:i,hiddenUnlessAdvanced:o,onTextInput:s,onSelectValueChange:c,getObserverModelLabel:l,getObserverModelTooltip:d,getObserverModelDescription:u,getObserverModelHint:p,protectedConfigHelp:f,observerStatusBannerSlot:m}){return a(H,{children:[a(km,{detail:`Set how codemem reaches your model provider and where it should look for credentials. Shared across ${xS()}.`,title:"Connection and credentials"}),m,a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Use auto for recommended defaults.",type:"button",children:"?"})]}),a(Wn,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:c("observerProvider"),options:[{label:"auto (default)",value:""},...n],placeholder:"auto (default)",triggerClassName:"settings-select-trigger",value:e.observerProvider,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to pin a specific provider. Pi setup can derive Direct API provider/model from API-key providers only."})]}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:l()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":d(),type:"button",children:"?"})]}),a(be,{id:"observerModel",onInput:s("observerModel"),placeholder:"leave empty for default",value:e.observerModel}),a("div",{className:"small",children:u()}),a("div",{className:"small",id:"observerModelHint",children:p()})]}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Direct API uses provider credentials, including cheap-model-first settings derived from pi API-key providers. Local sessions use the selected Claude or Codex CLI login.",type:"button",children:"?"})]}),a(Wn,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:c("observerRuntime"),options:[{label:"Direct API (default)",value:"api_http"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}],triggerClassName:"settings-select-trigger",value:e.observerRuntime,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Switch between provider API credentials (OpenCode, Claude, Codex, pi) and local Claude or Codex CLI auth."})]}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(so,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:f("codex_command")})]}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(so,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:f("claude_command")})]}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(be,{id:"observerMaxChars",min:"1",onInput:s("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:t?`Default: ${t}`:""})]})]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Authentication"}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Authentication method"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(Wn,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:c("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use `auto` unless you need to force a file or command-based token source."})]}),a(Te,{hidden:!r,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:f("observer_auth_file")})]}),a(Te,{hidden:!i,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(so,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:f("observer_auth_command")})]}),a("div",{className:"small",hidden:!i,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(ms,{hidden:o(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(be,{id:"observerAuthTimeoutMs",min:"1",onInput:s("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(be,{id:"observerAuthCacheTtlS",min:"0",onInput:s("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(Te,{className:"field settings-advanced",hidden:o(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(so,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:f("observer_headers")})]})]})]})}function zl({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`,l=Im(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(io,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"}),l?a(HC,{...l}):null]})}function BV({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r,onSwitchInput:i,getTieredRoutingHelperText:o}){return a(H,{children:[a(km,{detail:"Control how often codemem processes queued work and, if needed, how it routes lighter vs richer model requests.",title:"Processing and routing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(Te,{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",children:[a("h3",{className:"settings-group-title",children:"Tiered observer routing"}),a(zl,{checked:e.observerTierRoutingEnabled,className:"field",id:"observerTierRoutingEnabled",label:"Enable tiered routing",onCheckedChange:i("observerTierRoutingEnabled")}),a("div",{className:"small",children:o()}),a(ms,{hidden:!t||n(),children:"These advanced routing values are only useful when you are tuning model cost, latency, or output quality for a known workload. If a selected path cannot honor the requested tier settings, codemem falls back visibly instead of silently pretending it worked."}),a("div",{hidden:!t,children:[a("h4",{children:"Simple tier"}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerSimpleModel",children:"Model"}),a("button",{"aria-label":"About simple tier model",className:"help-icon","data-tooltip":"Used for lighter replay batches. Leave blank to keep codemem's routing defaults. Explicit simple-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(be,{id:"observerSimpleModel",onInput:r("observerSimpleModel"),placeholder:"leave empty for default",value:e.observerSimpleModel}),a("div",{className:"small",children:"Used when a batch falls below rich-routing thresholds."})]}),a(Te,{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(Te,{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(Te,{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",{hidden:!t,children:[a("h4",{children:"Rich tier"}),a(Te,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRichModel",children:"Model"}),a("button",{"aria-label":"About rich tier model",className:"help-icon","data-tooltip":"Used for larger or more complex replay batches. Leave blank to keep codemem's rich-tier defaults. Explicit rich-tier values override the built-in defaults.",type:"button",children:"?"})]}),a(be,{id:"observerRichModel",onInput:r("observerRichModel"),placeholder:"leave empty for default",value:e.observerRichModel}),a("div",{className:"small",children:"Used when routing detects a richer replay batch."})]}),a(Te,{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(Te,{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(Te,{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(Te,{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(ms,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(Te,{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(Te,{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 qV({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(H,{children:[a(km,{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(zl,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a(Te,{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(Te,{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(Te,{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(zl,{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(Te,{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(ms,{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(Te,{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(Te,{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 UV({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,onClose:o,onSave:s,onActiveTabChange:c,onAdvancedToggle:l,onShowGettingStarted:d,observerStatusBannerSlot:u}){const p=!i||r.isSaving;return a("form",{className:"modal-card",onKeyDown:f=>Ia(f,{onSubmit:s,disabled:p}),onSubmit:f=>f.preventDefault(),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(qr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:o})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(zl,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:l}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(ms,{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(bp,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:c,tabs:Wq,triggerClassName:"settings-tab",value:t,children:[a(Jr,{className:"settings-panel",forceMount:!0,value:"observer",children:a(FV,{...e,observerStatusBannerSlot:u})}),a(Jr,{className:"settings-panel",forceMount:!0,value:"queue",children:a(BV,{...e})}),a(Jr,{className:"settings-panel",forceMount:!0,value:"sync",children:a(qV,{...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",{className:"small",id:"settingsStatus",children:r.statusText}),a("button",{className:"settings-link-button",onClick:d,type:"button",children:"Show getting started"})]}),a("button",{className:"settings-save","data-primary-action":"true",disabled:p,id:"settingsSave",onClick:s,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function GV(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};return Object.entries(t).forEach(([c,l])=>{o(c)||Qn(r,c)&&!i.has(c)||iU(l,n[c])||(s[c]=l)}),s}function HV(e){const t=s=>{const c=tm[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function VV(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=>nm(String(p))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(p=>nm(String(p))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(p=>nm(String(p))):[],s=Array.isArray(n.warnings)?n.warnings.filter(p=>typeof p=="string"&&p.trim().length>0):[],c=Array.isArray(n.manual_actions)?n.manual_actions:[],l=n.sync&&typeof n.sync=="object"?n.sync:{},d=[];r.length&&d.push(`Applied now: ${kl(r)}.`),i.length&&d.push(`Live settings updated: ${kl(i)}.`),l.attempted&&typeof l.message=="string"&&l.message?d.push(`Sync: ${l.message}.`):Array.isArray(l.affected_keys)&&l.affected_keys.length&&typeof l.reason=="string"&&l.reason&&d.push(`Sync: ${l.reason}.`),o.length&&d.push(`Restart required for ${kl(o)}. Run: codemem serve restart`),s.forEach(p=>{d.push(p)}),c.forEach(p=>{p&&typeof p.command=="string"&&p.command.trim()&&d.push(`If needed: ${p.command}.`)}),d.length||d.push("Saved.");const u=o.length>0||s.length>0||l.ok===!1;return{message:d.join(" "),type:u?"warning":"success"}}var KV=()=>iV(xt().renderState.values,re.envOverrides),zV=()=>oV(xt().renderState.values),WV=()=>aV(xt().renderState.values),JV=()=>sV(xt().renderState.values),YV=()=>cV(xt().renderState.values),QV=()=>lV(xt().showAdvanced),{onTextInput:XV,onSelectValueChange:ZV,onSwitchInput:eK}=HV({getTouchedKeys:()=>re.touchedKeys,getValues:()=>xt().renderState.values,updateFormState:fV,setDirty:e=>Hl(e)});function tK(){const e=Sn.value.renderState.observerStatus;return a(SV,{status:e,onOpenDiagnostics:rK})}function nK(){!re.startPolling||!re.refresh||(To(re.startPolling,re.refresh),!xt().open&&(OM(),document.getElementById("tabBtn-feed")?.click(),MM()))}function rK(e){if(!re.startPolling||!re.refresh||(To(re.startPolling,re.refresh),xt().open))return;const t=bc("settingsButton");queueMicrotask(()=>dr({...e,trigger:t}))}function iK(){const e=Sn.value,t=e.renderState.values,n=String(_.configDefaults?.observer_max_chars||""),r=t.observerAuthSource==="file",i=t.observerAuthSource==="command",o=t.observerTierRoutingEnabled,s={values:t,observerMaxCharsDefault:n,providerOptions:Array.from(new Set(e.renderState.providers.concat(t.observerProvider?[t.observerProvider]:[]))).sort((c,l)=>c.localeCompare(l)).map(c=>({label:c,value:c})),showAuthFile:r,showAuthCommand:i,showTieredRouting:o,hiddenUnlessAdvanced:QV,onTextInput:XV,onSelectValueChange:ZV,onSwitchInput:eK,getObserverModelLabel:WV,getObserverModelTooltip:JV,getObserverModelDescription:YV,getObserverModelHint:KV,getTieredRoutingHelperText:zV,protectedConfigHelp:uV};return a(UV,{panelProps:s,activeTab:e.activeTab,showAdvanced:e.showAdvanced,renderState:e.renderState,settingsDirty:e.dirty,onClose:()=>{re.startPolling&&re.refresh&&To(re.startPolling,re.refresh)},onSave:()=>{re.startPolling&&re.refresh&&sK(re.startPolling,re.refresh)},onActiveTabChange:$C,onAdvancedToggle:mV,onShowGettingStarted:nK,observerStatusBannerSlot:a(tK,{})})}function oK(){return a(kV,{DialogContent:iK,onClose:To})}function aK(){const e=tt("settingsDialogMount");e&&ke(a(oK,{}),e)}function KC(){tt("settingsDialogMount")&&(re.shellMounted||(aK(),re.shellMounted=!0))}function zC(e){ai("settings-health"),re.shellMounted||KC(),Vl(!0),re.previouslyFocused=document.activeElement,e()}function To(e,t){if(xt().dirty&&!globalThis.confirm("Discard unsaved changes?")){Vl(!0);return}Vl(!1),pV(),(re.previouslyFocused&&typeof re.previouslyFocused.focus=="function"?re.previouslyFocused:bc("settingsButton"))?.focus(),re.previouslyFocused=null,re.touchedKeys=new Set,e(),t()}async function sK(e,t){if(!xt().renderState.isSaving){yi({isSaving:!0,statusText:"Saving changes…"});try{const n=FC({allowUntouchedParseErrors:!0}),r=GV({current:n,baseline:re.baseline,envOverrides:re.envOverrides,touchedKeys:re.touchedKeys,isProtected:hV});if(Object.keys(r).length===0){yi({isSaving:!1,statusText:"No unsaved changes"}),Hl(!1),To(e,t);return}const i=await TI(r),o=VV(i);yi({isSaving:!1,statusText:"Saved changes"}),Hl(!1),To(e,t),Y(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";yi({isSaving:!1,statusText:`Save failed: ${r}`})}}}function cK(e,t,n){re.startPolling=t,re.refresh=n,KC(),bc("settingsButton")?.addEventListener("click",()=>zC(e))}function lK(e){e.dataset.syncRenderRoot="preact"}function dK(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function lt(e,t){lK(e),ke(t,e)}function Ao(e){e.dataset.syncRenderRoot==="preact"&&ke(null,e)}function uK(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 pK(e){return typeof e=="object"&&e!==null}function fK(e,t){return _.pairingCommandRaw="",{payloadText:e,hintText:t}}function mK(e){if(!pK(e))return fK("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return _.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function hK(){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 gK(){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 vK(){const e=_.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function yK(){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 bK(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 _K({items:e}){return a(H,{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 wK({attempts:e,note:t}){return a(H,{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 WC({text:e}){return a(H,{children:e})}function SK({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function CK(e,t){if(!t.length){Ao(e);return}lt(e,a(_K,{items:t}))}function RK(e,t,n){if(!t.length){Ao(e);return}lt(e,a(wK,{attempts:t,note:n}))}function _i(e,t){lt(e,a(SK,{...t}))}function JC(e,t,n){lt(e,a(WC,{text:n.payloadText})),t&<(t,a(WC,{text:n.hintText}))}function YC({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=D(null),p=D(null),f=D(!1);ot(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),q(()=>{if(!e){f.current=!1;return}f.current||(f.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(ba,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(ya,{open:e,onOpenChange:t,children:[a(kp,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?un(m,l):m]})}function IK({open:e,onOpenChange:t}){return a(YC,{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(so,{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 kK({contentHost:e,open:t,onOpenChange:n}){return a(YC,{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 NK(e,t){lt(e,a(IK,{...t}))}function PK(e,t){lt(e,a(kK,{...t}))}function ce(e){return String(e??"").trim()}function TK(e){return ce(e).replace(/\s+/g," ").toLowerCase()}function AK(e){const t=ce(e);return t?t.slice(0,8):"Unnamed device"}function QC(e){return ce(e?.last_error).toLowerCase()}function XC(e){return e.includes("401")&&e.includes("unauthorized")}function ZC(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var EK={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function eR(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 xK(e){const t=eR(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 tR(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=OK(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=>nR(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=>nR(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 nR(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 DK(n)?"trust":jK(n)?"scope":null}function DK(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function jK(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function LK(e){const t=ce(e?.reason);return EK[t]??(t.replaceAll("_"," ")||"sync filters")}function OK(e){const t=new Map;for(const n of e){const r=LK(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 rR(e){const t=ce(e.localName);if(t)return t;const n=ce(e.coordinatorName);return n||AK(ce(e.deviceId))}function $K(e){const t=ce(e.localName),n=ce(e.coordinatorName);return t||n?!1:!!ce(e.deviceId)}function MK(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function hs(e){const t=ce(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=QC(e);return XC(n)?"needs-repair":ZC(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function Eo(e){const t=e?.status||{},n=ce(t.peer_state),r=QC(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}:XC(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}:ZC(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 FK={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 BK(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:FK[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 iR(e){return Array.isArray(e)?e.map(t=>ce(t)).filter(t=>!!t):[]}function oR(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 Wl(e,t){return e?e.replaceAll("_"," "):t}function qK(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=[Wl(ce(r.kind),"user"),Wl(ce(r.authority_type),"local"),`${Wl(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 aR(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=Wl(ce(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(f=>!!f).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var UK=["personal","private","home","mine","me"],GK=["oss","open source","opensource","community","public"],HK=["work","client"],VK=["local","legacy","review"];function KK(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>ce(t)??"").join(" ").toLowerCase()}function zK(e){return[e.scope_id,e.label,e.kind].map(t=>ce(t)??"").join(" ").toLowerCase()}function sR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nm(e,t){const n=KK(e);return t.some(r=>{const i=sR(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function cR(e){return Nm(e,UK)||Nm(e,GK)}function WK(e){const t=zK(e);return VK.some(n=>{const r=sR(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function JK(e){return!cR(e)&&(!WK(e)||Nm(e,HK))}function YK(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(cR),r=t.some(JK);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 QK(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function XK(e){const t=iR(e?.effective_include),n=iR(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${oR(t,"all projects")}`,o=`Exclude filter: ${oR(n,"no exclusions")}`,s=QK(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 ZK(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=ce(n?.display_name),i=ce(n?.actor_id),o=TK(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 lR(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 ez=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),tz=new Set(["pending","verifying","waiting"]);function nz(e){return(Array.isArray(e?.groups)?e.groups.map(t=>ce(t)).filter(Boolean):[]).join(", ")||"none"}function rz(e){return ce(e?.projects?.[0]?.display_name)||"the shared Project"}function iz(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=Eo(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function oz(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&Eo(n).state==="mutual-trust"&&!aR(n).rows.some(r=>r.status==="pending"))}function az(e){return e.some(t=>ce(t.status?.peer_state)==="online"&&Eo(t).state==="mutual-trust")}function sz(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=ce(n.status?.peer_state),i=Eo(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function cz(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 lz(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:nz(e.coordinator)}}function dz(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 uz(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 pz(e){const t=e.operations.find(o=>{const s=o.lifecycle?.state;return s!==void 0&&ez.has(s)}),n=e.reconciliationItems.find(o=>{const s=o.state;return s!==void 0&&tz.has(s)});if(!t&&!n)return null;const r=t?rz(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:uz(t,r)}}function fz(e){return cz(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."}:iz(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 mz(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 hz(e){return sz(e.peers,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${e.label}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:e.coordinator?.sync_enabled===!0&&oz(e.peers,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${e.label}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:az(e.peers)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${e.label}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${e.label}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function dR(e){const t=lz(e);return dz(t)??pz(t)??fz(t)??mz(t)??hz(t)}function gz(e){return e.discovered?.stale?e.peer?hs(e.peer)!=="connected":!0:!1}function uR(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 vz(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 yz(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 bz(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 _z(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 wz(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 Sz(e,t){const n=ce(e.discovered?.fingerprint),r=ce(e.peer?.fingerprint);return!e.peer||!n||!r||n===r?null:uR({id:e.deviceId,name:t,title:`${t} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."})}function Cz(e,t){if(!e.peer)return[];const n=[],r=hs(e.peer),i=Eo(e.peer);return r==="needs-repair"&&n.push(uR({id:e.deviceId,name:t,title:i.state==="needs-repairing"?`${t} needs re-pairing`:`${t} needs review`,summary:i.description||ce(e.peer.last_error)||"Sync needs review."})),i.state==="trusted-by-you"&&n.push(vz({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."})),$K({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId})&&n.push(yz({id:e.deviceId,name:t,summary:"Give this device a friendly name so it is easier to recognize later."})),n}function Rz(e){const t=rR({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId}),n=Sz(e,t);return n?[n]:Cz(e,t)}function Iz(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=_z(n,r),o=e.duplicatePersonDecisions??{},s=ZK(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[...wz(s),...i.flatMap(Rz)];return{primaryStatus:dR({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=>gz(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var pR={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 Pr(e){const t=document.getElementById(e);t&&t.remove()}var fR=!1;function kz(e){fR=e}var Pm=!1;function Nz(e){Pm=e}var Pz=new Set,Tm=new Set,Am=new Set,mR="codemem-sync-duplicate-person-decisions";function Tz(e){const t=String(e||"").trim();t&&(Tm.add(t),Am.add(t),Pz.add(t))}function Em(e){const t=String(e||"").trim();return!!t&&Tm.has(t)}function Az(e){const t=String(e||"").trim();t&&Tm.delete(t)}function Ez(e){const t=String(e||"").trim();return!t||!Am.has(t)?!1:(Am.delete(t),!0)}function xm(){try{const e=localStorage.getItem(mR);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function hR(e){try{localStorage.setItem(mR,JSON.stringify(e))}catch{}}function gR(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function xz(){return xm()}function Dz(e,t){const n=gR(e);if(!n)return;const r=xm();r[n]=t,hR(r)}function jz(e){const t=gR(e);if(!t)return;const n=xm();delete n[t],hR(n)}function vR(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function yR(e){const t=String(e||"");return t?vR(t):""}function Lz(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function Oz(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function Jl(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 Dm(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":Jl(e)}function $z(e){return(Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function Mz(){return lR({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}).visibleActors}function bR(e){return Mz().filter(t=>String(t?.actor_id||"")!==e)}function Fz(e,t){const n=bR(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${Dm(n)}. Assigned devices move now; existing memories keep their current provenance.`}function jm(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=yc("div","sync-action"),i=yc("div","sync-action-text");i.textContent=n.label,i.appendChild(yc("span","sync-action-command",n.command));const o=yc("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Ji(n.command,o)),r.append(i,o),e.appendChild(r)})}}function _R(e,t){return t&&e.error_redacted===!0}function Bz(e){return e?{action:t=>dr({severity:"error",subsystem:"sync",trigger:t})}:{}}function wR(){const e=document.getElementById("syncAttempts");if(!e)return;const t=_.lastSyncAttempts,n=String(_.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){_i(e,vK());return}const r=bK(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(_.lastSyncPeers)?_.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",p=[],f=ha();if(u&&o.error){const m=String(o.error);p.push(f?vR(m):m),_R(o,f)&&p.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&p.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!f&&o.address&&p.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:p.join(" · "),startedAt:s?Vr(s):"",...Bz(u),..._R(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});RK(e,i,r)}function qz(){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&&_i(t,gK()),n&&_i(n,yK()),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."),jm(i,[])}function xo(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function Uz(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=xo(n.would_remove),o=xo(n.ambiguous),s=xo(r.applied),c=xo(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 Gz(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?`${na(Ui(e.lastSync))} ago`:"never"},{label:"Last peer ping",value:e.lastPing?`${na(Ui(e.lastPing))} ago`:"never"},{label:"Retention",value:t}]}function SR(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Pr("syncDiagSkeleton");const r=_.lastSyncStatus;if(!r){_i(e,hK()),jm(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||uK(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),f=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),g=r.retention||{},b=r.cleanup_diagnostics,v=b?.stale_peer_rows??{},y=xo(v.would_remove),S=xo(v.ambiguous),w=g.enabled===!0,R=Number(g.last_deleted_ops||0),k=g.last_run_at||null,N=String(g.last_error||""),$={needs_attention:"Needs attention","offline-peers":"Offline peers",rebootstrapping:"Rebootstrapping"}[m]??ay(m),E=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,T=!E&&F===0;if(t){let G;E?G=["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:T?G=["Advanced sync is ready but idle","Pair another device from Devices, then return here for live peer status and recent attempts"]:G=[`Advanced state: ${$}`,`Peers: ${F}`,c?`Last sync: ${na(Ui(c))} ago`:"Last sync: never"],m==="offline-peers"&&G.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&G.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&G.push(`Detail: ${f}`),w&&G.push(k?`Retention last ran ${na(Ui(k))} ago (approx oldest-first)`:"Retention enabled"),y>0?G.push(`${y.toLocaleString()} stale peer rows pending cleanup`):S>0&&G.push(`${S.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=G.join(" · ")}const M=E?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:Gz({daemonStateLabel:$,lastPing:l,lastSync:c,pending:p,retentionDeleted:R,retentionEnabled:w,retentionLastRunAt:k,syncNoPeers:T});!E&&!T&&(d||u)&&M.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!E&&!T&&s.seconds_since_last&&M.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!E&&!T&&o.seconds_since_last&&M.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!E&&w&&N&&M.push({label:N,value:"Retention"}),!E&&!T&&b&&M.push({label:"Cleanup",value:Uz(b)}),CK(e,M);const L=[];T||m==="offline-peers"||(m==="stopped"?(L.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),L.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?L.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?L.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(L.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),L.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!E&&!T&&p>0&&L.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!E&&S>0?L.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!E&&y>0&&L.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),jm(n,L)}var Hz="syncRedactMount",Vz="syncRedactLabel",CR=()=>{};function Kz(e){CR=e}var Lm=()=>{};function Om(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;PK(e,{contentHost:t,open:_.syncPairingOpen,onOpenChange:r=>{if(x0(r),Om(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&JC(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Lm()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=_.pairingCommandRaw;r&&await Ji(r,n)})}function $m(){Om();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;JC(e,t,mK(_.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!_.pairingCommandRaw)}function RR(){const e=document.getElementById(Hz);e&<(e,h(io,{"aria-labelledby":Vz,checked:ha(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{D0(t),RR(),Lm(),SR(),CR(),wR(),$m()},thumbClassName:"sync-redact-switch-thumb"}))}function zz(e){Lm=e,Om(),RR()}function Wz(e){e.classList.add("sync-shake"),e.addEventListener("animationend",()=>e.classList.remove("sync-shake"),{once:!0})}function wi(e,t){e.classList.add("sync-field-error");const n=e.parentElement?.querySelector(".sync-field-hint");n&&n.remove();const r=document.createElement("div");return r.className="sync-field-hint",r.textContent=t,e.insertAdjacentElement("afterend",r),Wz(e),e.addEventListener("input",()=>gs(e),{once:!0}),!1}function gs(e){e.classList.remove("sync-field-error");const t=e.parentElement?.querySelector(".sync-field-hint");t&&t.remove()}function ht(e,t){if(e instanceof Error){const n=e.message;return n.includes("fetch")||n.includes("network")||n.includes("Failed to fetch")?"Network error — check your connection and try again.":n}return t}var Si=new Map,Mm=null,Jz={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 Yz(e){const t=e instanceof Error?e.message:String(e);return Jz[t]??"Setup could not be retried. Review diagnostics for details."}function Qz(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 Xz(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Fm(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 Zz({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=A(!1),[c,l]=A(()=>Si.get(e.operation_id)??null),d=D(null),u=e.lifecycle.primary_action;q(()=>{Mm!==e.operation_id||!d.current||(Mm=null,d.current.focus())},[c?.message,e.operation_id]);async function p(b){s(!0);try{let v=b;if(!v&&n){const S=(await n(e.operation_id)).lifecycle.primary_action;S?.kind==="copy_invite"&&(v=S.invite_link)}if(!v)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(S=>navigator.clipboard.writeText(S)))(v);const y={message:"Invite copied.",tone:"success"};Si.set(e.operation_id,y),l(y)}catch(v){const y={message:v instanceof Error?v.message:"Invite could not be copied.",tone:"warning"};Si.set(e.operation_id,y),l(y)}finally{s(!1)}}async function f(){s(!0);try{const b=await t(e.operation_id),v=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"};Si.set(e.operation_id,v),Mm=e.operation_id,l(v),await r()}catch(b){const v={message:Yz(b),tone:"warning"};Si.set(e.operation_id,v),l(v),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const b=e.projects.map(v=>v.project_id?.trim()).filter(v=>!!v);if(b.length!==e.projects.length){const v={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};Si.set(e.operation_id,v),l(v);return}if(!tc(b,e.person.display_name)){const v={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};Si.set(e.operation_id,v),l(v)}}function g(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){f();return}m()}}return a("section",{"aria-label":`${Fm(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:Fm(e.lifecycle.state)}),a("ul",{"aria-label":`${Fm(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((b,v)=>a("li",{className:"peer-scope-chip",children:b.display_name},`${b.display_name}:${v}`))}),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 eW({operations:e,...t}){const n=e[0].person,r=Xz(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(Zz,{operation:i,...t},i.operation_id))]})}function tW(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:Qz(e.operations).map(t=>a(eW,{...e,operations:t},t[0].person.actor_id))})}function nW(e,t){lt(e,a(tW,{...t}))}function IR({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 rW(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 iW({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=Jl(e),c=$z(o),l=bR(o),d=l.map(L=>String(L.actor_id||"")).join("|"),[u,p]=A(s),[f,m]=A(!1),[g,b]=A("Rename"),[v,y]=A(!1),[S,w]=A("Merge into selected person"),[R,k]=A(""),[N,$]=A(!1);q(()=>{p(s),m(!1),b("Rename"),y(!1),w("Merge into selected person"),k(""),$(!1)},[o,c,t,s,d]);const E=l.length?Fz(R,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(L=>{const G=String(L.actor_id||"");return{label:L.is_local?Dm(L):Jl(L),value:G}})];async function T(){const L=u.trim();if(!L)return;m(!0),b("Saving…");let G=!1;try{await n(o,L),G=!0}catch{b("Retry rename")}finally{m(!1),G&&b("Rename")}}async function M(){if(!R)return;const L=l.find(V=>String(V.actor_id||"")===R);if(!L||!await bn({title:`Merge ${s} into ${Jl(L)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;y(!0),w("Merging…");let G=!1;try{await r(R,o),G=!0}catch{w("Retry merge")}finally{y(!1),G&&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:Dm(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?rW(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(H,{children:[a(be,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||v,type:"text",value:u,onInput:L=>p(L.currentTarget.value),onKeyDown:L=>Ia(L,{onSubmit:()=>{T()},disabled:f||v||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||v,onClick:()=>{T()},children:g}),a("button",{type:"button",className:"settings-button danger",disabled:f||v,onClick:async()=>{await bn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:f||v,onClick:()=>$(L=>!L),children:N?"Hide duplicate cleanup":"Show duplicate cleanup"}),N?a(H,{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(Wn,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:v||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:k,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:R,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:v||l.length===0||!R,onClick:()=>{M()},children:S})]}),a("div",{className:"peer-meta actor-merge-note",children:E})]}):null]})})]})}function oW({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(H,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(iW,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(IR,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function aW(e,t){lt(e,a(oW,{...t}))}function sW(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function cW(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${Vr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function lW({devices:e}){return a(H,{children:cW(e)})}function dW(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 uW(e){const t=sW(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),Ao(e.mount),Ao(e.meta);return}const n=t.map(dW),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(Wn,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),lt(e.meta,a(lW,{devices:t}))}function Tr({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function pW(){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 fW(e){switch(hs(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var Yl=null,kR=0,Bm=new Set;function NR(e){if(Yl!==e){Yl=e,kR+=1;for(const t of Bm)t(kR)}}function mW(){const[,e]=A(0);return q(()=>(Bm.add(e),()=>{Bm.delete(e)}),[]),Yl}var hW={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function PR(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 gW(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: ${PR(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: ${PR(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 vW(e){_.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function yW(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 bW(){window.location.hash="advanced/teams/administration"}function qm(e=_.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function _W({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=Eo(e),l=hW[MK(e)],d=e.status||{},u=qK(e),p=Em(i),f=p&&u.total===0,m=YK(e),g=BK(e),b=aR(e),v=e.project_scope||{},y=XK(v),S=Lz(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(le=>String(le)))):[],R=Number(e.address_count??0),k=Number.isFinite(R)&&R>0?R:0,N=w.length?w.map(le=>ha()?yR(le):le).join(" · "):k>0?`${k} ${k===1?"address":"addresses"} hidden`:"No addresses",$=_.lastDeviceIdentityInventory?.items.find(le=>le.deviceId===i||le.evidenceDeviceIds.includes(i)),E=gW($,String(e.actor_id||"")||null,_.lastSyncActors,_.deviceIdentityInventoryLoadError,_.lastDeviceIdentityInventory?.truncated===!0,_.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),T=String(d.last_ping_at||d.last_ping_at_utc||""),M=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,L=Ez(i),G=D(null),[V,z]=A(o),[O,C]=A(()=>_.syncPeerFeedbackById.get(i)??null),[x,B]=A(!1),[U,te]=A("Save name"),[ae,ee]=A(!1),[qe,fe]=A(!1),[$e,Ne]=A("Remove device");q(()=>{p&&u.total>0&&Az(i)},[u.total,i,p]),q(()=>{z(o),C(_.syncPeerFeedbackById.get(i)??null),B(!1),te("Save name"),ee(!1),fe(!1),Ne("Remove device")},[o,e.actor_id,i]),q(()=>{!L||!G.current||queueMicrotask(()=>G.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[L]);async function se(){if(!i)return;const le=V.trim();if(!le){const Ct={message:"Enter a friendly name for this device.",tone:"warning"};C(Ct),_.syncPeerFeedbackById.set(i,Ct),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}B(!0),te("Saving…");try{const Ct=await n(i,le);C(Ct),_.syncPeerFeedbackById.set(i,Ct),te("Save name")}catch{te("Retry")}finally{B(!1)}}async function we(){if(f){const le=qm();if(!await bn({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}ee(!0);try{const le=await r(e,S);C(le),le&&_.syncPeerFeedbackById.set(i,le)}finally{ee(!1)}}async function Q(){if(!i||!await bn({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;fe(!0),Ne("Removing…");let le=!1;try{await t(i,s),le=!0}catch{Ne("Retry remove")}finally{fe(!1),le&&Ne("Remove device")}}const ie=mW()===i&&i!=="",je=`device-drawer-${i||"unknown"}`,ue=fW(e),dt=F?`Sync: ${Vr(F)}`:"Sync: never",ye=qm(),Dt=`${ie?"Collapse":"Expand"} device ${o}`;return a(ya,{asChild:!0,open:ie,onOpenChange:le=>{le?NR(i):Yl===i&&NR(null)},children:a("div",{ref:G,className:"peer-card","data-peer-device-id":i||void 0,children:[a(kp,{asChild:!0,children:a("button",{"aria-label":Dt,className:"device-row-head device-row-head--trigger",type:"button",children:[a(tn,{state:ue}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),f?a("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,a("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),g.badgeLabel?a("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:g.badgeLabel}):null,m.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:m.badgeLabel}):null,e.discovered_via_group_id?a("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:dt}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(pW,{})})]})}),a(ba,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:je,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:ae,onClick:()=>{we()},title:S?void 0:"Address details are hidden; sync will target this device by ID.",children:ae?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(be,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:x,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:x,onClick:()=>{se()},children:U}),a("button",{type:"button",className:"settings-button danger",disabled:qe,onClick:()=>{Q()},children:$e})]}),a("div",{className:"peer-scope",children:[L?a("div",{className:"peer-meta",children:ye?"Review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad.":"A coordinator operator can review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad."}):f?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:N}),M?a("div",{className:"peer-meta",children:M}):null,a("div",{className:"peer-meta",children:[F?`Sync: ${Vr(F)}`:"Sync: never",T?`Ping: ${Vr(T)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(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:y.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 ",Vr(g.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:E.summary}),a("div",{className:"peer-meta",children:E.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:yW(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>vW($?.deviceId??i),children:E.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[y.statusLabel,". ",y.summary," ",y.note]}),ye?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:bW,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(Tr,{feedback:O})]})]})]})})}function wW(e){const t=_.syncPeersSectionFeedback,n=_.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(H,{children:[a(Tr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(_W,{peer:i,...e},o)})]}):a(H,{children:[a(Tr,{feedback:t}),a(IR,{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 SW(e,t){lt(e,a(wW,{...t}))}var Ar=async()=>{},Ql="";function Um(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function CW(e){Ar=e}function RW(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Pr("syncActorsSkeleton"),Um(!1);const n=lR({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),aW(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await sN(i,o),await Ar()},onMerge:async(i,o)=>{try{await Qh(i,o),Y("People combined. Assigned devices moved to the selected person."),await Ar()}catch(s){throw Y(ht(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await cN(i),Y("Person removed. Assigned devices have been unassigned."),await Ar()}catch(o){throw Y(ht(o,"Failed to remove person."),"warning"),o}}})}function IW(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");Um(!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&&_i(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function kW(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;nW(e,{operations:_.lastShareOperations,onAdvance:n=>Qk(n),onLoadOperation:n=>Yk(n),onReload:Ar});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=_.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":_.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function Gm(){const e=document.getElementById("syncPeers");if(!e)return;Pr("syncPeersSkeleton");const t=_.lastSyncPeers,n=Array.isArray(t)?t:[];Oz(_.syncPeersSectionFeedback,n)&&(_.syncPeersSectionFeedback=null),SW(e,{peers:n,onRename:async(r,i)=>{try{return await Oh(r,i),await Ar(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:ht(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await Xh({address:i,peerDeviceId:o||void 0}),c=tR(s);let l;c.ok?o&&Em(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${qm()?"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 Ar()}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:ht(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Lh(r);const o={message:`Removed peer ${i}.`,tone:"success"};return _.syncPeerFeedbackById.delete(r),_.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await Ar(),o}catch(o){return{message:ht(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function NW(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");Um(!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&&_i(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&&_i(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 TR(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(_.lastSyncLegacyDevices)?_.lastSyncLegacyDevices:[];uW({devices:r,meta:n,mount:t,onValueChange:i=>{i!==Ql&&(Ql=i,TR())},panel:e,value:Ql})}function PW(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Ia(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){wi(n,"Enter a name for the person.");return}gs(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await aN(i),Y("Person created."),n.value="",await e()}catch(o){Y(ht(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(Ql||"").trim();if(!i||!r||!await bn({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 lN(i),Y("Old device history attached to you."),await e()}catch(s){Y(ht(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function TW(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function Hm(e=TW()){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 AR=!1;function AW(){AR||(AR=!0,window.addEventListener("hashchange",()=>{Hm()}))}var Rn={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function EW(e){Rn.loadSyncData=e}var xW=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function DW(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=_.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 Vm(){const e=document.getElementById("syncAdminDisclosureMount");e&&NK(e,{open:fR,onOpenChange:t=>{kz(t),Vm(),Zl(),Km()}})}function ER(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function Km(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(_.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function Xl(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=_.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function Zl(){const e=document.getElementById("syncInvitePolicyMount");e&<(e,h(Wn,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==Rn.invitePolicy&&(Rn.invitePolicy=n,Zl())},options:xW,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:Rn.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function jW(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 LW(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 OW(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 $W(e){const t=e;if(t.type==="project_share")return OW(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 MW(e,t){Vm(),Zl();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),o=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),f=document.getElementById("syncProjectInviteReviewHeading"),m=document.getElementById("syncRecipientName"),g=document.getElementById("syncRecipientDeviceName");let b="",v,y=0;const S=document.getElementById("syncPairingReview"),w=["syncPairingDeviceId","syncPairingFingerprint","syncPairingAddresses"].map(E=>document.getElementById(E)),R=()=>{S&&(S.hidden=!0);for(const E of w)E&&(E.textContent="")},k=E=>{if(!S||w.some(T=>!T))throw new Error("Pairing review unavailable. Refresh and try again.");const F=[E.device_id,E.fingerprint,E.addresses.join(`
|
|
118
|
-
`)];w.forEach((T,M)=>{T&&(T.textContent=F[M]??"")}),S.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},N=(E,F)=>F===y&&d?.value.trim()===E;r?.addEventListener("click",()=>{tc()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const $=async(E,F)=>{const T=await jh(E);return N(E,F)?(v=T.kind,T.kind==="pair"?(k(T),"other"):T.kind!=="project_share_invite"||!u||!m||!g?"other":(p&&(p.textContent=jW(T)),m.value=Gi(T.recipient_name),g.value=Gi(T.device_name),u.hidden=!1,b=E,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project")):"stale"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==b&&(b="",v=void 0,u&&(u.hidden=!0),R(),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const E=o.value.trim(),F=Number(s.value);let T=!0;if(E?gs(o):T=wi(o,"Team name is required."),!F||F<1?T=wi(s,"Must be at least 1 hour."):gs(s),!!T){i.disabled=!0,i.textContent="Creating…";try{const M=await Th({group_id:E,policy:Rn.invitePolicy,ttl_hours:F||24});_.lastTeamInvite=M,Km(),c.value=String(M.encoded||""),c.hidden=!1,c.focus(),c.select(),LW(Array.isArray(M.warnings)?M.warnings:[])}catch(M){Y(ht(M,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",E=>{Ia(E,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d||l.disabled)return;const E=d.value.trim();if(!E){wi(d,"Paste a team invite or pairing payload.");return}if(gs(d),b!==E){const T=y;l.disabled=!0;try{const M=await $(E,T);if(M==="project"||M==="stale")return}catch(M){if(!N(E,T))return;wi(d,ht(M,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{l.disabled=!1}if(!N(E,T))return;b=E,l.textContent="Accept invite";return}const F=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(F){const T=M=>Gi(M)==="";if(T(F.recipient_name)){m&&wi(m,"Enter a human-readable name using 120 characters or fewer.");return}if(T(F.device_name)){g&&wi(g,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const T=await Pd(E,F,v);_.lastTeamJoin=T;let M=$W(T);_.syncJoinFlowFeedback=M,Xl(),d.value="",y+=1,b="",v=void 0,R(),u&&(u.hidden=!0);try{await t()}catch(L){M={message:ht(L,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=M,Xl()}}catch(T){_.syncJoinFlowFeedback={message:ht(T,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Xl(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const E=await Xh(),F=tR(E);Y(F.message,F.warning?"warning":void 0)}catch(E){Y(ht(E,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function FW({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state==="healthy"?a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync on",state:"online"}),a("strong",{className:"xl",children:"Sync is on"}),a(Ue,{tone:"badge-online",variant:"badge",children:"On"})]}):a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function zm({element:e,hidden:t=!1,restoreParent:n=null}){const r=D(null);return ot(()=>{e&&(e.hidden=t)},[e,t]),ot(()=>{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 BW({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(H,{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(zm,{element:e,hidden:!t,restoreParent:n}):null]})}function qW({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(H,{children:[c?a(H,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(zm,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(H,{children:[r?a(zm,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(BW,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function ed({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 UW({item:e,onAction:t}){const[n,r]=A(!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 GW({request:e,onApprove:t,onDeny:n}){const[r,i]=A(null),[o,s]=A(null),[c,l]=A("Approve"),[d,u]=A("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(Tr,{feedback:o})]})}function HW({onReview:e,row:t}){const[n,r]=A(!1),[i,o]=A(null),s=t.actionLabel||"Pair with this device",[c,l]=A(s);return a(H,{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(Tr,{feedback:i})]})}function VW({onInspect:e,onRemove:t,row:n}){const[r,i]=A(!1),[o,s]=A(null),[c,l]=A("Remove broken device record");return a(H,{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(Tr,{feedback:o})]})}function KW({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("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(HW,{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(VW,{onInspect:t,onRemove:n,row:e}):null]})]})}function zW(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(H,{children:[r?a(ed,{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(UW,{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 WW({children:e}){return e?a(H,{children:[a(ed,{label:"Add devices & teammates"}),e]}):null}function JW({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!_.syncDiscoveredFeedback?null:un(a(H,{children:[a(ed,{count:t.length||void 0,label:"Devices waiting for review"}),a(Tr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(KW,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function YW({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:un(a(H,{children:[a(ed,{count:t.length||void 0,label:"Join requests to review"}),a(Tr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(GW,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function xR(e){return a(H,{children:[a(zW,{...e}),a(WW,{children:e.children}),a(YW,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(JW,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function DR(e){e&&(e.textContent="")}function td(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 QW(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vs(){return QW()?"auto":"smooth"}var Wm="syncTeamActionsMount",XW="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function ZW(e,t,n=!1){return e.length>1&&(!t||n)}function e3(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 t3(e,t){const n=document.createElement("div");n.id=Wm,e.appendChild(n),lt(n,h(xR,{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 jR(e,t){const n=document.getElementById(Wm);n&&(Ao(n),n.remove()),DR(e),t.forEach(r=>{DR(r)})}function n3(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");jR(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,t3(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function nd(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Vm(),Zl(),Km(),Xl(),DW();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");Pr("syncTeamSkeleton"),ER();const p=_.lastSyncCoordinator,f=i3();r3(f.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},g=C=>{if(m(),C.kind==="possible-duplicate-person"){const te=document.getElementById("syncActorsList");te instanceof HTMLElement&&(te.scrollIntoView({block:"center",behavior:vs()}),td(te));return}const x=String(C.deviceId||"").trim();if(!x)return;if(C.kind==="name-device"){const te=document.querySelector(`[data-device-name-input="${CSS.escape(x)}"]`);if(te instanceof HTMLInputElement){te.scrollIntoView({block:"center",behavior:vs()}),te.focus(),te.select(),td(te);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(x)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:vs()}),td(B);return}const U=document.querySelector(`[data-discovered-device-id="${CSS.escape(x)}"]`);U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:vs()}),td(U))},b=async C=>{const x=Array.isArray(C.actorIds)?C.actorIds.map(ee=>String(ee||"").trim()).filter(Boolean):[],B=(Array.isArray(_.lastSyncActors)?_.lastSyncActors:[]).filter(ee=>x.includes(String(ee?.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 U=await YO({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(ee=>({actorId:String(ee?.actor_id||""),label:String(ee?.display_name||ee?.actor_id||"Unknown person"),isLocal:!!ee?.is_local}))});if(U.action==="different-people"){Dz(x,"different-people"),Y("Okay. I will keep these people separate on this device."),await Rn.loadSyncData();return}if(U.action!=="merge")return;const te=B.find(ee=>String(ee?.actor_id||"")===U.primaryActorId),ae=B.find(ee=>String(ee?.actor_id||"")===U.secondaryActorId);if(!te?.actor_id||!ae?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await Qh(String(te.actor_id),String(ae.actor_id)),jz(x),Y(`Combined duplicate people into ${String(te.display_name||te.actor_id)}.`),await Rn.loadSyncData()}catch(ee){try{await Rn.loadSyncData()}catch{}Y(ht(ee,"Failed to combine these people."),"warning")}},v=async C=>await sf({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:x=>x.trim()?null:"Enter a device name to pair this device."}),y=!!p?.configured,S=bz(p);e.title=y?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?e3(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!y){n3({actions:n,setupPanel:t,primaryStatus:f.primaryStatus});return}t.hidden=!0,n.hidden=!1;const R=String(p.presence_status||""),k=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(f.attentionItems)?f.attentionItems:[],$=Array.isArray(p.discovered_devices)?p.discovered_devices:[],E=String(p.coordinator_url||"").trim(),F=$.map(C=>{const x=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),U=rR({coordinatorName:B,deviceId:x})||"Discovered device",te=x&&U!==x?x:null,ae=String(C.fingerprint||"").trim(),ee=String(C.incoming_reciprocal_request_id||"").trim(),qe=Array.isArray(C.groups)?C.groups.map(tr=>String(tr||"").trim()).filter(Boolean):[],fe=k.find(tr=>String(tr?.peer_device_id||"")===x),$e=ZW(qe,!!fe,C.needs_local_approval===!0),Ne=eR({device:C,pairedLocally:!!fe}),se=String(fe?.fingerprint||"").trim(),we=!!fe&&!!ae&&!!se&&se!==ae,Q=_.pendingCoordinatorApprovalsByDeviceId.get(x),ie=C.needs_local_approval===!0&&Q?.coordinatorUrl===E&&Q?.incomingRequestId===ee,je=ie?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",ue=!ie&&!S&&xK({device:C,hasAmbiguousCoordinatorGroup:$e,pairedLocally:!!fe}),dt=Array.isArray(C.addresses)?C.addresses:[],ye=Number(C.address_count??0),Dt=Number.isFinite(ye)&&ye>0?ye:0,it=a3({pairedLocally:!!fe,device:C,addressCount:dt.length+Dt}),le=[dt.length?dt.map(tr=>ha()?yR(String(tr||"")):String(tr||"")).filter(Boolean).join(" · "):Dt>0?`${Dt} ${C.stale?"last-known":"fresh"} ${Dt===1?"address":"addresses"} hidden`:"No fresh addresses"];!dt.length&&te&&le.push(`device id: ${x}`);let Ct=null,Xe=ue?"accept":"none",ws=null;we?Xe="conflict":ie?(Ct="Waiting for refreshed coordinator status. You do not need to approve again.",Xe="approval-pending"):S&&(!fe||Ne.state==="needs-your-approval")?(Ct=S.message,Xe="setup-blocked"):$e?(Ct="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",Xe="ambiguous"):it?(Ct=it.actionMessage,Xe=it.mode):fe&&Em(x)?(Ct="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",Xe="scope-pending"):fe?.last_error?(le.push(`error: ${String(fe.last_error)}`),ue||(Xe="paired")):fe?.status?.peer_state?(le.push(`status: ${String(fe.status.peer_state)}`),ue||(Xe="paired")):fe&&!ue&&(Xe="paired"),Xe==="paired"&&(ws=s3(Ne.state,Ne.description,fe?.last_error));const Ss=c3(we,!!fe);return{actionMessage:Ct,actionLabel:Ne.actionLabel||(fe?"Review device":"Pair with this device"),approvalBadgeLabel:ie?"Approval sent":Ne.badgeLabel,approvalState:je,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:Ss,coordinatorUrl:E,deviceId:x,displayName:U,displayTitle:te,fingerprint:ae,groupId:qe[0]??"",incomingRequestId:ee,mode:Xe,note:le.join(" · "),pairedMessage:ws}}),T=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),M=N.filter(C=>!C.deviceId||!T.has(C.deviceId)),L=[],G=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=M.length+L.length+V;l&&(l.hidden=G.length===0&&!_.syncDiscoveredFeedback),d&&(d.textContent=G.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=L.length===0&&!_.syncJoinRequestsFeedback),jR(n,[c,u]);const O=document.createElement("div");O.id=Wm,n.appendChild(O),lt(O,h(xR,{actionItems:M,actionableCount:z,children:h(qW,{invitePanel:r,invitePanelOpen:Pm,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(Nz(!Pm),nd())},presenceStatus:R}),discoveredListMount:u,discoveredRows:G,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 x=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(x instanceof HTMLElement){x.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 bn({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 Lh(C.deviceId);const x={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 _.syncDiscoveredFeedback=x,await Rn.loadSyncData(),x}catch(x){return{message:ht(x,"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 x=await v(C.displayName);return x?await o3(C,x):null}catch(x){return{message:ht(x,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:L,presenceStatus:R,primaryStatus:f.primaryStatus}))}function r3(e){const t=document.getElementById("syncAdvancedStatusMount");t&<(t,h(FW,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function i3(){return _.lastSyncViewModel||{primaryStatus:dR({status:_.lastSyncStatus,coordinator:_.lastSyncCoordinator,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function o3(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 bk(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&_.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];_.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."}],Tz(e.deviceId);let u=n?{message:XW,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};_.syncDiscoveredFeedback=u,n&&nd();try{t.trim()!==l.trim()&&(await Oh(e.deviceId,t.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ht(p,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=u;try{await Rn.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ht(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=u}return u}function a3({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 s3(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 c3(e,t){return e?pR.conflicts:t?pR.pairedLocally:"Not connected on this device"}function l3(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 Do(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function LR(e){return Do(e)?"Unclear project identity":e.displayProject}function zt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function d3(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function u3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p3(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function f3(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function m3(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 h3(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function g3({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"," · ",m3(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:h3(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 OR(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${u3(t)}\\b`,"g"),p3(t,n))),r}function v3(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 y3({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 b3({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]=A({}),[l,d]=A({}),[u,p]=A(o),[f,m]=A({}),[g,b]=A("all"),[v,y]=A(""),[S,w]=A(null),R=r.length,k=e.totalGroupCount??R,N=r.filter(Do).length,$=r.filter(C=>C.suggestedScopeId&&!Do(C)&&zt(C)).length,E=r.filter(C=>f[C.workspaceIdentity]&&zt(C)).length,F=r.filter(C=>f[C.workspaceIdentity]&&zt(C)&&!!u[C.workspaceIdentity]).length,T=r.filter(C=>{const x=Do(C);return g==="suggested"&&(!C.suggestedScopeId||x)||g==="cleanup"&&!x||g==="no-suggestion"&&(C.suggestedScopeId||x)||g==="selected"&&!f[C.workspaceIdentity]?!1:!v.trim()||v3(C,i).includes(v.trim().toLowerCase())});async function M(C){const x=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!x||!t||S)){w(C.workspaceIdentity),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U});try{const B=await t(C,x,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?U=>({...U,[C.workspaceIdentity]:B}):U=>{const te={...U};return delete te[C.workspaceIdentity],te})}catch(B){d(U=>({...U,[C.workspaceIdentity]:OR(B,x,i)}))}finally{w(null)}}}function L(C,x){p(B=>({...B,[C.workspaceIdentity]:x})),c(B=>{const U={...B};return delete U[C.workspaceIdentity],U}),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U})}function G(C,x){m(B=>({...B,[C.workspaceIdentity]:x}))}function V(C){m(x=>({...x,...Object.fromEntries(T.filter(zt).map(B=>[B.workspaceIdentity,C]))}))}function z(){m(C=>({...C,...Object.fromEntries(r.filter(x=>x.suggestedScopeId&&!Do(x)&&zt(x)).map(x=>[x.workspaceIdentity,!0]))}))}async function O(){if(!t||S||F===0)return;const C=r.filter(x=>f[x.workspaceIdentity]&&zt(x)&&!!u[x.workspaceIdentity]);if(!C.every(x=>s[x.workspaceIdentity])){w("bulk");try{for(const x of C){if(s[x.workspaceIdentity])continue;const B=u[x.workspaceIdentity]||x.suggestedScopeId||"";if(B)try{const U=await t(x,B,!1);d(te=>{const ae={...te};return delete ae[x.workspaceIdentity],ae}),U&&c(te=>({...te,[x.workspaceIdentity]:U}))}catch(U){d(te=>({...te,[x.workspaceIdentity]:OR(U,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:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<k?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${$.toLocaleString()}`],["cleanup",`Needs cleanup ${N.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,x])=>a("button",{className:g===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:x},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=>y(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),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=>f[C.workspaceIdentity]&&zt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{O()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&E>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>f[C.workspaceIdentity]&&zt(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:T.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 ${LR(C)}`,checked:!!f[C.workspaceIdentity],className:"cm-checkbox",disabled:!zt(C),onChange:x=>G(C,x.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:LR(C)}),a("div",{className:"legacy-review-group-meta",children:[l3(C.identitySource),d3(C,i)]}),zt(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."}),Do(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(g3,{group:C}),i.length>0&&t&&zt(C)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:S!=null,onChange:x=>L(C,x.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(x=>a("option",{value:x.scopeId,children:[x.label," · ",f3(x.authorityType),x.scopeId===C.suggestedScopeId?" · suggested":""]},x.scopeId))]})]}):null,i.length>0&&t&&zt(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{M(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function _3({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(H,{children:[t?a(b3,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(y3,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function w3(){op("mine"),_.feedQuery="",window.location.hash="feed"}function S3(){window.location.hash="projects"}async function C3(e,t,n,r){try{const i=await rN({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.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}.`),$R(),null}catch(i){if(i instanceof Mh)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function $R(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,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(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){Ao(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;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(_3,{items:d,legacyReview:c,onLegacyReassign:C3,onLegacyReview:S3,onReview:w3}))}var rd="";function R3(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 _.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){_.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)||_.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function I3(){return[..._.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var ys=null,Jm=0,Ym=null,Qm=0,Xm=null,k3=15e3;function MR(e){return`project:${e||""}|includeJoinRequests:false`}function N3(e){const t=MR(e);return!ys||ys.key!==t||Date.now()>=ys.expiresAtMs?null:ys.payload}function P3(e,t){ys={key:MR(e),expiresAtMs:Date.now()+k3,payload:t}}function T3(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function A3(){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 E3(e,t){if(_.activeTab==="health"&&!t.requireFreshSyncStatus){const r=N3(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!ha();return{payload:await Nd(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function x3(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}async function D3(e){const t=xz();let n=null,r=null,i=_.lastDeviceIdentityInventory,o=_.lastShareOperations,s=!1,c=!1,l=_.deviceIdentityInventoryLoadError,d=!1;try{n=await gk({signal:e.signal})}catch{s=!0}try{r=await Rd({signal:e.signal})}catch{c=!0}if(_.activeTab==="advanced"){l=!1;try{i=await Dd({signal:e.signal})}catch{l=!0}}try{const u=await Yh({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 id(e={}){const t=j3(++Jm,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return Ym=t,t}async function j3(e,t){try{const n=_.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await E3(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:p,shareOperationsLoadError:f,duplicatePersonDecisions:m}=await D3(t);if(e!==Jm)return Ym??!1;if(t.signal?.aborted)return!1;const g=x3({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:_.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&P3(n,T3(r)),R3(r.coordinator);const b=JSON.stringify([r,o,s,c,p,l,f,m,I3()]);if(b===rd)return g;rd=b;const v=r.status&&typeof r.status=="object"?r.status:null;v&&(_.lastSyncStatus=v),Array.isArray(o?.items)?_.lastSyncActors=o.items:_.lastSyncActors=[];const y=Array.isArray(r.peers)?r.peers:[],S=new Set(y.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(R=>{const k=String(R?.peer_device_id||"").trim();return k&&!S.has(k)}):[];return _.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...y,...w],p||(_.lastDeviceIdentityInventory=c),_.deviceIdentityInventoryLoadError=p,_.lastShareOperations=l,_.shareOperationsLoadError=f,_.lastSyncSharingReview=r.sharing_review||[],_.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,_.lastSyncCoordinator=r.coordinator||null,_.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,_.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],_.lastSyncAttempts=r.attempts||[],_.lastSyncLegacyDevices=r.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=m,_.lastSyncViewModel=Iz({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:v,shareOperations:_.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),SR(),nd(),RW(),kW(),$R(),Gm(),TR(),wR(),O3(),d&&IW(),u&&(_.lastSyncCoordinatorAdminStatus=null,nd()),g}catch{return t.signal?.aborted?!1:e!==Jm?Ym??!1:(rd="",_.deviceIdentityInventoryLoadError=!0,L3(),!1)}}function L3(){Pr("syncTeamSkeleton"),Pr("syncActorsSkeleton"),Pr("syncPeersSkeleton"),Pr("syncDiagSkeleton"),A3(),ER();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),NW(),qz()}function O3(){if(_.activeTab==="health"){MS();return}jS()}function $3(){rd="",_.lastSyncPeers?.length&&Gm()}async function od(){await id()}function M3(e={}){const t=F3(++Qm,e.signal);return Xm=t,t}async function F3(e,t){try{const n=await vk(!1,{signal:t});return t?.aborted?!1:e!==Qm?Xm??!1:(_.pairingPayloadRaw=n||null,$m(),!0)}catch{return t?.aborted?!1:e!==Qm?Xm??!1:(_.pairingPayloadRaw=null,$m(),!1)}}function B3(e){dK(),Zc(),EW(od),CW(od),Kz(Gm),MW(e,od),PW(od),zz(e),Hm(),AW()}function q3(e,t){const n=tt("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function U3(){try{const e=await JI();if(!e?.version)return;q3(e.version,"fb41c76")}catch{}}var Zm=null,FR=1500,bs=S0(),BR="codemem-legacy-upgrade-notice-dismissed",Er=null,an=!1,ad=!1,eh=!1;function qR(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function UR(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=qR(n.total_group_count,r.length),o=qR(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function GR(){try{return localStorage.getItem(BR)==="1"}catch{return!1}}function G3(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(BR,"1")}catch{}}function H3(e,t){e&&t?Tx(t):Ax()}function HR(e){!e||eh||GR()||(eh=!0,Ty(()=>H3(!0,e)))}async function V3(){if(!(eh||GR()))try{HR(UR(await Nd(!1,"",{includeJoinRequests:!1})))}catch{}}function Ci(e,t){_.viewerReconnectOpen=e;const n=tt("viewerReconnectOverlay"),r=tt("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",_.activeTab==="feed"&&wn(!0))}async function th(){try{return await WI(),!0}catch{return!1}}function nh(){return document.visibilityState!=="hidden"&&!MC()}function VR(){return`${_.activeTab}:${_.advancedSection}:${_.syncPairingOpen}`}function K3(e){_.refreshQueued||e.surface!==VR()||!e.refreshSucceeded||!ad||an||(ad=!1,$u("connection_restored"))}function KR(){if(an)return;an=!0,ad=!0,$u("connection_lost"),rh(),Ty(),xr("error","(reconnecting)"),Ci(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await th()){if(Er&&(clearTimeout(Er),Er=null),an=!1,Ci(!0,"Viewer responded. Restoring your session…"),nh()){xr("refreshing"),_s();try{await ld()}catch{}}else xr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");an||Ci(!1);return}Ci(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Er=setTimeout(e,FR)};Er=setTimeout(e,FR)}function xr(e,t){_.refreshState=e;const n=tt("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=tt("refreshAnnouncer");!s||Zm===e||(s.textContent=o,Zm=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}`,Zm=null}function rh(){bs.cancel(),jo&&(clearTimeout(jo),jo=null),_.refreshQueued=!1,_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function zR(){rh(),xr("paused")}function _s(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Dr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(rh(),xr("paused","(tab hidden)")):!MC()&&!an&&(_s(),Dr())});var sd=!1;function WR(){const e=_.advancedSection==="sync",t=tt("advancedSyncContent"),n=tt("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=tt("advancedTabsMount");r&&mD(r,_.advancedSection,z3),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&sd){sd=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}Hm(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function z3(e,t={}){ub(e,!0),WR(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var W3=O0();function JR(e){const t=new Set(k0(_.lastCoordinatorAdminStatus));zr.forEach(r=>{const i=tt(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),zr.forEach(r=>{const i=tt(`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=tt(`tabBtn-${e}`);n&&W3(n),e==="advanced"&&WR()}function In(e,t={}){bs.cancel();const n=ma(e,_.lastCoordinatorAdminStatus);n==="advanced"&&ub(t.advancedSection??ip()??_.advancedSection),pb(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&ai("settings-health"),JR(n),Dr()}function J3(){window.addEventListener("codemem:navigate-advanced-sync",X3),zr.forEach(e=>{tt(`tabBtn-${e}`)?.addEventListener("click",()=>In(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),tt("syncTurnOnButton")?.addEventListener("click",()=>{$C("sync"),zC(zR)}),tt("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),xu("teams"),In("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),tt("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),xu("invitations"),In("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=rp();if(e){const t=ip();sd=db(),In(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),sd=db(),In(_.activeTab)}async function Y3(){try{const e=await ks();_.knownProjects=e,$3();const t=tp("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function Q3(e){_.pendingDeviceIdentityFocus=e?.trim()||null,In("devices",{canonicalHash:!0})}function X3(){In("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var cd=_E({},{onOpenTeamSetup:rC,onReviewDevices:Q3}),YR={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},ih=0,oh=null,Wt=null;async function Z3(e={}){const t=[];let n=0;for(;;){const r=await qo({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return Zs(t)}function eJ(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of _.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 tJ(){return _.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function nJ(e){if(e==="advanced_sync"){In("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){In("sharing",{canonicalHash:!0}),xu("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}In(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function ah(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=iJ(t,++ih,e);return oh=n,n}async function rJ(){const[e,t]=await Promise.all([ah(),cd()]);return e&&t}function QR(){return{localDeviceId:_.lastSyncStatus?.device_id??void 0,onCommitted:rJ,onNavigate:nJ,onRetry:()=>{ah()}}}async function iJ(e,t,n){Wt||al(e,YR,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([Z3(n),xd(n),Fk(n),Dd(n).then(p=>({inventory:p,unavailable:!1})).catch(()=>({inventory:Wt?.inventory,unavailable:!0})),id({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==ih)return oh??!1;const l=eJ(),d=tJ(),u=Zh(_.lastSyncStatus);return!s.unavailable&&s.inventory&&(_.lastDeviceIdentityInventory=s.inventory),_.deviceIdentityInventoryLoadError=s.unavailable,al(e,i,o,r,l,{...QR(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u,peerRuntimeMetadata:d}),Wt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u},c}catch{return n.signal?.aborted?!1:t!==ih?oh??!1:(Wt?al(e,Wt.intent,Wt.reconciliation,Wt.projects,Wt.availability,{...QR(),coordinatorEnrollmentIssueCount:Wt.coordinatorEnrollmentIssueCount,inventory:Wt.inventory,inventoryUnavailable:Wt.inventoryUnavailable,peerRuntimeMetadata:Wt.peerRuntimeMetadata,refreshError:!0}):al(e,YR,{version:1,items:[]},[],[],{loadError:!0}),!1)}}tp("projectFilter")?.addEventListener("change",()=>{bs.cancel(),_.currentProject=tp("projectFilter")?.value||"",ai("scope"),wn(!0),Dr()});var jo=null;async function oJ(e){await Promise.all([JU({signal:e.signal}),_V({signal:e.signal}),Cx().catch(()=>{})])}function aJ(e,t,n,r){if(t!=="health"&&jS(),t==="feed"){const s=N$();e.push(O_(s,{signal:r.signal}),em({signal:r.signal}))}if(t==="projects"&&e.push(No({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(cd({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(ah({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(YU({signal:r.signal}),id({requiredSurface:"health",requireFreshSyncStatus:ad,signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="sync"&&e.push(id({signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="teams"&&e.push(nl({deferWhileRenaming:!0,signal:r.signal}).then(n)),!_.syncPairingOpen)return;const i=t==="advanced"&&_.advancedSection==="sync",o=M3({signal:r.signal});e.push(i?o.then(n):o)}async function Dr(){an||(jo&&clearTimeout(jo),jo=setTimeout(()=>ld(),80))}async function sJ(e,t){if(!t.isCurrent()&&!Rh(e))return;const n=await th();t.isOwned()&&(n?xr("error"):KR())}function cJ(e){bs.finish(e),_.refreshInFlight=!1,!(!_.refreshQueued||an||!nh())&&(_.refreshQueued=!1,ld())}async function ld(){if(an||!nh())return;if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;const e=bs.begin();try{xr("refreshing");const t=_.activeTab,n=VR(),r=[oJ(e)];let i=!0;if(aJ(r,t,s=>{i=i&&s},e),await Is(Promise.all(r),e.signal),!e.isCurrent()){if(Rh(e.signal.reason))throw e.signal.reason;return}HR(UR(_.lastSyncLegacySharedReview)),t==="feed"&&wn(!0);const o=ma(_.activeTab,_.lastCoordinatorAdminStatus);o!==_.activeTab&&pb(o),JR(_.activeTab),xr(i?"idle":"error"),K3({refreshSucceeded:i,surface:n})}catch(t){await sJ(t,e)}finally{cJ(e)}}j0();var XR=document.getElementById("toastRoot");XR&&w0(XR);var ZR=document.getElementById("diagnosticsDrawerMount");ZR&&Sx(ZR);var eI=document.getElementById("legacyTeamSetupMount");eI&&QG(eI,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(_.activeTab==="sharing"?(t=await No(n),e=await cd(n)):(e=await cd(n),t=await No(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var tI=document.getElementById("legacyUpgradeDialogMount");tI&&Px(tI,{onDismiss:G3,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),$0(bc("themeToggle")),gb(sp()),J3(),xq(),Rx(),ZH(()=>Dr(),{onOpenTeamSetup:rC}),B3(()=>Dr()),j$(),cK(zR,_s,()=>Dr()),Y3(),tt("viewerReconnectRetry")?.addEventListener("click",async()=>{if($u("reconnect_requested"),Ci(!0,"Checking whether the viewer server is back…"),!await th()){KR();return}Er&&(clearTimeout(Er),Er=null),an=!1,Ci(!0,"Viewer responded. Restoring your session…"),_s();try{await ld()}catch{}an||Ci(!1)}),U3(),V3(),Dr(),_s()})();
|
|
118
|
+
`)];w.forEach((T,M)=>{T&&(T.textContent=F[M]??"")}),S.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},N=(E,F)=>F===y&&d?.value.trim()===E;r?.addEventListener("click",()=>{tc()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const $=async(E,F)=>{const T=await jh(E);return N(E,F)?(v=T.kind,T.kind==="pair"?(k(T),"other"):T.kind!=="project_share_invite"||!u||!m||!g?"other":(p&&(p.textContent=jW(T)),m.value=Gi(T.recipient_name),g.value=Gi(T.device_name),u.hidden=!1,b=E,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project")):"stale"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==b&&(b="",v=void 0,u&&(u.hidden=!0),R(),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const E=o.value.trim(),F=Number(s.value);let T=!0;if(E?gs(o):T=wi(o,"Team name is required."),!F||F<1?T=wi(s,"Must be at least 1 hour."):gs(s),!!T){i.disabled=!0,i.textContent="Creating…";try{const M=await Th({group_id:E,policy:Rn.invitePolicy,ttl_hours:F||24});_.lastTeamInvite=M,Km(),c.value=String(M.encoded||""),c.hidden=!1,c.focus(),c.select(),LW(Array.isArray(M.warnings)?M.warnings:[])}catch(M){Y(ht(M,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",E=>{Ia(E,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d||l.disabled)return;const E=d.value.trim();if(!E){wi(d,"Paste a team invite or pairing payload.");return}if(gs(d),b!==E){const T=y;l.disabled=!0;try{const M=await $(E,T);if(M==="project"||M==="stale")return}catch(M){if(!N(E,T))return;wi(d,ht(M,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{l.disabled=!1}if(!N(E,T))return;b=E,l.textContent="Accept invite";return}const F=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:g?.value.trim()??""}:void 0;if(F){const T=M=>Gi(M)==="";if(T(F.recipient_name)){m&&wi(m,"Enter a human-readable name using 120 characters or fewer.");return}if(T(F.device_name)){g&&wi(g,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const T=await Pd(E,F,v);_.lastTeamJoin=T;let M=$W(T);_.syncJoinFlowFeedback=M,Xl(),d.value="",y+=1,b="",v=void 0,R(),u&&(u.hidden=!0);try{await t()}catch(L){M={message:ht(L,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=M,Xl()}}catch(T){_.syncJoinFlowFeedback={message:ht(T,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},Xl(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const E=await Xh(),F=tR(E);Y(F.message,F.warning?"warning":void 0)}catch(E){Y(ht(E,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function FW({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state==="healthy"?a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync on",state:"online"}),a("strong",{className:"xl",children:"Sync is on"}),a(Ue,{tone:"badge-online",variant:"badge",children:"On"})]}):a("div",{className:"advanced-sync-status-label",children:[a(tn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function zm({element:e,hidden:t=!1,restoreParent:n=null}){const r=D(null);return ot(()=>{e&&(e.hidden=t)},[e,t]),ot(()=>{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 BW({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(H,{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(zm,{element:e,hidden:!t,restoreParent:n}):null]})}function qW({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(H,{children:[c?a(H,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(zm,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(H,{children:[r?a(zm,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(BW,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function ed({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 UW({item:e,onAction:t}){const[n,r]=A(!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 GW({request:e,onApprove:t,onDeny:n}){const[r,i]=A(null),[o,s]=A(null),[c,l]=A("Approve"),[d,u]=A("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(Tr,{feedback:o})]})}function HW({onReview:e,row:t}){const[n,r]=A(!1),[i,o]=A(null),s=t.actionLabel||"Pair with this device",[c,l]=A(s);return a(H,{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(Tr,{feedback:i})]})}function VW({onInspect:e,onRemove:t,row:n}){const[r,i]=A(!1),[o,s]=A(null),[c,l]=A("Remove broken device record");return a(H,{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(Tr,{feedback:o})]})}function KW({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("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(HW,{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(VW,{onInspect:t,onRemove:n,row:e}):null]})]})}function zW(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(H,{children:[r?a(ed,{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(UW,{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 WW({children:e}){return e?a(H,{children:[a(ed,{label:"Add devices & teammates"}),e]}):null}function JW({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!_.syncDiscoveredFeedback?null:un(a(H,{children:[a(ed,{count:t.length||void 0,label:"Devices waiting for review"}),a(Tr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(KW,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function YW({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:un(a(H,{children:[a(ed,{count:t.length||void 0,label:"Join requests to review"}),a(Tr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(GW,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function xR(e){return a(H,{children:[a(zW,{...e}),a(WW,{children:e.children}),a(YW,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(JW,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function DR(e){e&&(e.textContent="")}function td(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 QW(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vs(){return QW()?"auto":"smooth"}var Wm="syncTeamActionsMount",XW="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function ZW(e,t,n=!1){return e.length>1&&(!t||n)}function e3(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 t3(e,t){const n=document.createElement("div");n.id=Wm,e.appendChild(n),lt(n,h(xR,{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 jR(e,t){const n=document.getElementById(Wm);n&&(Ao(n),n.remove()),DR(e),t.forEach(r=>{DR(r)})}function n3(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");jR(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,t3(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function nd(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;Vm(),Zl(),Km(),Xl(),DW();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");Pr("syncTeamSkeleton"),ER();const p=_.lastSyncCoordinator,f=i3();r3(f.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},g=C=>{if(m(),C.kind==="possible-duplicate-person"){const te=document.getElementById("syncActorsList");te instanceof HTMLElement&&(te.scrollIntoView({block:"center",behavior:vs()}),td(te));return}const x=String(C.deviceId||"").trim();if(!x)return;if(C.kind==="name-device"){const te=document.querySelector(`[data-device-name-input="${CSS.escape(x)}"]`);if(te instanceof HTMLInputElement){te.scrollIntoView({block:"center",behavior:vs()}),te.focus(),te.select(),td(te);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(x)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:vs()}),td(B);return}const U=document.querySelector(`[data-discovered-device-id="${CSS.escape(x)}"]`);U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:vs()}),td(U))},b=async C=>{const x=Array.isArray(C.actorIds)?C.actorIds.map(ee=>String(ee||"").trim()).filter(Boolean):[],B=(Array.isArray(_.lastSyncActors)?_.lastSyncActors:[]).filter(ee=>x.includes(String(ee?.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 U=await YO({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(ee=>({actorId:String(ee?.actor_id||""),label:String(ee?.display_name||ee?.actor_id||"Unknown person"),isLocal:!!ee?.is_local}))});if(U.action==="different-people"){Dz(x,"different-people"),Y("Okay. I will keep these people separate on this device."),await Rn.loadSyncData();return}if(U.action!=="merge")return;const te=B.find(ee=>String(ee?.actor_id||"")===U.primaryActorId),ae=B.find(ee=>String(ee?.actor_id||"")===U.secondaryActorId);if(!te?.actor_id||!ae?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await Qh(String(te.actor_id),String(ae.actor_id)),jz(x),Y(`Combined duplicate people into ${String(te.display_name||te.actor_id)}.`),await Rn.loadSyncData()}catch(ee){try{await Rn.loadSyncData()}catch{}Y(ht(ee,"Failed to combine these people."),"warning")}},v=async C=>await sf({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:x=>x.trim()?null:"Enter a device name to pair this device."}),y=!!p?.configured,S=bz(p);e.title=y?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?e3(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!y){n3({actions:n,setupPanel:t,primaryStatus:f.primaryStatus});return}t.hidden=!0,n.hidden=!1;const R=String(p.presence_status||""),k=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(f.attentionItems)?f.attentionItems:[],$=Array.isArray(p.discovered_devices)?p.discovered_devices:[],E=String(p.coordinator_url||"").trim(),F=$.map(C=>{const x=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),U=rR({coordinatorName:B,deviceId:x})||"Discovered device",te=x&&U!==x?x:null,ae=String(C.fingerprint||"").trim(),ee=String(C.incoming_reciprocal_request_id||"").trim(),qe=Array.isArray(C.groups)?C.groups.map(tr=>String(tr||"").trim()).filter(Boolean):[],fe=k.find(tr=>String(tr?.peer_device_id||"")===x),$e=ZW(qe,!!fe,C.needs_local_approval===!0),Ne=eR({device:C,pairedLocally:!!fe}),se=String(fe?.fingerprint||"").trim(),we=!!fe&&!!ae&&!!se&&se!==ae,Q=_.pendingCoordinatorApprovalsByDeviceId.get(x),ie=C.needs_local_approval===!0&&Q?.coordinatorUrl===E&&Q?.incomingRequestId===ee,je=ie?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",ue=!ie&&!S&&xK({device:C,hasAmbiguousCoordinatorGroup:$e,pairedLocally:!!fe}),dt=Array.isArray(C.addresses)?C.addresses:[],ye=Number(C.address_count??0),Dt=Number.isFinite(ye)&&ye>0?ye:0,it=a3({pairedLocally:!!fe,device:C,addressCount:dt.length+Dt}),le=[dt.length?dt.map(tr=>ha()?yR(String(tr||"")):String(tr||"")).filter(Boolean).join(" · "):Dt>0?`${Dt} ${C.stale?"last-known":"fresh"} ${Dt===1?"address":"addresses"} hidden`:"No fresh addresses"];!dt.length&&te&&le.push(`device id: ${x}`);let Ct=null,Xe=ue?"accept":"none",ws=null;we?Xe="conflict":ie?(Ct="Waiting for refreshed coordinator status. You do not need to approve again.",Xe="approval-pending"):S&&(!fe||Ne.state==="needs-your-approval")?(Ct=S.message,Xe="setup-blocked"):$e?(Ct="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",Xe="ambiguous"):it?(Ct=it.actionMessage,Xe=it.mode):fe&&Em(x)?(Ct="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",Xe="scope-pending"):fe?.last_error?(le.push(`error: ${String(fe.last_error)}`),ue||(Xe="paired")):fe?.status?.peer_state?(le.push(`status: ${String(fe.status.peer_state)}`),ue||(Xe="paired")):fe&&!ue&&(Xe="paired"),Xe==="paired"&&(ws=s3(Ne.state,Ne.description,fe?.last_error));const Ss=c3(we,!!fe);return{actionMessage:Ct,actionLabel:Ne.actionLabel||(fe?"Review device":"Pair with this device"),approvalBadgeLabel:ie?"Approval sent":Ne.badgeLabel,approvalState:je,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:Ss,coordinatorUrl:E,deviceId:x,displayName:U,displayTitle:te,fingerprint:ae,groupId:qe[0]??"",incomingRequestId:ee,mode:Xe,note:le.join(" · "),pairedMessage:ws}}),T=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),M=N.filter(C=>!C.deviceId||!T.has(C.deviceId)),L=[],G=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=M.length+L.length+V;l&&(l.hidden=G.length===0&&!_.syncDiscoveredFeedback),d&&(d.textContent=G.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=L.length===0&&!_.syncJoinRequestsFeedback),jR(n,[c,u]);const O=document.createElement("div");O.id=Wm,n.appendChild(O),lt(O,h(xR,{actionItems:M,actionableCount:z,children:h(qW,{invitePanel:r,invitePanelOpen:Pm,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(Nz(!Pm),nd())},presenceStatus:R}),discoveredListMount:u,discoveredRows:G,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 x=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(x instanceof HTMLElement){x.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 bn({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 Lh(C.deviceId);const x={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 _.syncDiscoveredFeedback=x,await Rn.loadSyncData(),x}catch(x){return{message:ht(x,"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 x=await v(C.displayName);return x?await o3(C,x):null}catch(x){return{message:ht(x,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:L,presenceStatus:R,primaryStatus:f.primaryStatus}))}function r3(e){const t=document.getElementById("syncAdvancedStatusMount");t&<(t,h(FW,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function i3(){return _.lastSyncViewModel||{primaryStatus:dR({status:_.lastSyncStatus,coordinator:_.lastSyncCoordinator,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function o3(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 bk(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&_.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];_.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."}],Tz(e.deviceId);let u=n?{message:XW,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};_.syncDiscoveredFeedback=u,n&&nd();try{t.trim()!==l.trim()&&(await Oh(e.deviceId,t.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ht(p,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=u;try{await Rn.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ht(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=u}return u}function a3({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 s3(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 c3(e,t){return e?pR.conflicts:t?pR.pairedLocally:"Not connected on this device"}function l3(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 Do(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function LR(e){return Do(e)?"Unclear project identity":e.displayProject}function zt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function d3(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function u3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p3(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function f3(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function m3(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 h3(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function g3({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"," · ",m3(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:h3(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 OR(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${u3(t)}\\b`,"g"),p3(t,n))),r}function v3(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 y3({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 b3({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]=A({}),[l,d]=A({}),[u,p]=A(o),[f,m]=A({}),[g,b]=A("all"),[v,y]=A(""),[S,w]=A(null),R=r.length,k=e.totalGroupCount??R,N=r.filter(Do).length,$=r.filter(C=>C.suggestedScopeId&&!Do(C)&&zt(C)).length,E=r.filter(C=>f[C.workspaceIdentity]&&zt(C)).length,F=r.filter(C=>f[C.workspaceIdentity]&&zt(C)&&!!u[C.workspaceIdentity]).length,T=r.filter(C=>{const x=Do(C);return g==="suggested"&&(!C.suggestedScopeId||x)||g==="cleanup"&&!x||g==="no-suggestion"&&(C.suggestedScopeId||x)||g==="selected"&&!f[C.workspaceIdentity]?!1:!v.trim()||v3(C,i).includes(v.trim().toLowerCase())});async function M(C){const x=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!x||!t||S)){w(C.workspaceIdentity),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U});try{const B=await t(C,x,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?U=>({...U,[C.workspaceIdentity]:B}):U=>{const te={...U};return delete te[C.workspaceIdentity],te})}catch(B){d(U=>({...U,[C.workspaceIdentity]:OR(B,x,i)}))}finally{w(null)}}}function L(C,x){p(B=>({...B,[C.workspaceIdentity]:x})),c(B=>{const U={...B};return delete U[C.workspaceIdentity],U}),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U})}function G(C,x){m(B=>({...B,[C.workspaceIdentity]:x}))}function V(C){m(x=>({...x,...Object.fromEntries(T.filter(zt).map(B=>[B.workspaceIdentity,C]))}))}function z(){m(C=>({...C,...Object.fromEntries(r.filter(x=>x.suggestedScopeId&&!Do(x)&&zt(x)).map(x=>[x.workspaceIdentity,!0]))}))}async function O(){if(!t||S||F===0)return;const C=r.filter(x=>f[x.workspaceIdentity]&&zt(x)&&!!u[x.workspaceIdentity]);if(!C.every(x=>s[x.workspaceIdentity])){w("bulk");try{for(const x of C){if(s[x.workspaceIdentity])continue;const B=u[x.workspaceIdentity]||x.suggestedScopeId||"";if(B)try{const U=await t(x,B,!1);d(te=>{const ae={...te};return delete ae[x.workspaceIdentity],ae}),U&&c(te=>({...te,[x.workspaceIdentity]:U}))}catch(U){d(te=>({...te,[x.workspaceIdentity]:OR(U,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:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<k?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${$.toLocaleString()}`],["cleanup",`Needs cleanup ${N.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,x])=>a("button",{className:g===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:x},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=>y(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:v}),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=>f[C.workspaceIdentity]&&zt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{O()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&E>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>f[C.workspaceIdentity]&&zt(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:T.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 ${LR(C)}`,checked:!!f[C.workspaceIdentity],className:"cm-checkbox",disabled:!zt(C),onChange:x=>G(C,x.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:LR(C)}),a("div",{className:"legacy-review-group-meta",children:[l3(C.identitySource),d3(C,i)]}),zt(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."}),Do(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(g3,{group:C}),i.length>0&&t&&zt(C)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:S!=null,onChange:x=>L(C,x.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(x=>a("option",{value:x.scopeId,children:[x.label," · ",f3(x.authorityType),x.scopeId===C.suggestedScopeId?" · suggested":""]},x.scopeId))]})]}):null,i.length>0&&t&&zt(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{M(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function _3({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(H,{children:[t?a(b3,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(y3,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function w3(){op("mine"),_.feedQuery="",window.location.hash="feed"}function S3(){window.location.hash="projects"}async function C3(e,t,n,r){try{const i=await rN({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.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}.`),$R(),null}catch(i){if(i instanceof Mh)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function $R(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,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(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){Ao(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;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(_3,{items:d,legacyReview:c,onLegacyReassign:C3,onLegacyReview:S3,onReview:w3}))}var rd="";function R3(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 _.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){_.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)||_.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function I3(){return[..._.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var ys=null,Jm=0,Ym=null,Qm=0,Xm=null,k3=15e3;function MR(e){return`project:${e||""}|includeJoinRequests:false`}function N3(e){const t=MR(e);return!ys||ys.key!==t||Date.now()>=ys.expiresAtMs?null:ys.payload}function P3(e,t){ys={key:MR(e),expiresAtMs:Date.now()+k3,payload:t}}function T3(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function A3(){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 E3(e,t){if(_.activeTab==="health"&&!t.requireFreshSyncStatus){const r=N3(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!ha();return{payload:await Nd(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function x3(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}async function D3(e){const t=xz();let n=null,r=null,i=_.lastDeviceIdentityInventory,o=_.lastShareOperations,s=!1,c=!1,l=_.deviceIdentityInventoryLoadError,d=!1;try{n=await gk({signal:e.signal})}catch{s=!0}try{r=await Rd({signal:e.signal})}catch{c=!0}if(_.activeTab==="advanced"){l=!1;try{i=await Dd({signal:e.signal})}catch{l=!0}}try{const u=await Yh({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 id(e={}){const t=j3(++Jm,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return Ym=t,t}async function j3(e,t){try{const n=_.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await E3(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:p,shareOperationsLoadError:f,duplicatePersonDecisions:m}=await D3(t);if(e!==Jm)return Ym??!1;if(t.signal?.aborted)return!1;const g=x3({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:_.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&P3(n,T3(r)),R3(r.coordinator);const b=JSON.stringify([r,o,s,c,p,l,f,m,I3()]);if(b===rd)return g;rd=b;const v=r.status&&typeof r.status=="object"?r.status:null;v&&(_.lastSyncStatus=v),Array.isArray(o?.items)?_.lastSyncActors=o.items:_.lastSyncActors=[];const y=Array.isArray(r.peers)?r.peers:[],S=new Set(y.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(R=>{const k=String(R?.peer_device_id||"").trim();return k&&!S.has(k)}):[];return _.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...y,...w],p||(_.lastDeviceIdentityInventory=c),_.deviceIdentityInventoryLoadError=p,_.lastShareOperations=l,_.shareOperationsLoadError=f,_.lastSyncSharingReview=r.sharing_review||[],_.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,_.lastSyncCoordinator=r.coordinator||null,_.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,_.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],_.lastSyncAttempts=r.attempts||[],_.lastSyncLegacyDevices=r.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=m,_.lastSyncViewModel=Iz({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:v,shareOperations:_.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),SR(),nd(),RW(),kW(),$R(),Gm(),TR(),wR(),O3(),d&&IW(),u&&(_.lastSyncCoordinatorAdminStatus=null,nd()),g}catch{return t.signal?.aborted?!1:e!==Jm?Ym??!1:(rd="",_.deviceIdentityInventoryLoadError=!0,L3(),!1)}}function L3(){Pr("syncTeamSkeleton"),Pr("syncActorsSkeleton"),Pr("syncPeersSkeleton"),Pr("syncDiagSkeleton"),A3(),ER();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),NW(),qz()}function O3(){if(_.activeTab==="health"){MS();return}jS()}function $3(){rd="",_.lastSyncPeers?.length&&Gm()}async function od(){await id()}function M3(e={}){const t=F3(++Qm,e.signal);return Xm=t,t}async function F3(e,t){try{const n=await vk(!1,{signal:t});return t?.aborted?!1:e!==Qm?Xm??!1:(_.pairingPayloadRaw=n||null,$m(),!0)}catch{return t?.aborted?!1:e!==Qm?Xm??!1:(_.pairingPayloadRaw=null,$m(),!1)}}function B3(e){dK(),Zc(),EW(od),CW(od),Kz(Gm),MW(e,od),PW(od),zz(e),Hm(),AW()}function q3(e,t){const n=tt("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function U3(){try{const e=await JI();if(!e?.version)return;q3(e.version,"295bc9b")}catch{}}var Zm=null,FR=1500,bs=S0(),BR="codemem-legacy-upgrade-notice-dismissed",Er=null,an=!1,ad=!1,eh=!1;function qR(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function UR(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=qR(n.total_group_count,r.length),o=qR(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function GR(){try{return localStorage.getItem(BR)==="1"}catch{return!1}}function G3(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(BR,"1")}catch{}}function H3(e,t){e&&t?Tx(t):Ax()}function HR(e){!e||eh||GR()||(eh=!0,Ty(()=>H3(!0,e)))}async function V3(){if(!(eh||GR()))try{HR(UR(await Nd(!1,"",{includeJoinRequests:!1})))}catch{}}function Ci(e,t){_.viewerReconnectOpen=e;const n=tt("viewerReconnectOverlay"),r=tt("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",_.activeTab==="feed"&&wn(!0))}async function th(){try{return await WI(),!0}catch{return!1}}function nh(){return document.visibilityState!=="hidden"&&!MC()}function VR(){return`${_.activeTab}:${_.advancedSection}:${_.syncPairingOpen}`}function K3(e){_.refreshQueued||e.surface!==VR()||!e.refreshSucceeded||!ad||an||(ad=!1,$u("connection_restored"))}function KR(){if(an)return;an=!0,ad=!0,$u("connection_lost"),rh(),Ty(),xr("error","(reconnecting)"),Ci(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await th()){if(Er&&(clearTimeout(Er),Er=null),an=!1,Ci(!0,"Viewer responded. Restoring your session…"),nh()){xr("refreshing"),_s();try{await ld()}catch{}}else xr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");an||Ci(!1);return}Ci(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),Er=setTimeout(e,FR)};Er=setTimeout(e,FR)}function xr(e,t){_.refreshState=e;const n=tt("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=tt("refreshAnnouncer");!s||Zm===e||(s.textContent=o,Zm=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}`,Zm=null}function rh(){bs.cancel(),jo&&(clearTimeout(jo),jo=null),_.refreshQueued=!1,_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function zR(){rh(),xr("paused")}function _s(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Dr(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(rh(),xr("paused","(tab hidden)")):!MC()&&!an&&(_s(),Dr())});var sd=!1;function WR(){const e=_.advancedSection==="sync",t=tt("advancedSyncContent"),n=tt("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=tt("advancedTabsMount");r&&mD(r,_.advancedSection,z3),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&sd){sd=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}Hm(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function z3(e,t={}){ub(e,!0),WR(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var W3=O0();function JR(e){const t=new Set(k0(_.lastCoordinatorAdminStatus));zr.forEach(r=>{const i=tt(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),zr.forEach(r=>{const i=tt(`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=tt(`tabBtn-${e}`);n&&W3(n),e==="advanced"&&WR()}function In(e,t={}){bs.cancel();const n=ma(e,_.lastCoordinatorAdminStatus);n==="advanced"&&ub(t.advancedSection??ip()??_.advancedSection),pb(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&ai("settings-health"),JR(n),Dr()}function J3(){window.addEventListener("codemem:navigate-advanced-sync",X3),zr.forEach(e=>{tt(`tabBtn-${e}`)?.addEventListener("click",()=>In(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),tt("syncTurnOnButton")?.addEventListener("click",()=>{$C("sync"),zC(zR)}),tt("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),xu("teams"),In("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),tt("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),xu("invitations"),In("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=rp();if(e){const t=ip();sd=db(),In(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),sd=db(),In(_.activeTab)}async function Y3(){try{const e=await ks();_.knownProjects=e,$3();const t=tp("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function Q3(e){_.pendingDeviceIdentityFocus=e?.trim()||null,In("devices",{canonicalHash:!0})}function X3(){In("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var cd=_E({},{onOpenTeamSetup:rC,onReviewDevices:Q3}),YR={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},ih=0,oh=null,Wt=null;async function Z3(e={}){const t=[];let n=0;for(;;){const r=await qo({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return Zs(t)}function eJ(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of _.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 tJ(){return _.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function nJ(e){if(e==="advanced_sync"){In("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){In("sharing",{canonicalHash:!0}),xu("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}In(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function ah(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=iJ(t,++ih,e);return oh=n,n}async function rJ(){const[e,t]=await Promise.all([ah(),cd()]);return e&&t}function QR(){return{localDeviceId:_.lastSyncStatus?.device_id??void 0,onCommitted:rJ,onNavigate:nJ,onRetry:()=>{ah()}}}async function iJ(e,t,n){Wt||al(e,YR,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([Z3(n),xd(n),Fk(n),Dd(n).then(p=>({inventory:p,unavailable:!1})).catch(()=>({inventory:Wt?.inventory,unavailable:!0})),id({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==ih)return oh??!1;const l=eJ(),d=tJ(),u=Zh(_.lastSyncStatus);return!s.unavailable&&s.inventory&&(_.lastDeviceIdentityInventory=s.inventory),_.deviceIdentityInventoryLoadError=s.unavailable,al(e,i,o,r,l,{...QR(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u,peerRuntimeMetadata:d}),Wt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:u},c}catch{return n.signal?.aborted?!1:t!==ih?oh??!1:(Wt?al(e,Wt.intent,Wt.reconciliation,Wt.projects,Wt.availability,{...QR(),coordinatorEnrollmentIssueCount:Wt.coordinatorEnrollmentIssueCount,inventory:Wt.inventory,inventoryUnavailable:Wt.inventoryUnavailable,peerRuntimeMetadata:Wt.peerRuntimeMetadata,refreshError:!0}):al(e,YR,{version:1,items:[]},[],[],{loadError:!0}),!1)}}tp("projectFilter")?.addEventListener("change",()=>{bs.cancel(),_.currentProject=tp("projectFilter")?.value||"",ai("scope"),wn(!0),Dr()});var jo=null;async function oJ(e){await Promise.all([JU({signal:e.signal}),_V({signal:e.signal}),Cx().catch(()=>{})])}function aJ(e,t,n,r){if(t!=="health"&&jS(),t==="feed"){const s=N$();e.push(O_(s,{signal:r.signal}),em({signal:r.signal}))}if(t==="projects"&&e.push(No({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(cd({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(ah({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(YU({signal:r.signal}),id({requiredSurface:"health",requireFreshSyncStatus:ad,signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="sync"&&e.push(id({signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="teams"&&e.push(nl({deferWhileRenaming:!0,signal:r.signal}).then(n)),!_.syncPairingOpen)return;const i=t==="advanced"&&_.advancedSection==="sync",o=M3({signal:r.signal});e.push(i?o.then(n):o)}async function Dr(){an||(jo&&clearTimeout(jo),jo=setTimeout(()=>ld(),80))}async function sJ(e,t){if(!t.isCurrent()&&!Rh(e))return;const n=await th();t.isOwned()&&(n?xr("error"):KR())}function cJ(e){bs.finish(e),_.refreshInFlight=!1,!(!_.refreshQueued||an||!nh())&&(_.refreshQueued=!1,ld())}async function ld(){if(an||!nh())return;if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;const e=bs.begin();try{xr("refreshing");const t=_.activeTab,n=VR(),r=[oJ(e)];let i=!0;if(aJ(r,t,s=>{i=i&&s},e),await Is(Promise.all(r),e.signal),!e.isCurrent()){if(Rh(e.signal.reason))throw e.signal.reason;return}HR(UR(_.lastSyncLegacySharedReview)),t==="feed"&&wn(!0);const o=ma(_.activeTab,_.lastCoordinatorAdminStatus);o!==_.activeTab&&pb(o),JR(_.activeTab),xr(i?"idle":"error"),K3({refreshSucceeded:i,surface:n})}catch(t){await sJ(t,e)}finally{cJ(e)}}j0();var XR=document.getElementById("toastRoot");XR&&w0(XR);var ZR=document.getElementById("diagnosticsDrawerMount");ZR&&Sx(ZR);var eI=document.getElementById("legacyTeamSetupMount");eI&&QG(eI,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(_.activeTab==="sharing"?(t=await No(n),e=await cd(n)):(e=await cd(n),t=await No(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var tI=document.getElementById("legacyUpgradeDialogMount");tI&&Px(tI,{onDismiss:G3,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),$0(bc("themeToggle")),gb(sp()),J3(),xq(),Rx(),ZH(()=>Dr(),{onOpenTeamSetup:rC}),B3(()=>Dr()),j$(),cK(zR,_s,()=>Dr()),Y3(),tt("viewerReconnectRetry")?.addEventListener("click",async()=>{if($u("reconnect_requested"),Ci(!0,"Checking whether the viewer server is back…"),!await th()){KR();return}Er&&(clearTimeout(Er),Er=null),an=!1,Ci(!0,"Viewer responded. Restoring your session…"),_s();try{await ld()}catch{}an||Ci(!1)}),U3(),V3(),Dr(),_s()})();
|
package/static/app.js.br
CHANGED
|
Binary file
|
package/static/app.js.gz
CHANGED
|
Binary file
|