@pi-chamber/web 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/assets/{DiagramView-DsCdfDOP.js → DiagramView-BB-aZobi.js} +1 -1
  2. package/dist/assets/{DiffView-BWo7yT-P.js → DiffView-BxW6BuOC.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-IFbuQCcP.js → FileSaveConflictDialog-Bzz8FNMq.js} +1 -1
  4. package/dist/assets/{FilesView-DLIQkVep.js → FilesView-DECxN8Z0.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-CxGg6x7R.js → GitHubDetailScaffold-CWsWycRd.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-BmqbTUpE.js → GitHubLinkPicker-BVYdg_e8.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-a1DxU6Zp.js → GitHubListPrimitives-Dlv3tC4d.js} +1 -1
  8. package/dist/assets/{GitView-DbqM8Qi1.js → GitView-DD33ngnM.js} +3 -3
  9. package/dist/assets/{IssuesSurface-B2EfICtZ.js → IssuesSurface-BAY_eyX5.js} +2 -2
  10. package/dist/assets/{JsonTreeView-DzVqgwz-.js → JsonTreeView-DpXbUrAl.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-7yTzCIEI.js → MarkdownRendererImpl-Cn63lAmn.js} +1 -1
  12. package/dist/assets/{PatchDiff-Dvfm6eOV.js → PatchDiff-BklyOEHs.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-ByYaUifK.js → PierreDiffViewer-wc6cB6qw.js} +1 -1
  14. package/dist/assets/{PullRequestsSurface-1IP_dDn8.js → PullRequestsSurface-BZvJkT1I.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-DVxWhG4x.js → SessionSwitcherContent-CscYekC1.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-DiBGmmtD.js → SessionSwitcherDropdown-DShvvGwC.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-qw67HcBO.js → SessionUnreadDot-CbqRq6h_.js} +1 -1
  18. package/dist/assets/{SettingsView-CMTIIpWD.js → SettingsView-DcF-At5E.js} +3 -3
  19. package/dist/assets/{SettingsWindow-DZUSs5Is.js → SettingsWindow-gxjULdm1.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-pgTNzNPN.js → ToolOutputDialog-DdMIfrnK.js} +1 -1
  21. package/dist/assets/{ToolPartDiffPreview-Cvnr4JkU.js → ToolPartDiffPreview-C6Sm4eVf.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-D8dSHI_H.js → VirtualizedFileDiff-BrbPymTL.js} +1 -1
  23. package/dist/assets/{collapsible-ZT74WYMA.js → collapsible-D6qdoq7-.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-g1aOl5nF.js → computeVirtualFileMetrics-G4csGiKs.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-IWdho_6z.js → contextFileOpenGuard-UU86YHgI.js} +1 -1
  26. package/dist/assets/{fileTreeStatus-trDHgX4B.js → fileTreeStatus-Bskhj4qT.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-CfBh9Rne.js → gitStatusPredicates-DQEO4Psc.js} +1 -1
  28. package/dist/assets/{githubLink-CuQ2WFBa.js → githubLink-ByPAyFjh.js} +1 -1
  29. package/dist/assets/{index-CK9t5Znh.js → index-ComwtfT4.js} +1 -1
  30. package/dist/assets/{index-fmzQmSSv.js → index-I2QYqABE.js} +3 -3
  31. package/dist/assets/{main-DOlk_lfi.js → main-DoiadX0a.js} +2 -2
  32. package/dist/assets/{main-UnRe9F68.js → main-DyFfbllq.js} +4 -4
  33. package/dist/assets/{markdownCore-DuZmdypZ.js → markdownCore-DczkEluO.js} +1 -1
  34. package/dist/assets/{miniChat-Dy9h0B6G.js → miniChat-Ck6MEZ9Q.js} +2 -2
  35. package/dist/assets/{mobile-CWrtn0Si.js → mobile-BucKVm1P.js} +2 -2
  36. package/dist/assets/{nativeFileSave-B4Rg6n8u.js → nativeFileSave-Cp9i5QGd.js} +1 -1
  37. package/dist/assets/{pi-session-focus-preference-q-s-Bhf0.js → pi-session-focus-preference-Dx0UXPoO.js} +1 -1
  38. package/dist/assets/{renderDiffWithHighlighter-HRnE6vfE.js → renderDiffWithHighlighter-PL82AR81.js} +1 -1
  39. package/dist/assets/{renderElectronMiniChatApp-OZ2fG5eY.js → renderElectronMiniChatApp-Cb7s7dWl.js} +2 -2
  40. package/dist/assets/{renderFileWithHighlighter-tJRUQWjE.js → renderFileWithHighlighter-CYgfbA4F.js} +1 -1
  41. package/dist/assets/{renderMobileApp-D1nkBJLP.js → renderMobileApp-Bp74b_Lo.js} +3 -3
  42. package/dist/assets/{runtimeEndpointReset-Bby2E_Je.js → runtimeEndpointReset-7nWYnKd4.js} +6 -6
  43. package/dist/assets/{runtimeSurface-X62LLBLv.js → runtimeSurface-CFwnvks_.js} +1 -1
  44. package/dist/assets/{useAppFontEffects-BFgKpDYT.js → useAppFontEffects-ZTyNwFk6.js} +85 -87
  45. package/dist/assets/{useGitHubRemoteSearch-MxC4J-VO.js → useGitHubRemoteSearch-BF3ohpsh.js} +1 -1
  46. package/dist/assets/{useSwitcherItems-D5TsQEbM.js → useSwitcherItems-BJzwyDGX.js} +1 -1
  47. package/dist/assets/{web-components-B_NMC-2c.js → web-components-CGDpzixf.js} +1 -1
  48. package/dist/index.html +3 -3
  49. package/dist/mini-chat.html +2 -2
  50. package/dist/mobile.html +2 -2
  51. package/package.json +1 -1
  52. package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
  53. package/server/lib/pi/session-daemon/extension-custom-host.js +37 -4
  54. package/server/lib/pi/session-daemon/extension-custom-host.test.js +231 -2
  55. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +55 -0
  56. package/server/lib/pi/session-daemon/session-daemon.js +18 -2
@@ -1 +1 @@
1
- import{j as e,bW as me,bX as he,bY as fe,bZ as pe,b_ as xe,aP as ge}from"./vendor-boot-3SaHYVb1.js";import{R as h}from"./vendor-react-Bz1tRBxM.js";import{f as H,j as be,p as je}from"./index-fmzQmSSv.js";import{B as N,I as G,ah as ye,t as K,cb as ve,cc as we,cd as Ne,cf as Ce,cg as ke,z as Se,A as I,bm as Re,a as Ge,bO as He,bN as Y,ee as Pe,a$ as J,b0 as ee,b1 as se,bT as Le,ef as O,b2 as Me,e1 as te,e2 as ne,dK as Ee,dL as Te,dM as De}from"./useAppFontEffects-BFgKpDYT.js";import{a6 as U,K as Fe,bb as ze,bc as Ie}from"./runtimeEndpointReset-Bby2E_Je.js";import{a as Be,G as re,b as $e,c as Ae,d as _e,e as Ke,f as Oe,g as qe,h as We}from"./GitHubListPrimitives-a1DxU6Zp.js";import{c as Ye}from"./vendor-zustand-CXhN0IMY.js";import{K as Ue,C as Ve,D as Qe}from"./GitHubDetailScaffold-CxGg6x7R.js";const ae=s=>s?s.kind==="rate-limited"?{reason:"rate-limited",retryAt:s.retryAt??null}:s.kind==="failed"?{reason:"failed",message:s.message}:{reason:s.reason,scopes:s.scopes??[]}:{reason:"failed",message:"GitHub request failed"},B=({command:s,label:t})=>{const i=h.useCallback(()=>{ye(s).then(a=>{K[a.ok?"success":"error"](a.ok?"Command copied":"Failed to copy command")}).catch(()=>K.error("Failed to copy command"))},[s]);return e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1.5",children:[e.jsx("code",{className:"min-w-0 truncate rounded bg-[var(--surface-muted)] px-1.5 py-0.5 font-mono typography-micro text-foreground",children:s}),e.jsx("button",{type:"button",onClick:i,className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-interactive-hover hover:text-foreground",title:t??`Copy ${s}`,"aria-label":t??`Copy ${s}`,children:e.jsx(G,{name:"file-copy",className:"size-3.5"})})]})},k=({icon:s,title:t,description:i,children:a})=>e.jsx(Be,{icon:s,title:t,description:i,action:a?e.jsx("div",{className:"mt-1 flex flex-wrap items-center justify-center gap-2",children:a}):void 0}),T=({info:s,onRetry:t,isRetrying:i})=>{const a=t?e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:t,disabled:i,children:[e.jsx(G,{name:"refresh",className:"size-3.5"}),i?"Checking…":"Check again"]}):null;switch(s.reason){case"gh-missing":return e.jsxs(k,{icon:"github-fill",title:"GitHub CLI not found",description:"Install the GitHub CLI on the machine running PiChamber to browse pull requests and issues.",children:[e.jsx(B,{command:"gh --version",label:"Copy gh version check"}),a]});case"gh-outdated":return e.jsxs(k,{icon:"github-fill",title:"GitHub CLI too old",description:"Update gh on the machine running PiChamber, then check again.",children:[e.jsx(B,{command:"gh upgrade",label:"Copy gh upgrade command"}),a]});case"gh-unauthenticated":return e.jsxs(k,{icon:"github-fill",title:"Not signed in",description:"Run gh auth login on the machine running PiChamber, then check again.",children:[e.jsx(B,{command:"gh auth login",label:"Copy gh auth login command"}),a]});case"not-github":return e.jsx(k,{icon:"git-repository",title:"Not a GitHub repository",description:"This directory is a git repository, but none of its remotes point at GitHub."});case"no-repository":return e.jsx(k,{icon:"git-repository",title:"No repository here",description:"Open a directory inside a git repository to browse pull requests and issues."});case"no-access":return e.jsx(k,{icon:"lock",title:"No access",description:"The signed-in GitHub account cannot access this repository. Check the remote and the account in Settings.",children:a});case"scope-missing":{const r=(s.scopes??[]).filter(Boolean),n=r.length>0?`gh auth refresh -s ${r.join(" ")}`:"gh auth refresh -s repo";return e.jsxs(k,{icon:"shield-keyhole",title:"Missing token scope",description:`The GitHub token needs ${r.length>0?r.join(", "):"more scope"}. Run this on the machine running PiChamber, then check again.`,children:[e.jsx(B,{command:n,label:"Copy gh auth refresh command"}),a]})}case"rate-limited":{const r=s.retryAt?new Date(s.retryAt).toLocaleTimeString():null;return e.jsx(k,{icon:"hourglass",title:"Rate limited",description:r?`GitHub rate limit reached. Try again after ${r}.`:"GitHub rate limit reached. Try again shortly.",children:a})}default:return e.jsx(k,{icon:"error-warning",title:"Something went wrong",description:s.message||"GitHub request failed",children:a})}},Xe=s=>s.map(t=>({host:t.host,owner:t.owner,repo:t.repo,relativePath:t.relativePath,kind:t.kind,submodule:t.submodule,disabledReason:t.disabledReason??null,ref:t.host&&t.owner&&t.repo?`${t.host}/${t.owner}/${t.repo}`:""})),Ze=s=>s.kind==="enclosing"?"enclosing":s.kind==="nested"?"nested":s.submodule?"submodule":null,V=({entries:s,value:t,onChange:i,ariaLabel:a})=>{const r=s.find(n=>n.ref===t)??null;return e.jsxs(ve,{value:t??"",onValueChange:i,children:[e.jsx(we,{size:"sm",className:"min-w-0 max-w-56","aria-label":a??"Select repository",children:e.jsx(Ne,{placeholder:"Select repository",children:n=>{const o=s.find(l=>l.ref===n)??r;return!o||!o.ref?"Select repository":e.jsxs("span",{className:"block truncate",children:[o.relativePath," · ",o.owner,"/",o.repo]})}})}),e.jsx(Ce,{children:s.map(n=>{const o=!n.ref||!!n.disabledReason,l=Ze(n);return e.jsx(ke,{value:n.ref,disabled:o,children:e.jsxs("span",{className:H("flex min-w-0 items-center gap-1.5",o&&"opacity-60"),children:[e.jsx(G,{name:"git-repository",className:"size-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:[n.relativePath," · ",n.owner&&n.repo?`${n.owner}/${n.repo}`:"not on GitHub"]}),l?e.jsx("span",{className:"shrink-0 rounded bg-[var(--surface-muted)] px-1 typography-micro text-muted-foreground",children:l}):null,n.disabledReason?e.jsxs("span",{className:"shrink-0 typography-micro text-muted-foreground",children:["· ",n.disabledReason]}):null]})},`${n.ref||n.relativePath}:${n.relativePath}`)})})]})},bs=({directory:s,isRefreshing:t,onRefresh:i,children:a})=>{const n=Se().github??null,o=I(p=>p.entriesByDirectory[be(s.trim())]??null),l=I(p=>p.ensureScope),c=I(p=>p.refreshScope),u=I(p=>p.setSelectedRepo),d=Re(s||null),m=U(p=>p.status),g=U(p=>p.refresh);h.useEffect(()=>{!s||!n||(l(s,n),g(n))},[s,n,l,g]);const C=h.useCallback(()=>{if(i){i();return}n&&(c(s,n,{force:!0}),g(n,{force:!0}))},[i,n,c,g,s]);if(!n)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:"failed",message:"GitHub is not available in this runtime."}})});if(o?.isLoading&&!o.scope&&!o.error)return e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx(re,{label:"Finding GitHub repositories"})});if(o?.error&&!o.scope)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:ae(o.error),onRetry:C,isRetrying:t||o.isLoading})});const y=o?.scope??null;if(y&&!m?.installed)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:"gh-missing"},onRetry:C,isRetrying:t})});const x=y?Xe(y.repositories):[],f=x.filter(p=>!!(p.ref&&!p.disabledReason));if(y&&f.length===0){const p=y.topLevel?"not-github":"no-repository";return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:p}})})}if(!d)return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2",children:e.jsx(V,{entries:x,value:d,onChange:p=>u(s,p)})}),e.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[e.jsx("div",{className:"typography-ui-header text-foreground",children:"Select a repository"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Several repositories are in scope. Pick one to browse."})]})]});const b=f.length>1;return e.jsxs("div",{className:"flex h-full flex-col",children:[b?e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2",children:e.jsx(V,{entries:x,value:d,onChange:p=>u(s,p)})}):null,e.jsx("div",{className:"min-h-0 flex-1",children:a({repo:d,directory:s})})]})},js=({copy:s,busy:t,destructive:i,disabled:a,disabledReason:r,label:n,variant:o="default",icon:l,onConfirm:c})=>{const[u,d]=h.useState(!1);return e.jsxs(me,{open:u,onOpenChange:m=>{t||d(m)},children:[e.jsxs(he,{render:e.jsx(N,{type:"button",variant:o,size:"xs",className:"shrink-0",disabled:a||t,title:r??n,"aria-label":n}),children:[l,n]}),e.jsx(fe,{children:e.jsx(pe,{side:"bottom",align:"start",sideOffset:6,collisionPadding:8,className:"z-50",children:e.jsxs(xe,{"aria-label":s.title,className:"w-64 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3 shadow-lg",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:s.title}),e.jsx("p",{className:"mt-1 typography-micro text-muted-foreground",children:s.detail}),e.jsxs("div",{className:"mt-3 flex justify-end gap-1.5",children:[e.jsx(N,{type:"button",variant:"outline",size:"xs",disabled:t,onClick:()=>d(!1),children:"Cancel"}),e.jsx(N,{type:"button",variant:i?"destructive":"default",size:"xs",disabled:t,onClick:()=>{Promise.resolve(c()).finally(()=>d(!1))},"aria-label":s.confirm,children:t?s.progress:s.confirm})]})]})})})]})},ys=async(s,t)=>{if(!t?.listGitWorktrees)return;const i=Ge.getState().projects,a=He(i,Y.getState()),n=Pe(i,a,s)?.path??s;try{await Y.getState().refreshProject(n,t,{force:!0})}catch{}},v=(s,t)=>`${s}#${t}`,ie=Object.freeze([]),Je=Object.freeze({comments:ie,summary:"",verdict:"comment",commentDraft:""});let Q=0;const es=()=>(Q+=1,`pending-review-comment-${Q}`),R=(s,t)=>s.entries[t]??Je,S=(s,t,i)=>({...s.entries,[t]:{...R(s,t),...i}}),P=Ye()((s,t)=>({entries:{},addComment:(i,a,r)=>{const n=r.id??es(),o=v(i,a);return s(l=>({entries:S(l,o,{comments:[...R(l,o).comments,{...r,id:n}]})})),n},removeComment:(i,a,r)=>{const n=v(i,a);s(o=>{const l=R(o,n).comments,c=l.filter(u=>u.id!==r);if(c.length===l.length)return o;if(c.length===0&&R(o,n).summary===""&&R(o,n).commentDraft===""){const u={...o.entries};return delete u[n],{entries:u}}return{entries:S(o,n,{comments:c})}})},removeComments:(i,a,r)=>{if(r.length===0)return;const n=v(i,a),o=new Set(r);s(l=>{const c=R(l,n).comments,u=c.filter(d=>!o.has(d.id));return u.length===c.length?l:{entries:S(l,n,{comments:u})}})},clearComments:(i,a)=>{const r=v(i,a);s(n=>(n.entries[r]?.comments.length??0)===0?n:{entries:S(n,r,{comments:[]})})},setSummary:(i,a,r)=>{const n=v(i,a);t().entries[n]?.summary!==r&&s(o=>({entries:S(o,n,{summary:r})}))},clearSummary:(i,a,r)=>{const n=v(i,a);s(o=>R(o,n).summary!==r?o:{entries:S(o,n,{summary:""})})},setVerdict:(i,a,r)=>{const n=v(i,a);t().entries[n]?.verdict!==r&&s(o=>({entries:S(o,n,{verdict:r})}))},setCommentDraft:(i,a,r)=>{const n=v(i,a);t().entries[n]?.commentDraft!==r&&s(o=>({entries:S(o,n,{commentDraft:r})}))},clearCommentDraft:(i,a)=>{const r=v(i,a);s(n=>R(n,r).commentDraft===""?n:{entries:S(n,r,{commentDraft:""})})},resetForRuntimeSwitch:()=>s({entries:{}})}));typeof window<"u"&&je(()=>{P.getState().resetForRuntimeSwitch()});const vs=(s,t)=>P(i=>i.entries[v(s,t)]?.comments??ie),ws=(s,t)=>P(i=>i.entries[v(s,t)]?.summary??""),Ns=(s,t)=>P(i=>i.entries[v(s,t)]?.verdict??"comment"),Cs=(s,t)=>P(i=>i.entries[v(s,t)]?.comments.length??0),ss=300,ks=(s,t)=>{const i=v(s,t),a=P(m=>m.entries[i]?.commentDraft??""),[r,n]=h.useState(a),o=h.useRef(r);o.current=r;const l=h.useRef(a);l.current=a;const c=h.useRef(a);h.useEffect(()=>{o.current===c.current&&a!==c.current&&(c.current=a,n(a))},[a]);const u=h.useCallback(()=>{const m=o.current;m!==c.current&&(c.current=m,P.getState().setCommentDraft(s,t,m))},[s,t]),d=h.useCallback(m=>{n(m)},[]);return h.useEffect(()=>{if(r===c.current)return;const m=setTimeout(u,ss);return()=>clearTimeout(m)},[r,u]),h.useEffect(()=>()=>u(),[u]),{draft:r,onDraftChange:d,flushDraft:u}},ts=240,Ss=({draft:s,onDraftChange:t,placeholder:i="Leave a comment",ariaLabel:a="Leave a comment",busy:r,error:n,disabledReason:o,followUp:l,onSubmitComment:c,onDraftBlur:u})=>{const d=h.useRef(null),[m,g]=h.useState(!1),C=h.useRef(null);h.useLayoutEffect(()=>{const f=d.current;if(!f)return;f.style.height="0px",f.style.height=`${Math.min(f.scrollHeight,ts)}px`;let b=C.current;if(!b){const w=getComputedStyle(f);b={lineHeight:Number.parseFloat(w.lineHeight)||20,padding:Number.parseFloat(w.paddingTop)+Number.parseFloat(w.paddingBottom)||0},C.current=b}const p=f.scrollHeight-b.padding>b.lineHeight*1.5;g(w=>w===p?w:p)},[s]);const y=s.trim().length===0,x=r!==null;return e.jsxs("form",{className:"flex flex-col gap-2 border-t border-border/60 pt-5","aria-label":a,onSubmit:f=>{f.preventDefault(),c()},children:[e.jsxs("div",{className:`flex ${m?"items-end":"items-center"} gap-1.5 rounded-md border border-border bg-[var(--surface-elevated)] py-1 pr-1 focus-within:border-[var(--interactive-focus-ring)]`,children:[e.jsx(Fe,{simple:!0,ref:d,rows:1,value:s,placeholder:`${i} (⌘↩)`,"aria-label":a,disabled:x,onChange:f=>t(f.target.value),onBlur:()=>u?.(),outerClassName:"min-w-0 flex-1",className:"min-h-0 w-full resize-none overflow-y-auto border-0 bg-transparent px-2.5 py-1 typography-ui text-foreground shadow-none outline-none placeholder:text-muted-foreground focus-visible:ring-0",onKeyDown:f=>{f.nativeEvent.isComposing||f.key==="Enter"&&(f.metaKey||f.ctrlKey)&&!f.shiftKey&&!f.altKey&&!f.repeat&&(f.preventDefault(),f.stopPropagation(),!y&&!x&&c())}}),!y&&l&&l.allowed?e.jsx(N,{type:"button",variant:"ghost",size:"xs",disabled:x,title:l.reason??l.label,onClick:l.onRun,children:r===l.id?l.busyLabel:l.label}):null,e.jsx(N,{type:"button",variant:"default",size:"xs",disabled:y||x,title:o??"Post comment",onClick:c,children:r==="comment"?"Posting…":"Comment"})]}),n?e.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:n}):null]})},ns=async s=>{const t=s.notify??((r,n)=>K[r](n)),i=await s.postComment(s.trimmed);if(!i.ok){const r=i.error?.kind==="failed"&&i.error.message?i.error.message:"Failed to post comment";throw t("error",r),new Error(r)}if(s.afterPost(),s.action==="comment"){t("success","Comment posted");return}const a=await s.runFollowUp(s.action);if(!a.ok){const r=s.verbs[s.action],n=a.error?.kind==="failed"&&a.error.message?a.error.message:`Failed to ${r}`;throw t("error",n),new Error(n)}t("success",s.doneLabels[s.action])},Rs=s=>{const[t,i]=h.useState(null),[a,r]=h.useState(null),n=h.useRef(s);n.current=s;const o=h.useCallback(async(l,c)=>{const u=c.trim(),d=n.current;if(!(u.length===0||t!==null)){i(l),r(null);try{await ns({trimmed:u,action:l,postComment:d.postComment,runFollowUp:d.runFollowUp,verbs:d.verbs,doneLabels:d.doneLabels,afterPost:d.afterPost})}catch(m){r(m instanceof Error?m.message:"Failed to post comment")}finally{i(null)}}},[t]);return{busy:t,error:a,submit:o}},X=({label:s,value:t,options:i,currentLabel:a,onChange:r})=>e.jsxs(Ee,{children:[e.jsxs(Te,{children:[e.jsx("span",{className:"flex-1",children:s}),e.jsx("span",{className:"min-w-0 max-w-32 truncate typography-micro text-muted-foreground",children:a})]}),e.jsx(De,{className:"min-w-48",children:e.jsxs(te,{value:t,onValueChange:n=>{typeof n=="string"&&n!==t&&r(n)},children:[e.jsx(O,{children:s}),i.map(n=>e.jsx(ne,{value:n.id,closeOnClick:!1,children:n.label},n.id))]})})]}),rs=({stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l})=>{const c=t.find(g=>g.id===s)?.label??s,u=r.find(g=>g.id===a)?.label??a,d=(o??"").trim().length>0,m=(s!==t[0]?.id?1:0)+(a!==r[0]?.id?1:0)+(d?1:0);return e.jsxs(J,{modal:!1,children:[e.jsx(ee,{asChild:!0,children:e.jsxs(N,{type:"button",variant:"ghost",size:"sm","aria-label":"Filters",title:"Filters",className:"h-8 shrink-0 gap-1.5 px-2 normal-case",children:[e.jsx(G,{name:"equalizer",className:"size-4","aria-hidden":"true"}),e.jsx("span",{children:"Filters"}),m>0?e.jsx("span",{className:"rounded-full bg-[var(--surface-muted)] px-1.5 typography-micro tabular-nums text-muted-foreground",children:m}):null]})}),e.jsxs(se,{align:"end",className:"w-64",children:[e.jsx(X,{label:"State",value:s,options:t,currentLabel:c,onChange:i}),e.jsx(X,{label:"Involvement",value:a,options:r,currentLabel:u,onChange:n}),l?e.jsxs(e.Fragment,{children:[e.jsx(Le,{}),e.jsx(O,{children:"Labels"}),e.jsxs("div",{className:"px-2 pb-2",children:[e.jsx(Me,{value:o??"",onChange:g=>l(g.target.value),placeholder:"bug, enhancement","aria-label":"Filter by labels",className:"h-7"}),e.jsx("p",{className:"mt-1 typography-micro text-muted-foreground",children:"Comma-separated. Or type label:bug in search."})]})]}):null]})]})},as=({value:s,options:t,onChange:i,ariaLabel:a})=>e.jsxs(J,{modal:!1,children:[e.jsx(ee,{asChild:!0,children:e.jsx(N,{type:"button",variant:"ghost",size:"sm","aria-label":a,title:a,className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"expand-up-down",className:"size-4","aria-hidden":"true"})})}),e.jsx(se,{align:"end",className:"w-52",children:e.jsxs(te,{value:s,onValueChange:r=>{typeof r=="string"&&r!==s&&i(r)},children:[e.jsx(O,{children:"Sort"}),t.map(r=>e.jsx(ne,{value:r.id,children:r.label},r.id))]})})]}),Z=({isRefreshing:s,onRefresh:t,label:i,presentation:a="toolbar"})=>a==="desktop"?e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}):a==="drawer"?e.jsx(N,{type:"button",variant:"ghost",size:"icon",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"shrink-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}):e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}),Gs=({items:s,renderRow:t,hasMore:i,isLoadingMore:a,isLoading:r,isRefreshing:n,stale:o,error:l,searchValue:c,onSearchChange:u,searchPlaceholder:d,searchAriaLabel:m,toolbarControls:g,primaryAction:C,headerActionsSlot:y=null,headerActionsPresentation:x="drawer",isDefaultFilters:f,noItemsTitle:b,noItemsBody:p,noItemsIcon:w,noItemsAction:D,listAriaLabel:L,skeletonLabel:$,incompleteNotice:M=null,remote:j=null,numberJump:F=null,numberJumpKind:oe,onClearFilters:le,onLoadMore:ce,onRetry:z,onOpen:ue})=>{const A=!!l&&s.length===0,q=!A&&r&&s.length===0,_=y??null,de=x??"drawer",W=n||r;return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o?e.jsx($e,{onRetry:z}):null,e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border px-3 py-2",children:[e.jsx(Ae,{value:c,onChange:u,placeholder:d,ariaLabel:m}),g,_?null:e.jsxs(e.Fragment,{children:[C,e.jsx(Z,{isRefreshing:W,onRefresh:z,presentation:"toolbar"})]})]}),_?ge.createPortal(e.jsxs(e.Fragment,{children:[C,e.jsx(Z,{isRefreshing:W,onRefresh:z,presentation:de})]}),_):null,A?e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(T,{info:ae(l),onRetry:z,isRetrying:r})}):q?e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e.jsx(re,{label:$})}):e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",role:"list","aria-label":L,children:[s.length===0&&F==null?e.jsx(_e,{kind:f?"no-items":"no-match",noItemsTitle:b,noItemsBody:f?p:void 0,noItemsIcon:w,noItemsAction:f?D:void 0,onClearFilters:f?void 0:le}):e.jsxs(e.Fragment,{children:[s.length>0?e.jsx("ul",{className:"flex flex-col p-1",children:s.map(E=>e.jsx(h.Fragment,{children:t(E)},E.number))}):null,F!=null?e.jsx(Ke,{number:F,kindLabel:oe,onOpen:()=>ue(F)}):null]}),e.jsx(Oe,{hasMore:i,isLoading:a||r,onLoadMore:ce}),j&&(j.isSearching||j.error||j.items.length>0)?e.jsx(qe,{title:"More results from GitHub",isSearching:j.isSearching,error:j.error,hasResults:j.items.length>0,hasMore:j.hasMore,isLoadingMore:j.isLoadingMore,onRetry:j.onRetry,onLoadMore:j.onLoadMore,children:e.jsx("ul",{className:"flex flex-col",children:j.items.map(E=>e.jsx(h.Fragment,{children:t(E)},E.number))})}):null]}),!A&&!q&&M?e.jsx(We,{matchSummary:M.summary,searching:M.searching,onSearchAll:M.onSearchAll}):null]})},Hs=({stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l,sortValue:c,sortOptions:u,onSortChange:d,sortAriaLabel:m})=>e.jsxs(e.Fragment,{children:[e.jsx(rs,{stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l}),e.jsx(as,{value:c,options:u,onChange:d,ariaLabel:m})]}),is="shrink-0 font-mono typography-micro tabular-nums text-muted-foreground",os=({glyph:s,below:t})=>e.jsxs("span",{className:"flex w-4 shrink-0 flex-col items-center gap-0.5",children:[e.jsx("span",{className:"inline-flex",children:s}),t?e.jsx("span",{className:"inline-flex",children:t}):null]}),Ps=({login:s,avatarUrl:t})=>e.jsxs("span",{className:"inline-flex min-w-0 shrink-0 items-center gap-1",title:s??"ghost",children:[e.jsx(Ve,{login:s,avatarUrl:t,size:"xs"}),e.jsx("span",{className:"truncate",children:s??"ghost"})]}),Ls=({head:s,base:t})=>e.jsxs("span",{className:"flex min-w-0 items-center gap-1 font-mono",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",title:s,children:s}),e.jsx("span",{className:"shrink-0",children:"→"}),e.jsx("span",{className:"max-w-[45%] shrink-0 truncate",title:t,children:t})]}),ls=[{show:""},{show:"hidden @xl/github-row:inline-flex"},{show:"hidden @3xl/github-row:inline-flex"}],cs=["hidden @xl/github-row:hidden","hidden @xl/github-row:inline-flex @3xl/github-row:hidden",""],Ms=({labels:s})=>s.length===0?null:e.jsx("span",{className:"flex min-w-0 shrink-0 items-center gap-1",children:ls.map((t,i)=>{const a=s[i];if(!a)return null;const r=s.length-i-1;return e.jsxs("span",{className:H("min-w-0",t.show),children:[e.jsx(Qe,{name:a.name,color:a.color}),r>0?e.jsxs("span",{className:H("ml-0.5 shrink-0",cs[i]),"aria-label":`${r} more labels`,children:["+",r]}):null]},a.name)})}),Es=({glyph:s,glyphBelow:t,number:i,title:a,signals:r,status:n,meta:o,updatedAt:l,selected:c,onOpen:u,ariaLabel:d})=>e.jsxs("button",{type:"button",onClick:u,"aria-label":d,"aria-current":c?"true":void 0,className:H("@container/github-row group/github-row flex w-full items-center gap-2 rounded-md px-2 py-1 text-left",c?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:[e.jsx(os,{glyph:s,below:t}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:is,children:i}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:a,children:a}),r?e.jsx("span",{className:"flex shrink-0 items-center gap-1",children:r}):null,n?e.jsx("span",{className:"ml-auto flex shrink-0 items-center gap-1.5",children:n}):null]}),e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[o,l?e.jsx("span",{className:"ml-auto shrink-0 whitespace-nowrap tabular-nums",children:Ue(l)}):null]})]})]}),Ts=s=>{const{repo:t,query:i,queryKey:a,autoRemote:r,indexNumbers:n,visibleItems:o,searchText:l,useRemoteEntry:c,runSearch:u,runLoadMore:d}=s,[m,g]=h.useState(!1),[C,y]=h.useState(null);h.useEffect(()=>y(null),[t]);const x=c(t,i),f=r||C===a||x!=null,b=h.useCallback(()=>{g(!0),u(i).catch(()=>null).finally(()=>g(!1))},[i,u]);h.useEffect(()=>{if(!r||x?.data||x?.isLoading||x?.error||m)return;const j=setTimeout(b,400);return()=>clearTimeout(j)},[r,a,x?.data,x?.isLoading,x?.error,m,b]);const p=h.useCallback(()=>{y(a),b()},[a,b]),w=h.useCallback(()=>{g(!0),d(i).catch(()=>null).finally(()=>g(!1))},[i,d]),D=h.useMemo(()=>ze(x?.data?.items??[],n),[x?.data?.items,n]),L=Ie(l),$=L!=null&&!o.some(j=>j.number===L)?L:null;return{remoteView:h.useMemo(()=>f?{items:D,isSearching:m||(x?.isLoading??!1),isLoadingMore:m,hasMore:x?.data?.nextCursor!=null,error:x?.error??null,onSearchAll:p,onLoadMore:w,onRetry:b}:null,[f,D,m,x?.isLoading,x?.data?.nextCursor,x?.error,p,w,b]),numberJump:$,remotePending:m,handleSearchAll:p}};export{Ss as G,vs as a,ks as b,Rs as c,ws as d,Ns as e,Cs as f,T as g,js as h,Es as i,Ps as j,Ls as k,Gs as l,Hs as m,bs as n,Ts as o,Ms as p,ys as r,ae as t,P as u};
1
+ import{j as e,bW as me,bX as he,bY as fe,bZ as pe,b_ as xe,aP as ge}from"./vendor-boot-3SaHYVb1.js";import{R as h}from"./vendor-react-Bz1tRBxM.js";import{f as H,j as be,p as je}from"./index-I2QYqABE.js";import{B as N,I as G,ah as ye,t as K,cb as ve,cc as we,cd as Ne,cf as Ce,cg as ke,z as Se,A as I,bm as Re,a as Ge,bO as He,bN as Y,ee as Pe,a$ as J,b0 as ee,b1 as se,bT as Le,ef as O,b2 as Me,e1 as te,e2 as ne,dK as Ee,dL as Te,dM as De}from"./useAppFontEffects-ZTyNwFk6.js";import{a6 as U,K as Fe,bb as ze,bc as Ie}from"./runtimeEndpointReset-7nWYnKd4.js";import{a as Be,G as re,b as $e,c as Ae,d as _e,e as Ke,f as Oe,g as qe,h as We}from"./GitHubListPrimitives-Dlv3tC4d.js";import{c as Ye}from"./vendor-zustand-CXhN0IMY.js";import{K as Ue,C as Ve,D as Qe}from"./GitHubDetailScaffold-CWsWycRd.js";const ae=s=>s?s.kind==="rate-limited"?{reason:"rate-limited",retryAt:s.retryAt??null}:s.kind==="failed"?{reason:"failed",message:s.message}:{reason:s.reason,scopes:s.scopes??[]}:{reason:"failed",message:"GitHub request failed"},B=({command:s,label:t})=>{const i=h.useCallback(()=>{ye(s).then(a=>{K[a.ok?"success":"error"](a.ok?"Command copied":"Failed to copy command")}).catch(()=>K.error("Failed to copy command"))},[s]);return e.jsxs("span",{className:"inline-flex max-w-full items-center gap-1.5",children:[e.jsx("code",{className:"min-w-0 truncate rounded bg-[var(--surface-muted)] px-1.5 py-0.5 font-mono typography-micro text-foreground",children:s}),e.jsx("button",{type:"button",onClick:i,className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-interactive-hover hover:text-foreground",title:t??`Copy ${s}`,"aria-label":t??`Copy ${s}`,children:e.jsx(G,{name:"file-copy",className:"size-3.5"})})]})},k=({icon:s,title:t,description:i,children:a})=>e.jsx(Be,{icon:s,title:t,description:i,action:a?e.jsx("div",{className:"mt-1 flex flex-wrap items-center justify-center gap-2",children:a}):void 0}),T=({info:s,onRetry:t,isRetrying:i})=>{const a=t?e.jsxs(N,{type:"button",variant:"outline",size:"sm",onClick:t,disabled:i,children:[e.jsx(G,{name:"refresh",className:"size-3.5"}),i?"Checking…":"Check again"]}):null;switch(s.reason){case"gh-missing":return e.jsxs(k,{icon:"github-fill",title:"GitHub CLI not found",description:"Install the GitHub CLI on the machine running PiChamber to browse pull requests and issues.",children:[e.jsx(B,{command:"gh --version",label:"Copy gh version check"}),a]});case"gh-outdated":return e.jsxs(k,{icon:"github-fill",title:"GitHub CLI too old",description:"Update gh on the machine running PiChamber, then check again.",children:[e.jsx(B,{command:"gh upgrade",label:"Copy gh upgrade command"}),a]});case"gh-unauthenticated":return e.jsxs(k,{icon:"github-fill",title:"Not signed in",description:"Run gh auth login on the machine running PiChamber, then check again.",children:[e.jsx(B,{command:"gh auth login",label:"Copy gh auth login command"}),a]});case"not-github":return e.jsx(k,{icon:"git-repository",title:"Not a GitHub repository",description:"This directory is a git repository, but none of its remotes point at GitHub."});case"no-repository":return e.jsx(k,{icon:"git-repository",title:"No repository here",description:"Open a directory inside a git repository to browse pull requests and issues."});case"no-access":return e.jsx(k,{icon:"lock",title:"No access",description:"The signed-in GitHub account cannot access this repository. Check the remote and the account in Settings.",children:a});case"scope-missing":{const r=(s.scopes??[]).filter(Boolean),n=r.length>0?`gh auth refresh -s ${r.join(" ")}`:"gh auth refresh -s repo";return e.jsxs(k,{icon:"shield-keyhole",title:"Missing token scope",description:`The GitHub token needs ${r.length>0?r.join(", "):"more scope"}. Run this on the machine running PiChamber, then check again.`,children:[e.jsx(B,{command:n,label:"Copy gh auth refresh command"}),a]})}case"rate-limited":{const r=s.retryAt?new Date(s.retryAt).toLocaleTimeString():null;return e.jsx(k,{icon:"hourglass",title:"Rate limited",description:r?`GitHub rate limit reached. Try again after ${r}.`:"GitHub rate limit reached. Try again shortly.",children:a})}default:return e.jsx(k,{icon:"error-warning",title:"Something went wrong",description:s.message||"GitHub request failed",children:a})}},Xe=s=>s.map(t=>({host:t.host,owner:t.owner,repo:t.repo,relativePath:t.relativePath,kind:t.kind,submodule:t.submodule,disabledReason:t.disabledReason??null,ref:t.host&&t.owner&&t.repo?`${t.host}/${t.owner}/${t.repo}`:""})),Ze=s=>s.kind==="enclosing"?"enclosing":s.kind==="nested"?"nested":s.submodule?"submodule":null,V=({entries:s,value:t,onChange:i,ariaLabel:a})=>{const r=s.find(n=>n.ref===t)??null;return e.jsxs(ve,{value:t??"",onValueChange:i,children:[e.jsx(we,{size:"sm",className:"min-w-0 max-w-56","aria-label":a??"Select repository",children:e.jsx(Ne,{placeholder:"Select repository",children:n=>{const o=s.find(l=>l.ref===n)??r;return!o||!o.ref?"Select repository":e.jsxs("span",{className:"block truncate",children:[o.relativePath," · ",o.owner,"/",o.repo]})}})}),e.jsx(Ce,{children:s.map(n=>{const o=!n.ref||!!n.disabledReason,l=Ze(n);return e.jsx(ke,{value:n.ref,disabled:o,children:e.jsxs("span",{className:H("flex min-w-0 items-center gap-1.5",o&&"opacity-60"),children:[e.jsx(G,{name:"git-repository",className:"size-3.5 shrink-0"}),e.jsxs("span",{className:"min-w-0 truncate",children:[n.relativePath," · ",n.owner&&n.repo?`${n.owner}/${n.repo}`:"not on GitHub"]}),l?e.jsx("span",{className:"shrink-0 rounded bg-[var(--surface-muted)] px-1 typography-micro text-muted-foreground",children:l}):null,n.disabledReason?e.jsxs("span",{className:"shrink-0 typography-micro text-muted-foreground",children:["· ",n.disabledReason]}):null]})},`${n.ref||n.relativePath}:${n.relativePath}`)})})]})},bs=({directory:s,isRefreshing:t,onRefresh:i,children:a})=>{const n=Se().github??null,o=I(p=>p.entriesByDirectory[be(s.trim())]??null),l=I(p=>p.ensureScope),c=I(p=>p.refreshScope),u=I(p=>p.setSelectedRepo),d=Re(s||null),m=U(p=>p.status),g=U(p=>p.refresh);h.useEffect(()=>{!s||!n||(l(s,n),g(n))},[s,n,l,g]);const C=h.useCallback(()=>{if(i){i();return}n&&(c(s,n,{force:!0}),g(n,{force:!0}))},[i,n,c,g,s]);if(!n)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:"failed",message:"GitHub is not available in this runtime."}})});if(o?.isLoading&&!o.scope&&!o.error)return e.jsx("div",{className:"flex h-full min-h-0 flex-col",children:e.jsx(re,{label:"Finding GitHub repositories"})});if(o?.error&&!o.scope)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:ae(o.error),onRetry:C,isRetrying:t||o.isLoading})});const y=o?.scope??null;if(y&&!m?.installed)return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:"gh-missing"},onRetry:C,isRetrying:t})});const x=y?Xe(y.repositories):[],f=x.filter(p=>!!(p.ref&&!p.disabledReason));if(y&&f.length===0){const p=y.topLevel?"not-github":"no-repository";return e.jsx("div",{className:"flex h-full flex-col",children:e.jsx(T,{info:{reason:p}})})}if(!d)return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2",children:e.jsx(V,{entries:x,value:d,onChange:p=>u(s,p)})}),e.jsxs("div",{className:"flex flex-col items-start gap-2 p-4",children:[e.jsx("div",{className:"typography-ui-header text-foreground",children:"Select a repository"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Several repositories are in scope. Pick one to browse."})]})]});const b=f.length>1;return e.jsxs("div",{className:"flex h-full flex-col",children:[b?e.jsx("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-3 py-2",children:e.jsx(V,{entries:x,value:d,onChange:p=>u(s,p)})}):null,e.jsx("div",{className:"min-h-0 flex-1",children:a({repo:d,directory:s})})]})},js=({copy:s,busy:t,destructive:i,disabled:a,disabledReason:r,label:n,variant:o="default",icon:l,onConfirm:c})=>{const[u,d]=h.useState(!1);return e.jsxs(me,{open:u,onOpenChange:m=>{t||d(m)},children:[e.jsxs(he,{render:e.jsx(N,{type:"button",variant:o,size:"xs",className:"shrink-0",disabled:a||t,title:r??n,"aria-label":n}),children:[l,n]}),e.jsx(fe,{children:e.jsx(pe,{side:"bottom",align:"start",sideOffset:6,collisionPadding:8,className:"z-50",children:e.jsxs(xe,{"aria-label":s.title,className:"w-64 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3 shadow-lg",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:s.title}),e.jsx("p",{className:"mt-1 typography-micro text-muted-foreground",children:s.detail}),e.jsxs("div",{className:"mt-3 flex justify-end gap-1.5",children:[e.jsx(N,{type:"button",variant:"outline",size:"xs",disabled:t,onClick:()=>d(!1),children:"Cancel"}),e.jsx(N,{type:"button",variant:i?"destructive":"default",size:"xs",disabled:t,onClick:()=>{Promise.resolve(c()).finally(()=>d(!1))},"aria-label":s.confirm,children:t?s.progress:s.confirm})]})]})})})]})},ys=async(s,t)=>{if(!t?.listGitWorktrees)return;const i=Ge.getState().projects,a=He(i,Y.getState()),n=Pe(i,a,s)?.path??s;try{await Y.getState().refreshProject(n,t,{force:!0})}catch{}},v=(s,t)=>`${s}#${t}`,ie=Object.freeze([]),Je=Object.freeze({comments:ie,summary:"",verdict:"comment",commentDraft:""});let Q=0;const es=()=>(Q+=1,`pending-review-comment-${Q}`),R=(s,t)=>s.entries[t]??Je,S=(s,t,i)=>({...s.entries,[t]:{...R(s,t),...i}}),P=Ye()((s,t)=>({entries:{},addComment:(i,a,r)=>{const n=r.id??es(),o=v(i,a);return s(l=>({entries:S(l,o,{comments:[...R(l,o).comments,{...r,id:n}]})})),n},removeComment:(i,a,r)=>{const n=v(i,a);s(o=>{const l=R(o,n).comments,c=l.filter(u=>u.id!==r);if(c.length===l.length)return o;if(c.length===0&&R(o,n).summary===""&&R(o,n).commentDraft===""){const u={...o.entries};return delete u[n],{entries:u}}return{entries:S(o,n,{comments:c})}})},removeComments:(i,a,r)=>{if(r.length===0)return;const n=v(i,a),o=new Set(r);s(l=>{const c=R(l,n).comments,u=c.filter(d=>!o.has(d.id));return u.length===c.length?l:{entries:S(l,n,{comments:u})}})},clearComments:(i,a)=>{const r=v(i,a);s(n=>(n.entries[r]?.comments.length??0)===0?n:{entries:S(n,r,{comments:[]})})},setSummary:(i,a,r)=>{const n=v(i,a);t().entries[n]?.summary!==r&&s(o=>({entries:S(o,n,{summary:r})}))},clearSummary:(i,a,r)=>{const n=v(i,a);s(o=>R(o,n).summary!==r?o:{entries:S(o,n,{summary:""})})},setVerdict:(i,a,r)=>{const n=v(i,a);t().entries[n]?.verdict!==r&&s(o=>({entries:S(o,n,{verdict:r})}))},setCommentDraft:(i,a,r)=>{const n=v(i,a);t().entries[n]?.commentDraft!==r&&s(o=>({entries:S(o,n,{commentDraft:r})}))},clearCommentDraft:(i,a)=>{const r=v(i,a);s(n=>R(n,r).commentDraft===""?n:{entries:S(n,r,{commentDraft:""})})},resetForRuntimeSwitch:()=>s({entries:{}})}));typeof window<"u"&&je(()=>{P.getState().resetForRuntimeSwitch()});const vs=(s,t)=>P(i=>i.entries[v(s,t)]?.comments??ie),ws=(s,t)=>P(i=>i.entries[v(s,t)]?.summary??""),Ns=(s,t)=>P(i=>i.entries[v(s,t)]?.verdict??"comment"),Cs=(s,t)=>P(i=>i.entries[v(s,t)]?.comments.length??0),ss=300,ks=(s,t)=>{const i=v(s,t),a=P(m=>m.entries[i]?.commentDraft??""),[r,n]=h.useState(a),o=h.useRef(r);o.current=r;const l=h.useRef(a);l.current=a;const c=h.useRef(a);h.useEffect(()=>{o.current===c.current&&a!==c.current&&(c.current=a,n(a))},[a]);const u=h.useCallback(()=>{const m=o.current;m!==c.current&&(c.current=m,P.getState().setCommentDraft(s,t,m))},[s,t]),d=h.useCallback(m=>{n(m)},[]);return h.useEffect(()=>{if(r===c.current)return;const m=setTimeout(u,ss);return()=>clearTimeout(m)},[r,u]),h.useEffect(()=>()=>u(),[u]),{draft:r,onDraftChange:d,flushDraft:u}},ts=240,Ss=({draft:s,onDraftChange:t,placeholder:i="Leave a comment",ariaLabel:a="Leave a comment",busy:r,error:n,disabledReason:o,followUp:l,onSubmitComment:c,onDraftBlur:u})=>{const d=h.useRef(null),[m,g]=h.useState(!1),C=h.useRef(null);h.useLayoutEffect(()=>{const f=d.current;if(!f)return;f.style.height="0px",f.style.height=`${Math.min(f.scrollHeight,ts)}px`;let b=C.current;if(!b){const w=getComputedStyle(f);b={lineHeight:Number.parseFloat(w.lineHeight)||20,padding:Number.parseFloat(w.paddingTop)+Number.parseFloat(w.paddingBottom)||0},C.current=b}const p=f.scrollHeight-b.padding>b.lineHeight*1.5;g(w=>w===p?w:p)},[s]);const y=s.trim().length===0,x=r!==null;return e.jsxs("form",{className:"flex flex-col gap-2 border-t border-border/60 pt-5","aria-label":a,onSubmit:f=>{f.preventDefault(),c()},children:[e.jsxs("div",{className:`flex ${m?"items-end":"items-center"} gap-1.5 rounded-md border border-border bg-[var(--surface-elevated)] py-1 pr-1 focus-within:border-[var(--interactive-focus-ring)]`,children:[e.jsx(Fe,{simple:!0,ref:d,rows:1,value:s,placeholder:`${i} (⌘↩)`,"aria-label":a,disabled:x,onChange:f=>t(f.target.value),onBlur:()=>u?.(),outerClassName:"min-w-0 flex-1",className:"min-h-0 w-full resize-none overflow-y-auto border-0 bg-transparent px-2.5 py-1 typography-ui text-foreground shadow-none outline-none placeholder:text-muted-foreground focus-visible:ring-0",onKeyDown:f=>{f.nativeEvent.isComposing||f.key==="Enter"&&(f.metaKey||f.ctrlKey)&&!f.shiftKey&&!f.altKey&&!f.repeat&&(f.preventDefault(),f.stopPropagation(),!y&&!x&&c())}}),!y&&l&&l.allowed?e.jsx(N,{type:"button",variant:"ghost",size:"xs",disabled:x,title:l.reason??l.label,onClick:l.onRun,children:r===l.id?l.busyLabel:l.label}):null,e.jsx(N,{type:"button",variant:"default",size:"xs",disabled:y||x,title:o??"Post comment",onClick:c,children:r==="comment"?"Posting…":"Comment"})]}),n?e.jsx("p",{className:"typography-micro text-[var(--status-error)]",role:"alert",children:n}):null]})},ns=async s=>{const t=s.notify??((r,n)=>K[r](n)),i=await s.postComment(s.trimmed);if(!i.ok){const r=i.error?.kind==="failed"&&i.error.message?i.error.message:"Failed to post comment";throw t("error",r),new Error(r)}if(s.afterPost(),s.action==="comment"){t("success","Comment posted");return}const a=await s.runFollowUp(s.action);if(!a.ok){const r=s.verbs[s.action],n=a.error?.kind==="failed"&&a.error.message?a.error.message:`Failed to ${r}`;throw t("error",n),new Error(n)}t("success",s.doneLabels[s.action])},Rs=s=>{const[t,i]=h.useState(null),[a,r]=h.useState(null),n=h.useRef(s);n.current=s;const o=h.useCallback(async(l,c)=>{const u=c.trim(),d=n.current;if(!(u.length===0||t!==null)){i(l),r(null);try{await ns({trimmed:u,action:l,postComment:d.postComment,runFollowUp:d.runFollowUp,verbs:d.verbs,doneLabels:d.doneLabels,afterPost:d.afterPost})}catch(m){r(m instanceof Error?m.message:"Failed to post comment")}finally{i(null)}}},[t]);return{busy:t,error:a,submit:o}},X=({label:s,value:t,options:i,currentLabel:a,onChange:r})=>e.jsxs(Ee,{children:[e.jsxs(Te,{children:[e.jsx("span",{className:"flex-1",children:s}),e.jsx("span",{className:"min-w-0 max-w-32 truncate typography-micro text-muted-foreground",children:a})]}),e.jsx(De,{className:"min-w-48",children:e.jsxs(te,{value:t,onValueChange:n=>{typeof n=="string"&&n!==t&&r(n)},children:[e.jsx(O,{children:s}),i.map(n=>e.jsx(ne,{value:n.id,closeOnClick:!1,children:n.label},n.id))]})})]}),rs=({stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l})=>{const c=t.find(g=>g.id===s)?.label??s,u=r.find(g=>g.id===a)?.label??a,d=(o??"").trim().length>0,m=(s!==t[0]?.id?1:0)+(a!==r[0]?.id?1:0)+(d?1:0);return e.jsxs(J,{modal:!1,children:[e.jsx(ee,{asChild:!0,children:e.jsxs(N,{type:"button",variant:"ghost",size:"sm","aria-label":"Filters",title:"Filters",className:"h-8 shrink-0 gap-1.5 px-2 normal-case",children:[e.jsx(G,{name:"equalizer",className:"size-4","aria-hidden":"true"}),e.jsx("span",{children:"Filters"}),m>0?e.jsx("span",{className:"rounded-full bg-[var(--surface-muted)] px-1.5 typography-micro tabular-nums text-muted-foreground",children:m}):null]})}),e.jsxs(se,{align:"end",className:"w-64",children:[e.jsx(X,{label:"State",value:s,options:t,currentLabel:c,onChange:i}),e.jsx(X,{label:"Involvement",value:a,options:r,currentLabel:u,onChange:n}),l?e.jsxs(e.Fragment,{children:[e.jsx(Le,{}),e.jsx(O,{children:"Labels"}),e.jsxs("div",{className:"px-2 pb-2",children:[e.jsx(Me,{value:o??"",onChange:g=>l(g.target.value),placeholder:"bug, enhancement","aria-label":"Filter by labels",className:"h-7"}),e.jsx("p",{className:"mt-1 typography-micro text-muted-foreground",children:"Comma-separated. Or type label:bug in search."})]})]}):null]})]})},as=({value:s,options:t,onChange:i,ariaLabel:a})=>e.jsxs(J,{modal:!1,children:[e.jsx(ee,{asChild:!0,children:e.jsx(N,{type:"button",variant:"ghost",size:"sm","aria-label":a,title:a,className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"expand-up-down",className:"size-4","aria-hidden":"true"})})}),e.jsx(se,{align:"end",className:"w-52",children:e.jsxs(te,{value:s,onValueChange:r=>{typeof r=="string"&&r!==s&&i(r)},children:[e.jsx(O,{children:"Sort"}),t.map(r=>e.jsx(ne,{value:r.id,children:r.label},r.id))]})})]}),Z=({isRefreshing:s,onRefresh:t,label:i,presentation:a="toolbar"})=>a==="desktop"?e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}):a==="drawer"?e.jsx(N,{type:"button",variant:"ghost",size:"icon",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"shrink-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}):e.jsx(N,{type:"button",variant:"ghost",size:"sm",onClick:t,disabled:s,title:i??"Refresh","aria-label":i??"Refresh GitHub data",className:"h-8 w-8 shrink-0 p-0",children:e.jsx(G,{name:"refresh",className:H("size-4",s&&"animate-spin"),"aria-hidden":"true"})}),Gs=({items:s,renderRow:t,hasMore:i,isLoadingMore:a,isLoading:r,isRefreshing:n,stale:o,error:l,searchValue:c,onSearchChange:u,searchPlaceholder:d,searchAriaLabel:m,toolbarControls:g,primaryAction:C,headerActionsSlot:y=null,headerActionsPresentation:x="drawer",isDefaultFilters:f,noItemsTitle:b,noItemsBody:p,noItemsIcon:w,noItemsAction:D,listAriaLabel:L,skeletonLabel:$,incompleteNotice:M=null,remote:j=null,numberJump:F=null,numberJumpKind:oe,onClearFilters:le,onLoadMore:ce,onRetry:z,onOpen:ue})=>{const A=!!l&&s.length===0,q=!A&&r&&s.length===0,_=y??null,de=x??"drawer",W=n||r;return e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[o?e.jsx($e,{onRetry:z}):null,e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1.5 border-b border-border px-3 py-2",children:[e.jsx(Ae,{value:c,onChange:u,placeholder:d,ariaLabel:m}),g,_?null:e.jsxs(e.Fragment,{children:[C,e.jsx(Z,{isRefreshing:W,onRefresh:z,presentation:"toolbar"})]})]}),_?ge.createPortal(e.jsxs(e.Fragment,{children:[C,e.jsx(Z,{isRefreshing:W,onRefresh:z,presentation:de})]}),_):null,A?e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(T,{info:ae(l),onRetry:z,isRetrying:r})}):q?e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:e.jsx(re,{label:$})}):e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",role:"list","aria-label":L,children:[s.length===0&&F==null?e.jsx(_e,{kind:f?"no-items":"no-match",noItemsTitle:b,noItemsBody:f?p:void 0,noItemsIcon:w,noItemsAction:f?D:void 0,onClearFilters:f?void 0:le}):e.jsxs(e.Fragment,{children:[s.length>0?e.jsx("ul",{className:"flex flex-col p-1",children:s.map(E=>e.jsx(h.Fragment,{children:t(E)},E.number))}):null,F!=null?e.jsx(Ke,{number:F,kindLabel:oe,onOpen:()=>ue(F)}):null]}),e.jsx(Oe,{hasMore:i,isLoading:a||r,onLoadMore:ce}),j&&(j.isSearching||j.error||j.items.length>0)?e.jsx(qe,{title:"More results from GitHub",isSearching:j.isSearching,error:j.error,hasResults:j.items.length>0,hasMore:j.hasMore,isLoadingMore:j.isLoadingMore,onRetry:j.onRetry,onLoadMore:j.onLoadMore,children:e.jsx("ul",{className:"flex flex-col",children:j.items.map(E=>e.jsx(h.Fragment,{children:t(E)},E.number))})}):null]}),!A&&!q&&M?e.jsx(We,{matchSummary:M.summary,searching:M.searching,onSearchAll:M.onSearchAll}):null]})},Hs=({stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l,sortValue:c,sortOptions:u,onSortChange:d,sortAriaLabel:m})=>e.jsxs(e.Fragment,{children:[e.jsx(rs,{stateValue:s,stateOptions:t,onStateChange:i,involvementValue:a,involvementOptions:r,onInvolvementChange:n,labelsValue:o,onLabelsChange:l}),e.jsx(as,{value:c,options:u,onChange:d,ariaLabel:m})]}),is="shrink-0 font-mono typography-micro tabular-nums text-muted-foreground",os=({glyph:s,below:t})=>e.jsxs("span",{className:"flex w-4 shrink-0 flex-col items-center gap-0.5",children:[e.jsx("span",{className:"inline-flex",children:s}),t?e.jsx("span",{className:"inline-flex",children:t}):null]}),Ps=({login:s,avatarUrl:t})=>e.jsxs("span",{className:"inline-flex min-w-0 shrink-0 items-center gap-1",title:s??"ghost",children:[e.jsx(Ve,{login:s,avatarUrl:t,size:"xs"}),e.jsx("span",{className:"truncate",children:s??"ghost"})]}),Ls=({head:s,base:t})=>e.jsxs("span",{className:"flex min-w-0 items-center gap-1 font-mono",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",title:s,children:s}),e.jsx("span",{className:"shrink-0",children:"→"}),e.jsx("span",{className:"max-w-[45%] shrink-0 truncate",title:t,children:t})]}),ls=[{show:""},{show:"hidden @xl/github-row:inline-flex"},{show:"hidden @3xl/github-row:inline-flex"}],cs=["hidden @xl/github-row:hidden","hidden @xl/github-row:inline-flex @3xl/github-row:hidden",""],Ms=({labels:s})=>s.length===0?null:e.jsx("span",{className:"flex min-w-0 shrink-0 items-center gap-1",children:ls.map((t,i)=>{const a=s[i];if(!a)return null;const r=s.length-i-1;return e.jsxs("span",{className:H("min-w-0",t.show),children:[e.jsx(Qe,{name:a.name,color:a.color}),r>0?e.jsxs("span",{className:H("ml-0.5 shrink-0",cs[i]),"aria-label":`${r} more labels`,children:["+",r]}):null]},a.name)})}),Es=({glyph:s,glyphBelow:t,number:i,title:a,signals:r,status:n,meta:o,updatedAt:l,selected:c,onOpen:u,ariaLabel:d})=>e.jsxs("button",{type:"button",onClick:u,"aria-label":d,"aria-current":c?"true":void 0,className:H("@container/github-row group/github-row flex w-full items-center gap-2 rounded-md px-2 py-1 text-left",c?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:[e.jsx(os,{glyph:s,below:t}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:is,children:i}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:a,children:a}),r?e.jsx("span",{className:"flex shrink-0 items-center gap-1",children:r}):null,n?e.jsx("span",{className:"ml-auto flex shrink-0 items-center gap-1.5",children:n}):null]}),e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[o,l?e.jsx("span",{className:"ml-auto shrink-0 whitespace-nowrap tabular-nums",children:Ue(l)}):null]})]})]}),Ts=s=>{const{repo:t,query:i,queryKey:a,autoRemote:r,indexNumbers:n,visibleItems:o,searchText:l,useRemoteEntry:c,runSearch:u,runLoadMore:d}=s,[m,g]=h.useState(!1),[C,y]=h.useState(null);h.useEffect(()=>y(null),[t]);const x=c(t,i),f=r||C===a||x!=null,b=h.useCallback(()=>{g(!0),u(i).catch(()=>null).finally(()=>g(!1))},[i,u]);h.useEffect(()=>{if(!r||x?.data||x?.isLoading||x?.error||m)return;const j=setTimeout(b,400);return()=>clearTimeout(j)},[r,a,x?.data,x?.isLoading,x?.error,m,b]);const p=h.useCallback(()=>{y(a),b()},[a,b]),w=h.useCallback(()=>{g(!0),d(i).catch(()=>null).finally(()=>g(!1))},[i,d]),D=h.useMemo(()=>ze(x?.data?.items??[],n),[x?.data?.items,n]),L=Ie(l),$=L!=null&&!o.some(j=>j.number===L)?L:null;return{remoteView:h.useMemo(()=>f?{items:D,isSearching:m||(x?.isLoading??!1),isLoadingMore:m,hasMore:x?.data?.nextCursor!=null,error:x?.error??null,onSearchAll:p,onLoadMore:w,onRetry:b}:null,[f,D,m,x?.isLoading,x?.data?.nextCursor,x?.error,p,w,b]),numberJump:$,remotePending:m,handleSearchAll:p}};export{Ss as G,vs as a,ks as b,Rs as c,ws as d,Ns as e,Cs as f,T as g,js as h,Es as i,Ps as j,Ls as k,Gs as l,Hs as m,bs as n,Ts as o,Ms as p,ys as r,ae as t,P as u};
@@ -1 +1 @@
1
- import{R as f}from"./vendor-react-Bz1tRBxM.js";import{b9 as v,a as z,b as B,c as L,bM as M,r as I,d as D,bW as k}from"./useAppFontEffects-BFgKpDYT.js";const C=50,P=n=>{if(!n)return null;const c=n.replace(/\\/g,"/");return c==="/"?"/":c.replace(/\/+$/,"")},R=(n,c)=>{const s=P(n),a=P(c);return!s||!a?!1:s===a||s.startsWith(`${a}/`)},A=n=>n?k(n):null,w=(n,c={})=>{const{scopeProjectId:s=null,maxParents:a=C}=c,u=v({archived:!1}),S=z(e=>e.projects),d=B(e=>e.ids),h=L(e=>e.rankById),b=M(),j=f.useMemo(()=>S.map(e=>({...e,normalizedPath:P(e.path)})).filter(e=>e.normalizedPath),[S]),m=f.useCallback(e=>e?j.filter(i=>R(e,i.normalizedPath)).sort((i,l)=>(l.normalizedPath?.length??0)-(i.normalizedPath?.length??0))[0]??null:null,[j]);return f.useMemo(()=>{if(!n)return[];const e=new Map;for(const t of u){const r=t.parentID;if(!r||t.time?.archived)continue;const o=e.get(r);o?o.push(t):e.set(r,[t])}const y=D(d,h);e.forEach(t=>{t.sort(y)});const i=u.filter(t=>!t.time?.archived).filter(t=>!t.parentID).filter(t=>{if(!s)return!0;const r=I(t);return m(r)?.id===s}).sort(D(d,h)).slice(0,a),l=t=>{const r=e.get(t.id)??[];return{session:t,children:r.map(o=>l(o))}};return i.map(t=>{const r=I(t),o=m(r),g=A(o),p=(r?b.get(r):void 0)??null;return{node:l(t),projectId:o?.id??null,groupDirectory:r,secondaryMeta:{projectLabel:g,branchLabel:p&&p!==g?p:null}}})},[u,b,n,m,a,d,s,h])};export{w as u};
1
+ import{R as f}from"./vendor-react-Bz1tRBxM.js";import{b9 as v,a as z,b as B,c as L,bM as M,r as I,d as D,bW as k}from"./useAppFontEffects-ZTyNwFk6.js";const C=50,P=n=>{if(!n)return null;const c=n.replace(/\\/g,"/");return c==="/"?"/":c.replace(/\/+$/,"")},R=(n,c)=>{const s=P(n),a=P(c);return!s||!a?!1:s===a||s.startsWith(`${a}/`)},A=n=>n?k(n):null,w=(n,c={})=>{const{scopeProjectId:s=null,maxParents:a=C}=c,u=v({archived:!1}),S=z(e=>e.projects),d=B(e=>e.ids),h=L(e=>e.rankById),b=M(),j=f.useMemo(()=>S.map(e=>({...e,normalizedPath:P(e.path)})).filter(e=>e.normalizedPath),[S]),m=f.useCallback(e=>e?j.filter(i=>R(e,i.normalizedPath)).sort((i,l)=>(l.normalizedPath?.length??0)-(i.normalizedPath?.length??0))[0]??null:null,[j]);return f.useMemo(()=>{if(!n)return[];const e=new Map;for(const t of u){const r=t.parentID;if(!r||t.time?.archived)continue;const o=e.get(r);o?o.push(t):e.set(r,[t])}const y=D(d,h);e.forEach(t=>{t.sort(y)});const i=u.filter(t=>!t.time?.archived).filter(t=>!t.parentID).filter(t=>{if(!s)return!0;const r=I(t);return m(r)?.id===s}).sort(D(d,h)).slice(0,a),l=t=>{const r=e.get(t.id)??[];return{session:t,children:r.map(o=>l(o))}};return i.map(t=>{const r=I(t),o=m(r),g=A(o),p=(r?b.get(r):void 0)??null;return{node:l(t),projectId:o?.id??null,groupDirectory:r,secondaryMeta:{projectLabel:g,branchLabel:p&&p!==g?p:null}}})},[u,b,n,m,a,d,s,h])};export{w as u};
@@ -1,4 +1,4 @@
1
- import{dm as M,dR as V,dS as Y,dT as X,dU as j,dX as K,dY as Z,dZ as $,d_ as J,dV as Q}from"./useAppFontEffects-BFgKpDYT.js";import{b as ee,t as p,y as I,A as ne,a as G,z as te,B as C}from"./computeVirtualFileMetrics-g1aOl5nF.js";import{t as ie}from"./vendor-hast-util-to-html-O3stl53j.js";function U(e,n,t){if(e===n||e==null||n==null)return e===n;const i=new Set(t),a=Object.keys(e),r=new Set(Object.keys(n));for(const s of a)if(r.delete(s),!i.has(s)&&(!(s in n)||e[s]!==n[s]))return!1;for(const s of Array.from(r))if(!i.has(s))return!1;return!0}function Te(e,n){const t=e?.theme??M,i=n?.theme??M,a=R(e),r=R(n);return ee(t,i)&&U(e,n,["theme","parseDiffOptions"])&&U(a,r)}function R(e){if(e!=null&&"parseDiffOptions"in e)return e.parseDiffOptions}function H(e,n){return e?.start===n?.start&&e?.end===n?.end&&e?.side===n?.side&&e?.endSide===n?.endSide}function ae(){return p({tagName:"button",properties:{"data-utility-button":"",type:"button"},children:[I({name:"diffs-icon-plus",properties:{"data-icon":""}})]})}function re(e,n){return e.lineNumber===n.lineNumber&&e.side===n.side}var Ie=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;activeLineHighlightSide;activeLineNumberOnly=!1;editorAttached=!1;proposedSelectedRange;renderedSelectionRange;selectionAnchor;queuedSelectionRender;pointerSession={mode:"idle"};constructor(e,n){this.mode=e,this.options=n}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener("click",this.handlePointerClick),this.pre?.removeEventListener("pointerdown",this.handlePointerDown),this.pre?.removeEventListener("pointermove",this.handlePointerMove),this.pre?.removeEventListener("pointerleave",this.handlePointerLeave),this.pre?.removeAttribute("data-interactive-lines"),this.pre?.removeAttribute("data-interactive-line-numbers"),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1}setup(e){this.setSelectionDirty();const{usesCustomGutterUtility:n=!1,enableGutterUtility:t=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),t?this.ensureGutterUtilityNode(n):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode==="gutterSelecting"&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectionRange=void 0}setEditorAttached(e){this.editorAttached!==e&&(this.editorAttached=e,this.setSelectionDirty(),this.renderSelection())}isSelectionDirty(){return this.renderedSelectionRange===null}setSelection(e,n){const t=!(e===this.selectedRange||H(e??void 0,this.selectedRange??void 0));!this.isSelectionDirty()&&!t||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.activeLineHighlightSide=n?.activeLineSide,this.activeLineNumberOnly=n?.lineNumberOnly??!1,this.renderSelection(),this.placeUtility(),t&&n?.notify!==!1&&this.notifySelectionCommitted())}getSelection(){return this.selectedRange}getHoveredLine=()=>{const e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode==="diff"&&e.type==="diff-line")return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode==="file"&&e.type==="line")return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{const{onHunkExpand:n,onLineClick:t,onLineNumberClick:i,onTokenClick:a,onMergeConflictActionClick:r}=this.options;n==null&&t==null&&i==null&&r==null&&a==null||this.options.onGutterUtilityClick!=null&&E(e.composedPath())||(k(this.options.__debugPointerEvents,"click","FileDiff.DEBUG.handlePointerClick:",e),this.handlePointerEvent({eventType:"click",event:e}))};handlePointerMove=e=>{if(e.pointerType!=="mouse")return;const{lineHoverHighlight:n="disabled",onLineEnter:t,onLineLeave:i,onTokenEnter:a,onTokenLeave:r,enableGutterUtility:s=!1}=this.options;n==="disabled"&&!s&&t==null&&i==null&&a==null&&r==null||(k(this.options.__debugPointerEvents,"move","FileDiff.DEBUG.handlePointerMove:",e),this.handlePointerEvent({eventType:"move",event:e}))};handlePointerLeave=e=>{const{__debugPointerEvents:n}=this.options;if(k(n,"move","FileDiff.DEBUG.handlePointerLeave: no event"),this.hoveredLine==null&&this.hoveredToken==null){k(n,"move","FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token");return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:n}){const{__debugPointerEvents:t}=this.options,i=n.composedPath();k(t,e,"FileDiff.DEBUG.handlePointerEvent:",{eventType:e,composedPath:i});const a=this.resolvePointerTarget(i);k(t,e,"FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:",a);const{onLineClick:r,onLineNumberClick:s,onLineEnter:l,onLineLeave:o,onTokenClick:d,onTokenEnter:c,onTokenLeave:m,onHunkExpand:h,onMergeConflictActionClick:f}=this.options;switch(e){case"move":{const u=T(a)&&this.hoveredLine?.lineElement===a.lineElement;A(a)&&this.hoveredToken?.tokenElement===a.tokenElement||(this.hoveredToken!=null&&(m?.(this.hoveredToken,n),this.clearHoveredToken()),A(a)&&(this.setHoveredToken(this.toTokenEventBaseProps(a)),c?.(this.hoveredToken,n))),u||(this.hoveredLine!=null&&(o?.({...this.hoveredLine,event:n}),this.clearHoveredLine()),T(a)?(this.setHoveredLine(this.toEventBaseProps(a)),this.placeUtility(),l?.({...this.hoveredLine,event:n})):this.placeUtility());break}case"click":{if(a==null)break;if(de(a)&&f!=null){f(a);break}if(se(a)&&h!=null){h(a.hunkIndex,a.all||n.shiftKey?"both":a.direction,a.all||n.shiftKey?Number.POSITIVE_INFINITY:void 0);break}if(!T(a))break;A(a)&&d!=null&&d(this.toTokenEventBaseProps(a),n);const u=this.toEventBaseProps(a);s!=null&&a.numberColumn?s({...u,event:n}):r?.({...u,event:n});break}}}syncPointerListeners(e){const{__debugPointerEvents:n,lineHoverHighlight:t="disabled",onLineClick:i,onLineNumberClick:a,onLineEnter:r,onLineLeave:s,onTokenClick:l,onTokenEnter:o,onTokenLeave:d,onHunkExpand:c,onMergeConflictActionClick:m,enableGutterUtility:h=!1,enableLineSelection:f=!1,onGutterUtilityClick:u}=this.options,v=u!=null,b=t!=="disabled"||i!=null||a!=null||r!=null||s!=null||l!=null||o!=null||d!=null||c!=null||m!=null||h||f||v;b&&!this.hasPointerListeners?(e.addEventListener("click",this.handlePointerClick),e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!0,k(n,"click","FileDiff.DEBUG.attachEventListeners: Attaching click events for:",(()=>{const x=[];return(n==="both"||n==="click")&&(i!=null&&x.push("onLineClick"),a!=null&&x.push("onLineNumberClick"),c!=null&&x.push("expandable hunk separators"),m!=null&&x.push("merge conflict actions")),x})()),k(n,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer move event"),k(n,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event")):!b&&this.hasPointerListeners&&(e.removeEventListener("click",this.handlePointerClick),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!1);const g=this.pointerSession.mode==="selecting"||this.pointerSession.mode==="pendingSingleLineUnselect",y=this.pointerSession.mode==="gutterSelecting";(!f&&g||!v&&y)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;const{onLineClick:e,onLineNumberClick:n,enableLineSelection:t=!1}=this.options,i=e!=null,a=n!=null||t;i&&!this.interactiveLinesAttr?(this.pre.setAttribute("data-interactive-lines",""),this.interactiveLinesAttr=!0):!i&&this.interactiveLinesAttr&&(this.pre.removeAttribute("data-interactive-lines"),this.interactiveLinesAttr=!1),a&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute("data-interactive-line-numbers",""),this.interactiveLineNumbersAttr=!0):!a&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute("data-interactive-line-numbers"),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType==="mouse"&&e.button!==0||this.pre==null||this.pointerSession.mode!=="idle")return;const n=e.composedPath();E(n)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!=="mouse"&&this.revealUtilityFromGutterPath(n),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){const{enableLineSelection:n=!1}=this.options;if(!n)return;const t=this.resolveSelectionInfo(e,{source:"event-path",requireNumberColumn:!0});if(t==null)return;const{pre:i}=this;if(i==null)return;e.preventDefault();const{lineNumber:a,eventSide:r,lineIndex:s}=t;if(e.shiftKey&&this.selectedRange!=null){const l=this.getIndexesFromSelection(this.selectedRange,i.getAttribute("data-diff-type")==="split");if(l==null)return;const o=l.start<=l.end?s>=l.start:s<=l.end;this.selectionAnchor={lineNumber:o?this.selectedRange.start:this.selectedRange.end,side:o?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(a,r,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===a&&this.selectedRange?.end===a){const l={lineNumber:a,side:r};this.selectionAnchor=l,this.pointerSession={mode:"pendingSingleLineUnselect",pointerId:e.pointerId,anchor:l,pending:l},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:a,side:r},this.updateSelection(a,r,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){const{enableLineSelection:n=!1,onGutterUtilityClick:t}=this.options;if(t==null)return;const i=this.currentSelectionEnds(),a=i?.bottom??this.resolveSelectionPoint(e,{source:"event-path",excludeUtility:!1}),r=i?.top??a;a==null||r==null||(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:"gutterSelecting",pointerId:e.pointerId,anchor:r,current:a},n&&(this.selectionAnchor={lineNumber:r.lineNumber,side:r.side},this.updateSelection(a.lineNumber,a.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange())),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{const{enableLineSelection:n=!1}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionPoint(e,{source:"coordinates-first"});if(t==null)return;this.pointerSession.current=t,n===!0&&this.updateSelection(t.lineNumber,t.side);return}case"selecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case"pendingSingleLineUnselect":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;const i={lineNumber:t.lineNumber,side:t.eventSide};if(re(this.pointerSession.pending,i))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:"selecting",pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{const{enableLineSelection:n=!1,onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const i=this.resolveSelectionPoint(e,{source:"coordinates-first"});i!=null&&(this.pointerSession.current=i,n&&this.updateSelection(i.lineNumber,i.side)),t?.(this.buildSelectedLineRange(this.pointerSession.anchor,this.pointerSession.current)),this.selectionAnchor=void 0,n&&(this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case"pendingSingleLineUnselect":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection();return;case"selecting":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":case"selecting":case"pendingSingleLineUnselect":if("pointerId"in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute("data-hovered"),this.hoveredLine.numberElement.removeAttribute("data-hovered"),this.hoveredLine=void 0)}setHoveredLine(e){const{lineHoverHighlight:n="disabled"}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,n!=="disabled"&&((n==="both"||n==="line")&&this.hoveredLine.lineElement.setAttribute("data-hovered",""),(n==="both"||n==="number")&&this.hoveredLine.numberElement.setAttribute("data-hovered",""))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer==null&&(this.gutterUtilityContainer=document.createElement("div"),this.gutterUtilityContainer.setAttribute("data-gutter-utility-slot","")),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot==null&&(this.gutterUtilitySlot=document.createElement("slot"),this.gutterUtilitySlot.name="gutter-utility-slot"),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){const n=document.createElement("div");n.innerHTML=ie(ae());const t=n.firstElementChild;if(!(t instanceof HTMLButtonElement))throw new Error("InteractionManager.ensureGutterUtilityNode: Node element should be a button");t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;const n=this.resolvePointerTarget(e);w(n)&&n.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(n))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){const e=this.currentSelectionEnds();if(e==null)return!1;const n=this.targetForSelectionPoint(e.bottom);return n==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(n)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){const e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){const n={lineNumber:e.start,side:e.side},t={lineNumber:e.end,side:e.endSide??e.side},i=this.selectionPointRowIndex(n),a=this.selectionPointRowIndex(t);if(!(i==null||a==null))return i>a?{top:t,bottom:n}:{top:n,bottom:t}}selectionPointRowIndex(e){const n=this.getLineIndex(e.lineNumber,e.side);if(n!=null)return this.isSplitDiff()?n[1]:n[0]}targetForSelectionPoint(e){if(this.pre==null)return;const n=this.getLineIndex(e.lineNumber,e.side);if(n==null)return;const t=this.mode==="diff"?`${n[0]},${n[1]}`:`${n[0]}`,i=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${t}"]`);for(const a of i){if(!(a instanceof HTMLElement))continue;const r=this.resolvePointerTarget(L(a));if(w(r)&&!(this.mode==="diff"&&e.side!=null&&r.side!==e.side))return r}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||(document.addEventListener("pointermove",this.handleDocumentPointerMove),document.addEventListener("pointerup",this.handleDocumentPointerUp),document.addEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&(document.removeEventListener("pointermove",this.handleDocumentPointerMove),document.removeEventListener("pointerup",this.handleDocumentPointerUp),document.removeEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!1)}clearPointerSession(){this.pointerSession={mode:"idle"}}clearPendingSingleLineState(){this.pointerSession.mode==="pendingSingleLineUnselect"&&(this.pointerSession={mode:"idle"})}selectionInfoFromPath(e,n){const t=this.resolvePointerTarget(e);if(w(t)&&!(n&&!t.numberColumn)&&t.splitLineIndex!=null)return{lineIndex:t.splitLineIndex,lineNumber:t.lineNumber,eventSide:this.mode==="diff"?t.side:void 0}}resolveSelectionInfo(e,n){const t=this.resolveSelectionPath(e,n);return t!=null?this.selectionInfoFromPath(t,n.requireNumberColumn):void 0}selectionPointFromPath(e){const n=this.resolvePointerTarget(e);if(w(n))return{lineNumber:n.lineNumber,side:this.mode==="diff"?n.side:void 0}}resolveSelectionPoint(e,n){const t=this.resolveSelectionPath(e,n);return t!=null?this.selectionPointFromPath(t):void 0}resolveSelectionPath(e,n){const t=n.excludeUtility!==!1;switch(n.source){case"event-path":return this.pathFromEventPath(e.composedPath(),t);case"coordinates-first":{const i=this.pathFromCoordinates(e,t);return i!==void 0?i??void 0:this.pathFromEventPath(e.composedPath(),t)}}}pathFromCoordinates(e,n){const t=this.hitTest(e);if(t!==void 0)return t===null?null:this.pathFromElement(t,n)??null}pathFromEventPath(e,n){if(!(n&&E(e))){for(const t of e)if(t instanceof Element)return this.pathFromElement(t,n)}}pathFromElement(e,n){const t=L(e);if(n&&E(t))return;const i=fe(e);return i!=null?L(i):this.pathFromAnnotationSlot(e)}pathFromAnnotationSlot(e){const n=ue(ce(e));if(n==null)return;const t=this.targetForSelectionPoint(n);return t!=null?L(t.lineElement):void 0}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;const n=this.pre?.getRootNode(),t=z(n)?n:z(document)?document:void 0;if(t!=null)return t.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,n){const{getLineIndex:t}=this.options;return t!=null?t(e,n):[e-1,e-1]}getCurrentSelectionRange(){return this.proposedSelectedRange!==void 0?this.proposedSelectedRange:this.selectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,n,t=!0){const i=this.getCurrentSelectionRange();let a;if(e==null)a=null;else{const r=this.selectionAnchor?.side??n,s=this.selectionAnchor?.lineNumber??e;a=this.buildSelectionRange(s,e,r,n)}H(i??void 0,a??void 0)||(this.activeLineHighlightSide=void 0,this.activeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=a:(this.selectedRange=a,this.queuedSelectionRender??=requestAnimationFrame(this.renderSelection)),this.placeUtility(),t&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,n){if(this.pre==null)return;const t=this.getLineIndex(e.start,e.side),i=this.getLineIndex(e.end,e.endSide??e.side);return t!=null&&i!=null?{start:n?t[1]:t[0],end:n?i[1]:i[0]}:void 0}highlightLineNumberOnly(){return this.activeLineHighlightSide!=null?this.activeLineNumberOnly:this.activeLineNumberOnly||this.editorAttached}renderSelection=()=>{if(this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.pre==null||this.renderedSelectionRange===this.selectedRange)return;const e=this.pre.querySelectorAll("[data-selected-line]");for(const o of e)o.removeAttribute("data-selected-line");if(this.renderedSelectionRange=this.selectedRange,this.selectedRange==null)return;const{children:n}=this.pre;if(n.length===0)return;if(n.length>2)throw console.error(n),new Error("InteractionManager.renderSelection: Somehow there are more than 2 code elements...");const t=this.pre.getAttribute("data-diff-type")==="split",i=this.getIndexesFromSelection(this.selectedRange,t);if(i==null)throw console.error({rowRange:i,selectedRange:this.selectedRange}),new Error("InteractionManager.renderSelection: No valid rowRange");const a=i.start===i.end,r=Math.min(i.start,i.end),s=Math.max(i.start,i.end),l=this.highlightLineNumberOnly();for(const o of n){const d=this.activeLineHighlightSide;if(d!=null&&(d==="additions"&&o.hasAttribute("data-deletions")||d==="deletions"&&o.hasAttribute("data-additions")))continue;const[c,m]=o.children,h=m.children.length;if(h!==c.children.length)throw new Error("InteractionManager.renderSelection: gutter and content children dont match, something is wrong");for(let f=0;f<h;f++){const u=m.children[f],v=c.children[f];if(!(u instanceof HTMLElement)||!(v instanceof HTMLElement))continue;const b=this.parseLineIndex(u,t);if((b??0)>s)break;if(b==null||b<r)continue;let g=a?"single":b===r?"first":b===s?"last":"";v.setAttribute("data-selected-line",g),!l&&(u.setAttribute("data-selected-line",g),v.nextSibling instanceof HTMLElement&&u.nextSibling instanceof HTMLElement&&(u.nextSibling.hasAttribute("data-line-annotation")||u.nextSibling.hasAttribute("data-merge-conflict-actions"))&&(a?(g="last",u.setAttribute("data-selected-line","first")):b===r?g="":b===s&&u.setAttribute("data-selected-line",""),u.nextSibling.setAttribute("data-selected-line",g),v.nextSibling.setAttribute("data-selected-line",g)))}}};notifySelectionCommitted(){this.options.onLineSelected?.(this.getCurrentSelectionRange()??null)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode==="file"?{type:"line",lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:"diff-line",annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:n,lineNumber:t,side:i,tokenElement:a,tokenText:r}){return this.mode==="file"?{type:"token",lineCharEnd:e,lineCharStart:n,lineNumber:t,tokenElement:a,tokenText:r}:{type:"token",lineCharEnd:e,lineCharStart:n,lineNumber:t,side:i,tokenElement:a,tokenText:r}}buildSelectedLineRange(e,n){return this.buildSelectionRange(e.lineNumber,n.lineNumber,e.side,n.side)}buildSelectionRange(e,n,t,i){return{start:e,end:n,...t!=null?{side:t}:{},...t!==i&&i!=null?{endSide:i}:{}}}resolvePointerTarget(e){let n=!1,t,i,a,r,s,l,o,d,c,m;for(const f of e){if(!(f instanceof HTMLElement))continue;if(m==null&&f.hasAttribute("data-merge-conflict-action")){const g=f.getAttribute("data-merge-conflict-action")??void 0,y=f.getAttribute("data-merge-conflict-conflict-index")??void 0,x=y!=null?Number.parseInt(y,10):NaN;le(g)&&Number.isFinite(x)&&(m={kind:"merge-conflict-action",resolution:g,conflictIndex:x})}if(l==null&&f.hasAttribute("data-char")){l=f;const g=f.getAttribute("data-char");if(g!=null){const y=Number.parseInt(g,10);if(!Number.isNaN(y)){const x=f.textContent??"",N=y+x.length;(x.trim()!==""||this.options.enableTokenInteractionsOnWhitespace===!0)&&(o={tokenElement:l,lineCharStart:y,lineCharEnd:N,tokenText:x});continue}}}const u=s==null?f.getAttribute("data-column-number")??void 0:void 0;if(u!=null){s=f,c=Number.parseInt(u,10),n=!0,t=O(f),r=f.getAttribute("data-line-index")??void 0;continue}const v=a==null?f.getAttribute("data-line")??void 0:void 0;if(v!=null){a=f,c=Number.parseInt(v,10),t=O(f),r=f.getAttribute("data-line-index")??void 0;continue}if(d==null&&(f.hasAttribute("data-expand-button")||f.hasAttribute("data-unmodified-lines"))){d={hunkIndex:void 0,direction:f.hasAttribute("data-expand-up")?"up":f.hasAttribute("data-expand-down")?"down":"both",all:f.hasAttribute("data-expand-all-button")};continue}const b=d!=null?f.getAttribute("data-expand-index")??void 0:void 0;if(d!=null&&b!=null){const g=Number.parseInt(b,10);Number.isNaN(g)||(d.hunkIndex=g);continue}if(i==null&&f.hasAttribute("data-code")){i=f;break}}if(m!=null)return m;if(d?.hunkIndex!=null)return{type:"line-info",hunkIndex:d.hunkIndex,direction:d.direction,all:d.all};if(a??=r!=null?D(i,`[data-line][data-line-index="${r}"]`):void 0,s??=r!=null?D(i,`[data-column-number][data-line-index="${r}"]`):void 0,i==null||a==null||s==null||t==null||c==null||Number.isNaN(c))return;const h=this.parseLineIndex(a,this.isSplitDiff());return o!=null?this.mode==="file"?{kind:"token",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:void 0,splitLineIndex:h,...o}:{kind:"token",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:F(t,i),splitLineIndex:h,...o}:this.mode==="file"?{kind:"line",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:void 0,splitLineIndex:h}:{kind:"line",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:F(t,i),splitLineIndex:h}}isSplitDiff(){return this.pre?.getAttribute("data-diff-type")==="split"}parseLineIndex(e,n){const t=(e.getAttribute("data-line-index")??"").split(",").map(i=>Number.parseInt(i,10)).filter(i=>!Number.isNaN(i));if(n&&t.length===2)return t[1];if(!n)return t[0]}};function Me({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:n,lineHoverHighlight:t,onGutterUtilityClick:i,onLineClick:a,onLineEnter:r,onLineLeave:s,onLineNumberClick:l,onTokenClick:o,onTokenEnter:d,onTokenLeave:c,renderGutterUtility:m,__debugPointerEvents:h,enableLineSelection:f,controlledSelection:u,onLineSelected:v,onLineSelectionStart:b,onLineSelectionChange:g,onLineSelectionEnd:y},x,N,W){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:oe({enableGutterUtility:n,renderGutterUtility:m,onGutterUtilityClick:i}),usesCustomGutterUtility:m!=null,lineHoverHighlight:t,onGutterUtilityClick:i,onHunkExpand:x,onMergeConflictActionClick:W,onLineClick:a,onLineEnter:r,onLineLeave:s,onLineNumberClick:l,onTokenClick:o,onTokenEnter:d,onTokenLeave:c,__debugPointerEvents:h,enableLineSelection:f,controlledSelection:u,onLineSelected:v,onLineSelectionStart:b,onLineSelectionChange:g,onLineSelectionEnd:y,getLineIndex:N}}function oe({enableGutterUtility:e,renderGutterUtility:n,onGutterUtilityClick:t}){if(t!=null&&n!=null)throw new Error("Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.");return e??!1}function w(e){return e!=null&&"kind"in e&&e.kind==="line"}function A(e){return e!=null&&"kind"in e&&e.kind==="token"}function T(e){return w(e)||A(e)}function se(e){return"type"in e&&e.type==="line-info"}function de(e){return"kind"in e&&e.kind==="merge-conflict-action"}function le(e){return e==="current"||e==="incoming"||e==="both"}function D(e,n){const t=e?.querySelector(n);return t instanceof HTMLElement?t:void 0}function L(e){const n=[];let t=e;for(;t!=null;)n.push(t),t=t.parentNode;return n}function fe(e){const n=e.closest("[data-line], [data-column-number]");if(n instanceof HTMLElement)return n;const t=e.closest('[data-line-annotation], [data-gutter-buffer="annotation"]');if(!(t instanceof HTMLElement))return;const i=t.previousElementSibling;return i instanceof HTMLElement&&(i.hasAttribute("data-line")||i.hasAttribute("data-column-number"))?i:void 0}function ce(e){const n=e.closest('[slot^="annotation-"]');if(n instanceof HTMLElement)return n.getAttribute("slot")??void 0;if(e instanceof HTMLElement){const t=e.getAttribute("name")??void 0;return t!=null&&t.startsWith("annotation-")?t:void 0}}function ue(e){if(e==null)return;const n=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(n==null)return;const t=Number.parseInt(n[2],10);if(!(!Number.isFinite(t)||t<=0))return{lineNumber:t,side:n[1]}}function z(e){return e!=null&&typeof e.elementFromPoint=="function"}function F(e,n){switch(e){case"change-deletion":return"deletions";case"change-addition":return"additions";default:return n.hasAttribute("data-deletions")?"deletions":"additions"}}function O(e){const n=e.getAttribute("data-line-type");if(n!=null)switch(n){case"change-deletion":case"change-addition":case"context":case"context-expanded":return n;default:return}}function E(e){for(const n of e)if(n instanceof HTMLElement&&(n.hasAttribute("data-utility-button")||n.hasAttribute("data-gutter-utility-slot")||n.getAttribute("slot")==="gutter-utility-slot"||n.getAttribute("name")==="gutter-utility-slot"))return!0;return!1}function k(e="none",n,...t){switch(e){case"none":return;case"both":break;case"click":if(n!=="click")return;break;case"move":if(n!=="move")return;break}console.log(...t)}var Ue=class S{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){const n=S.resizeObserver??new ResizeObserver(S.handleSharedResizeEntries);return S.resizeObserver=n,n}static handleSharedResizeEntries(n){const t=new Map;for(const i of n){const a=S.managersByElement.get(i.target);if(a==null)continue;const r=t.get(a);r==null?t.set(a,[i]):r.push(i)}for(const[i,a]of t)i.handleResizeEntries(a)}observedNodes=new Map;setup(n,t){const i=new Set;let a=0;const r=new Map(this.observedNodes);this.observedNodes.clear();for(const s of n.children){if(a===2)break;const l=(()=>{if(s instanceof HTMLElement&&s.tagName==="CODE")return s})();if(l==null)continue;a++;let o=r.get(l);if(o!=null&&o.type!=="code")throw new Error("ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible");let d=l.firstElementChild;d instanceof HTMLElement||(d=null),o!=null?(this.observedNodes.set(l,o),r.delete(l),o.numberElement!==d?(o.numberElement!=null&&(this.unobserve(o.numberElement),r.delete(o.numberElement)),d!=null&&(this.observe(d),r.delete(d),this.observedNodes.set(d,o)),o.numberElement=d,o.numberWidth=0):o.numberElement!=null?(r.delete(o.numberElement),this.observedNodes.set(o.numberElement,o)):o.numberWidth=0):(o={type:"code",codeElement:l,numberElement:d,codeWidth:"auto",numberWidth:0},this.observedNodes.set(l,o),this.observe(l),d!=null&&(this.observedNodes.set(d,o),this.observe(d)))}if(a>1&&!t){const s=n.querySelectorAll('[data-line-annotation*=","]'),l=new Map;for(const o of s){if(!(o instanceof HTMLElement))continue;const d=o.getAttribute("data-line-annotation")??"";if(!/^-?\d+,-?\d+$/.test(d)){console.error("DiffFileRenderer.setupResizeObserver: Invalid element or annotation",{lineAnnotation:d,element:o});continue}let c=l.get(d);c==null&&(c=[],l.set(d,c)),c.push(o)}for(const[o,d]of l){if(d.length!==2){console.error("DiffFileRenderer.setupResizeObserver: Bad Pair",o,d);continue}const[c,m]=d,h=c.firstElementChild,f=m.firstElementChild;if(!(c instanceof HTMLElement)||!(m instanceof HTMLElement)||!(h instanceof HTMLElement)||!(f instanceof HTMLElement))continue;let u=r.get(h);if(u!=null){this.observedNodes.set(h,u),this.observedNodes.set(f,u),r.delete(h),r.delete(f);continue}const v=h.getBoundingClientRect().height,b=f.getBoundingClientRect().height;u={type:"annotations",column1:{container:c,child:h,childHeight:v},column2:{container:m,child:f,childHeight:b},currentHeight:"auto"},i.add({child1:h,child2:f,item:u,newHeight:Math.max(v,b)})}for(const o of i)this.applyNewHeight(o.item,o.newHeight),this.observedNodes.set(o.child1,o.item),this.observedNodes.set(o.child2,o.item),this.observe(o.child1),this.observe(o.child2);i.clear()}for(const[s,l]of r)this.unobserve(s),l.type==="code"?ge(l):pe(l);r.clear()}cleanUp(){for(const n of this.observedNodes.keys())this.unobserve(n);this.observedNodes.clear()}observe(n){const{managersByElement:t}=S,i=t.get(n);if(i!==this){if(i!=null&&i!==this)throw new Error("ResizeManager.observe: element is already owned by another ResizeManager");t.set(n,this),S.getResizeObserver().observe(n)}}unobserve(n){const{managersByElement:t,resizeObserver:i}=S,a=t.get(n);if(a!=null){if(a!==this)throw new Error("ResizeManager.unobserve: element is owned by another ResizeManager");t.delete(n),i?.unobserve(n),i!=null&&t.size===0&&(i.disconnect(),S.resizeObserver=void 0)}}handleResizeEntries(n){const t=new Map,i=new Set;for(const a of n){const{target:r,borderBoxSize:s,contentBoxSize:l}=a;if(!(r instanceof HTMLElement)){console.error("ResizeManager.handleResizeEntries: Invalid element for ResizeObserver",a);continue}const o=this.observedNodes.get(r);if(o==null){console.error("ResizeManager.handleResizeEntries: Not a valid observed node",a);continue}if(o.type==="annotations"){const d=(()=>{if(r===o.column1.child)return o.column1;if(r===o.column2.child)return o.column2})();if(d==null){console.error("ResizeManager.handleResizeEntries: Couldn't find a column for",{item:o,target:r});continue}d.childHeight=s[0].blockSize,i.add(o)}else if(o.type==="code"){const d=t.get(o)??{},c=l[0].inlineSize;r===o.codeElement?d.codeInlineSize=c:r===o.numberElement&&(d.numberInlineSize=c),t.set(o,d)}}this.applyAnnotationUpdates(i),i.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(n){for(const t of n)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=n=>{for(const[t,i]of n){const a=i.codeInlineSize!=null?he(i.codeInlineSize):t.codeWidth,r=i.numberInlineSize!=null?me(i.numberInlineSize):t.numberWidth,s=a!==t.codeWidth,l=r!==t.numberWidth;if(!(!s&&!l)&&(t.codeWidth=a,t.numberWidth=r,s&&t.codeElement.style.setProperty("--diffs-column-width",`${typeof a=="number"?`${a}px`:"auto"}`),l&&t.codeElement.style.setProperty("--diffs-column-number-width",`${r===0?"auto":`${r}px`}`),s||l&&a!=="auto")){const o=typeof a=="number"?Math.max(a-r,0):0;t.codeElement.style.setProperty("--diffs-column-content-width",`${o>0?`${o}px`:"auto"}`)}}};applyNewHeight(n,t){t!==n.currentHeight&&(n.currentHeight=Math.max(t,0),n.column1.container.style.setProperty("--diffs-annotation-min-height",`${n.currentHeight}px`),n.column2.container.style.setProperty("--diffs-annotation-min-height",`${n.currentHeight}px`))}};function he(e){const n=Math.max(Math.floor(e),0);return n===0?"auto":n}function me(e){return Math.max(Math.ceil(e),0)}function ge(e){e.codeElement.isConnected&&(e.codeElement.style.removeProperty("--diffs-column-content-width"),e.codeElement.style.removeProperty("--diffs-column-number-width"),e.codeElement.style.removeProperty("--diffs-column-width"))}function pe(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty("--diffs-annotation-min-height"),e.column2.container.isConnected&&e.column2.container.style.removeProperty("--diffs-annotation-min-height")}function Re(e){for(const n of Array.isArray(e)?e:[e])if(!(n==="text"||n==="ansi")&&!ne.has(n))return!1;return!0}function He(e){for(const n of G(e))if(!te.has(n))return!1;return!0}function De(e,n){return e==null||n==null?e===n:e.startingLine===n.startingLine&&e.totalLines===n.totalLines&&e.bufferBefore===n.bufferBefore&&e.bufferAfter===n.bufferAfter}function ze(e){return p({tagName:"div",children:[p({tagName:"div",children:e.annotations?.map(n=>p({tagName:"slot",properties:{name:n}})),properties:{"data-annotation-content":""}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function be(e){switch(e){case"file":return"diffs-icon-file-code";case"change":return"diffs-icon-symbol-modified";case"new":return"diffs-icon-symbol-added";case"deleted":return"diffs-icon-symbol-deleted";case"rename-pure":case"rename-changed":return"diffs-icon-symbol-moved"}}function Fe({fileOrDiff:e,mode:n,stickyHeader:t}){const i="type"in e?e:void 0,a={"data-diffs-header":n,"data-change-type":i?.type,"data-sticky":t?"":void 0};return p({tagName:"div",children:[n==="custom"?p({tagName:"slot",properties:{name:V}}):ve({name:e.name,prevName:"prevName"in e?e.prevName:void 0,iconType:i?.type??"file"}),...n==="custom"?[]:[xe(i)]],properties:a})}function ve({name:e,prevName:n,iconType:t}){const i=[p({tagName:"slot",properties:{name:Y}}),I({name:be(t),properties:{"data-change-icon":t}})];return n!=null&&(i.push(p({tagName:"div",children:[p({tagName:"bdi",children:[C(n)]})],properties:{"data-prev-name":""}})),i.push(I({name:"diffs-icon-arrow-right-short",properties:{"data-rename-icon":""}}))),i.push(p({tagName:"div",children:[p({tagName:"bdi",children:[C(e)]})],properties:{"data-title":""}})),i.push(p({tagName:"slot",properties:{name:X}})),p({tagName:"div",children:i,properties:{"data-header-content":""}})}function xe(e){const n=[];if(e!=null){let t=0,i=0;for(const a of e.hunks)t+=a.additionLines,i+=a.deletionLines;(i>0||t===0)&&n.push(p({tagName:"span",children:[C(`-${i}`)],properties:{"data-deletions-count":""}})),(t>0||i===0)&&n.push(p({tagName:"span",children:[C(`+${t}`)],properties:{"data-additions-count":""}}))}return n.push(p({tagName:"slot",properties:{name:j}})),p({tagName:"div",children:n,properties:{"data-metadata":""}})}function Oe(e){return p({tagName:"pre",properties:ye(e)})}function ye({diffIndicators:e,disableBackground:n,disableLineNumbers:t,overflow:i,split:a,totalLines:r,type:s,customProperties:l}){return{...l,"data-diff":s==="diff"?"":void 0,"data-file":s==="file"?"":void 0,"data-diff-type":s==="diff"?a?"split":"single":void 0,"data-overflow":i,"data-disable-line-numbers":t?"":void 0,"data-background":n?void 0:"","data-indicators":e==="bars"||e==="classic"?e:void 0,tabIndex:0,style:`--diffs-min-number-column-width-default:${`${r}`.length}ch;`}}function Be(e,{theme:n,preferredHighlighter:t="shiki-js"}){return{langs:[e??"text"],themes:G(n),preferredHighlighter:t}}function $e(e){return`annotation-${"side"in e?`${e.side}-`:""}${e.lineNumber}`}const Ge="-1,-1";function _e(e){return e?.some(n=>n.lineNumber===0)??!1}function qe(e){const n=e[0];return n!=null&&n.length>0?n:void 0}function We(e){return e.startingLine===0&&e.totalLines>0}function Ve(e,n){return p({tagName:"div",children:e,properties:{"data-content":"",style:`grid-row: span ${n}`}})}function Ye(e){return e.useTokenTransformer===!0||e.onTokenClick!=null||e.onTokenEnter!=null||e.onTokenLeave!=null}const Xe=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
1
+ import{dm as M,dR as V,dS as Y,dT as X,dU as j,dX as K,dY as Z,dZ as $,d_ as J,dV as Q}from"./useAppFontEffects-ZTyNwFk6.js";import{b as ee,t as p,y as I,A as ne,a as G,z as te,B as C}from"./computeVirtualFileMetrics-G4csGiKs.js";import{t as ie}from"./vendor-hast-util-to-html-O3stl53j.js";function U(e,n,t){if(e===n||e==null||n==null)return e===n;const i=new Set(t),a=Object.keys(e),r=new Set(Object.keys(n));for(const s of a)if(r.delete(s),!i.has(s)&&(!(s in n)||e[s]!==n[s]))return!1;for(const s of Array.from(r))if(!i.has(s))return!1;return!0}function Te(e,n){const t=e?.theme??M,i=n?.theme??M,a=R(e),r=R(n);return ee(t,i)&&U(e,n,["theme","parseDiffOptions"])&&U(a,r)}function R(e){if(e!=null&&"parseDiffOptions"in e)return e.parseDiffOptions}function H(e,n){return e?.start===n?.start&&e?.end===n?.end&&e?.side===n?.side&&e?.endSide===n?.endSide}function ae(){return p({tagName:"button",properties:{"data-utility-button":"",type:"button"},children:[I({name:"diffs-icon-plus",properties:{"data-icon":""}})]})}function re(e,n){return e.lineNumber===n.lineNumber&&e.side===n.side}var Ie=class{mode;options;hoveredLine;hoveredToken;pre;gutterUtilityLine;gutterUtilityContainer;gutterUtilityButton;gutterUtilitySlot;interactiveLinesAttr=!1;interactiveLineNumbersAttr=!1;hasPointerListeners=!1;hasDocumentPointerListeners=!1;selectedRange=null;activeLineHighlightSide;activeLineNumberOnly=!1;editorAttached=!1;proposedSelectedRange;renderedSelectionRange;selectionAnchor;queuedSelectionRender;pointerSession={mode:"idle"};constructor(e,n){this.mode=e,this.options=n}setOptions(e){this.options=e}cleanUp(){this.pre?.removeEventListener("click",this.handlePointerClick),this.pre?.removeEventListener("pointerdown",this.handlePointerDown),this.pre?.removeEventListener("pointermove",this.handlePointerMove),this.pre?.removeEventListener("pointerleave",this.handlePointerLeave),this.pre?.removeAttribute("data-interactive-lines"),this.pre?.removeAttribute("data-interactive-line-numbers"),this.pre=void 0,this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.clearHoveredLine(),this.clearHoveredToken(),this.detachDocumentPointerListeners(),this.clearPointerSession(),this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.interactiveLinesAttr=!1,this.interactiveLineNumbersAttr=!1,this.hasPointerListeners=!1}setup(e){this.setSelectionDirty();const{usesCustomGutterUtility:n=!1,enableGutterUtility:t=!1}=this.options;this.pre!==e&&(this.cleanUp(),this.pre=e),t?this.ensureGutterUtilityNode(n):this.gutterUtilityContainer!=null&&(this.gutterUtilityContainer.remove(),this.gutterUtilityLine=void 0,this.gutterUtilityContainer=void 0,this.gutterUtilityButton=void 0,this.gutterUtilitySlot=void 0,this.pointerSession.mode==="gutterSelecting"&&(this.clearPointerSession(),this.detachDocumentPointerListeners())),this.syncPointerListeners(e),this.updateInteractiveLineAttributes(),this.renderSelection(),this.placeUtility()}setSelectionDirty(){this.renderedSelectionRange=void 0}setEditorAttached(e){this.editorAttached!==e&&(this.editorAttached=e,this.setSelectionDirty(),this.renderSelection())}isSelectionDirty(){return this.renderedSelectionRange===null}setSelection(e,n){const t=!(e===this.selectedRange||H(e??void 0,this.selectedRange??void 0));!this.isSelectionDirty()&&!t||(this.proposedSelectedRange=void 0,this.selectedRange=e,this.activeLineHighlightSide=n?.activeLineSide,this.activeLineNumberOnly=n?.lineNumberOnly??!1,this.renderSelection(),this.placeUtility(),t&&n?.notify!==!1&&this.notifySelectionCommitted())}getSelection(){return this.selectedRange}getHoveredLine=()=>{const e=this.gutterUtilityLine??this.hoveredLine;if(e!=null){if(this.mode==="diff"&&e.type==="diff-line")return{lineNumber:e.lineNumber,side:e.annotationSide};if(this.mode==="file"&&e.type==="line")return{lineNumber:e.lineNumber}}};handlePointerClick=e=>{const{onHunkExpand:n,onLineClick:t,onLineNumberClick:i,onTokenClick:a,onMergeConflictActionClick:r}=this.options;n==null&&t==null&&i==null&&r==null&&a==null||this.options.onGutterUtilityClick!=null&&E(e.composedPath())||(k(this.options.__debugPointerEvents,"click","FileDiff.DEBUG.handlePointerClick:",e),this.handlePointerEvent({eventType:"click",event:e}))};handlePointerMove=e=>{if(e.pointerType!=="mouse")return;const{lineHoverHighlight:n="disabled",onLineEnter:t,onLineLeave:i,onTokenEnter:a,onTokenLeave:r,enableGutterUtility:s=!1}=this.options;n==="disabled"&&!s&&t==null&&i==null&&a==null&&r==null||(k(this.options.__debugPointerEvents,"move","FileDiff.DEBUG.handlePointerMove:",e),this.handlePointerEvent({eventType:"move",event:e}))};handlePointerLeave=e=>{const{__debugPointerEvents:n}=this.options;if(k(n,"move","FileDiff.DEBUG.handlePointerLeave: no event"),this.hoveredLine==null&&this.hoveredToken==null){k(n,"move","FileDiff.DEBUG.handlePointerLeave: returned early, no hovered line or token");return}this.hoveredToken!=null&&(this.options.onTokenLeave?.(this.hoveredToken,e),this.clearHoveredToken()),this.hoveredLine!=null&&(this.options.onLineLeave?.({...this.hoveredLine,event:e}),this.clearHoveredLine()),this.placeUtility()};handlePointerEvent({eventType:e,event:n}){const{__debugPointerEvents:t}=this.options,i=n.composedPath();k(t,e,"FileDiff.DEBUG.handlePointerEvent:",{eventType:e,composedPath:i});const a=this.resolvePointerTarget(i);k(t,e,"FileDiff.DEBUG.handlePointerEvent: resolvePointerTarget result:",a);const{onLineClick:r,onLineNumberClick:s,onLineEnter:l,onLineLeave:o,onTokenClick:d,onTokenEnter:c,onTokenLeave:m,onHunkExpand:h,onMergeConflictActionClick:f}=this.options;switch(e){case"move":{const u=T(a)&&this.hoveredLine?.lineElement===a.lineElement;A(a)&&this.hoveredToken?.tokenElement===a.tokenElement||(this.hoveredToken!=null&&(m?.(this.hoveredToken,n),this.clearHoveredToken()),A(a)&&(this.setHoveredToken(this.toTokenEventBaseProps(a)),c?.(this.hoveredToken,n))),u||(this.hoveredLine!=null&&(o?.({...this.hoveredLine,event:n}),this.clearHoveredLine()),T(a)?(this.setHoveredLine(this.toEventBaseProps(a)),this.placeUtility(),l?.({...this.hoveredLine,event:n})):this.placeUtility());break}case"click":{if(a==null)break;if(de(a)&&f!=null){f(a);break}if(se(a)&&h!=null){h(a.hunkIndex,a.all||n.shiftKey?"both":a.direction,a.all||n.shiftKey?Number.POSITIVE_INFINITY:void 0);break}if(!T(a))break;A(a)&&d!=null&&d(this.toTokenEventBaseProps(a),n);const u=this.toEventBaseProps(a);s!=null&&a.numberColumn?s({...u,event:n}):r?.({...u,event:n});break}}}syncPointerListeners(e){const{__debugPointerEvents:n,lineHoverHighlight:t="disabled",onLineClick:i,onLineNumberClick:a,onLineEnter:r,onLineLeave:s,onTokenClick:l,onTokenEnter:o,onTokenLeave:d,onHunkExpand:c,onMergeConflictActionClick:m,enableGutterUtility:h=!1,enableLineSelection:f=!1,onGutterUtilityClick:u}=this.options,v=u!=null,b=t!=="disabled"||i!=null||a!=null||r!=null||s!=null||l!=null||o!=null||d!=null||c!=null||m!=null||h||f||v;b&&!this.hasPointerListeners?(e.addEventListener("click",this.handlePointerClick),e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!0,k(n,"click","FileDiff.DEBUG.attachEventListeners: Attaching click events for:",(()=>{const x=[];return(n==="both"||n==="click")&&(i!=null&&x.push("onLineClick"),a!=null&&x.push("onLineNumberClick"),c!=null&&x.push("expandable hunk separators"),m!=null&&x.push("merge conflict actions")),x})()),k(n,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer move event"),k(n,"move","FileDiff.DEBUG.attachEventListeners: Attaching pointer leave event")):!b&&this.hasPointerListeners&&(e.removeEventListener("click",this.handlePointerClick),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("pointerleave",this.handlePointerLeave),this.hasPointerListeners=!1);const g=this.pointerSession.mode==="selecting"||this.pointerSession.mode==="pendingSingleLineUnselect",y=this.pointerSession.mode==="gutterSelecting";(!f&&g||!v&&y)&&(this.clearPointerSession(),this.detachDocumentPointerListeners(),this.selectionAnchor=void 0,this.clearPendingSingleLineState())}updateInteractiveLineAttributes(){if(this.pre==null)return;const{onLineClick:e,onLineNumberClick:n,enableLineSelection:t=!1}=this.options,i=e!=null,a=n!=null||t;i&&!this.interactiveLinesAttr?(this.pre.setAttribute("data-interactive-lines",""),this.interactiveLinesAttr=!0):!i&&this.interactiveLinesAttr&&(this.pre.removeAttribute("data-interactive-lines"),this.interactiveLinesAttr=!1),a&&!this.interactiveLineNumbersAttr?(this.pre.setAttribute("data-interactive-line-numbers",""),this.interactiveLineNumbersAttr=!0):!a&&this.interactiveLineNumbersAttr&&(this.pre.removeAttribute("data-interactive-line-numbers"),this.interactiveLineNumbersAttr=!1)}handlePointerDown=e=>{if(e.pointerType==="mouse"&&e.button!==0||this.pre==null||this.pointerSession.mode!=="idle")return;const n=e.composedPath();E(n)&&this.options.onGutterUtilityClick!=null?this.startGutterSelectionFromPointerDown(e):(e.pointerType!=="mouse"&&this.revealUtilityFromGutterPath(n),this.startLineSelectionFromPointerDown(e))};startLineSelectionFromPointerDown(e){const{enableLineSelection:n=!1}=this.options;if(!n)return;const t=this.resolveSelectionInfo(e,{source:"event-path",requireNumberColumn:!0});if(t==null)return;const{pre:i}=this;if(i==null)return;e.preventDefault();const{lineNumber:a,eventSide:r,lineIndex:s}=t;if(e.shiftKey&&this.selectedRange!=null){const l=this.getIndexesFromSelection(this.selectedRange,i.getAttribute("data-diff-type")==="split");if(l==null)return;const o=l.start<=l.end?s>=l.start:s<=l.end;this.selectionAnchor={lineNumber:o?this.selectedRange.start:this.selectedRange.end,side:o?this.selectedRange.side:this.selectedRange.endSide??this.selectedRange.side},this.updateSelection(a,r,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners();return}if(this.selectedRange?.start===a&&this.selectedRange?.end===a){const l={lineNumber:a,side:r};this.selectionAnchor=l,this.pointerSession={mode:"pendingSingleLineUnselect",pointerId:e.pointerId,anchor:l,pending:l},this.attachDocumentPointerListeners();return}this.options.controlledSelection===!0?this.proposedSelectedRange=null:this.selectedRange=null,this.placeUtility(),this.selectionAnchor={lineNumber:a,side:r},this.updateSelection(a,r,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.pointerSession={mode:"selecting",pointerId:e.pointerId},this.attachDocumentPointerListeners()}startGutterSelectionFromPointerDown(e){const{enableLineSelection:n=!1,onGutterUtilityClick:t}=this.options;if(t==null)return;const i=this.currentSelectionEnds(),a=i?.bottom??this.resolveSelectionPoint(e,{source:"event-path",excludeUtility:!1}),r=i?.top??a;a==null||r==null||(e.preventDefault(),e.stopPropagation(),this.pointerSession={mode:"gutterSelecting",pointerId:e.pointerId,anchor:r,current:a},n&&(this.selectionAnchor={lineNumber:r.lineNumber,side:r.side},this.updateSelection(a.lineNumber,a.side,!1),this.notifySelectionStart(this.getCurrentSelectionRange())),this.attachDocumentPointerListeners())}handleDocumentPointerMove=e=>{const{enableLineSelection:n=!1}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionPoint(e,{source:"coordinates-first"});if(t==null)return;this.pointerSession.current=t,n===!0&&this.updateSelection(t.lineNumber,t.side);return}case"selecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;this.updateSelection(t.lineNumber,t.eventSide);return}case"pendingSingleLineUnselect":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const t=this.resolveSelectionInfo(e,{source:"coordinates-first",requireNumberColumn:!1});if(t==null||this.selectionAnchor==null)return;const i={lineNumber:t.lineNumber,side:t.eventSide};if(re(this.pointerSession.pending,i))return;this.updateSelection(t.lineNumber,t.eventSide,!1),this.notifySelectionStart(this.getCurrentSelectionRange()),this.notifySelectionChangeDelta(),this.pointerSession={mode:"selecting",pointerId:e.pointerId};return}}};handleDocumentPointerUp=e=>{const{enableLineSelection:n=!1,onGutterUtilityClick:t}=this.options;switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":{if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault();const i=this.resolveSelectionPoint(e,{source:"coordinates-first"});i!=null&&(this.pointerSession.current=i,n&&this.updateSelection(i.lineNumber,i.side)),t?.(this.buildSelectedLineRange(this.pointerSession.anchor,this.pointerSession.current)),this.selectionAnchor=void 0,n&&(this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()),this.clearPointerSession(),this.detachDocumentPointerListeners();return}case"pendingSingleLineUnselect":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.updateSelection(null,void 0,!1),this.selectionAnchor=void 0,this.clearPendingSingleLineState(),this.detachDocumentPointerListeners(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection();return;case"selecting":if(e.pointerId!==this.pointerSession.pointerId)return;e.preventDefault(),this.selectionAnchor=void 0,this.detachDocumentPointerListeners(),this.clearPointerSession(),this.notifySelectionEnd(this.getCurrentSelectionRange()),this.notifySelectionCommitted(),this.clearProposedSelection()}};handleDocumentPointerCancel=e=>{switch(this.pointerSession.mode){case"idle":return;case"gutterSelecting":case"selecting":case"pendingSingleLineUnselect":if("pointerId"in this.pointerSession&&e.pointerId!==this.pointerSession.pointerId)return;this.selectionAnchor=void 0,this.clearProposedSelection(),this.clearPendingSingleLineState(),this.clearPointerSession(),this.detachDocumentPointerListeners()}};clearHoveredLine(){this.hoveredLine!=null&&(this.hoveredLine.lineElement.removeAttribute("data-hovered"),this.hoveredLine.numberElement.removeAttribute("data-hovered"),this.hoveredLine=void 0)}setHoveredLine(e){const{lineHoverHighlight:n="disabled"}=this.options;this.hoveredLine!=null&&this.clearHoveredLine(),this.hoveredLine=e,n!=="disabled"&&((n==="both"||n==="line")&&this.hoveredLine.lineElement.setAttribute("data-hovered",""),(n==="both"||n==="number")&&this.hoveredLine.numberElement.setAttribute("data-hovered",""))}clearHoveredToken(){this.hoveredToken!=null&&(this.hoveredToken=void 0)}setHoveredToken(e){this.hoveredToken!=null&&this.clearHoveredToken(),this.hoveredToken=e}ensureGutterUtilityNode(e){if(this.gutterUtilityContainer==null&&(this.gutterUtilityContainer=document.createElement("div"),this.gutterUtilityContainer.setAttribute("data-gutter-utility-slot","")),e)this.gutterUtilityButton!=null&&(this.gutterUtilityButton.remove(),this.gutterUtilityButton=void 0),this.gutterUtilitySlot==null&&(this.gutterUtilitySlot=document.createElement("slot"),this.gutterUtilitySlot.name="gutter-utility-slot"),this.gutterUtilitySlot.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilitySlot);else{if(this.gutterUtilitySlot?.remove(),this.gutterUtilitySlot=void 0,this.gutterUtilityButton==null){const n=document.createElement("div");n.innerHTML=ie(ae());const t=n.firstElementChild;if(!(t instanceof HTMLButtonElement))throw new Error("InteractionManager.ensureGutterUtilityNode: Node element should be a button");t.remove(),this.gutterUtilityButton=t}this.gutterUtilityButton.parentNode!==this.gutterUtilityContainer&&this.gutterUtilityContainer.replaceChildren(this.gutterUtilityButton)}}revealUtilityFromGutterPath(e){if(this.placeUtilityFromSelection())return;const n=this.resolvePointerTarget(e);w(n)&&n.numberColumn&&this.showUtilityOnLine(this.toEventBaseProps(n))}placeUtility(){if(!this.placeUtilityFromSelection()){if(this.hoveredLine!=null){this.showUtilityOnLine(this.hoveredLine);return}this.hideUtility()}}placeUtilityFromSelection(){const e=this.currentSelectionEnds();if(e==null)return!1;const n=this.targetForSelectionPoint(e.bottom);return n==null?this.hideUtility():this.showUtilityOnLine(this.toEventBaseProps(n)),!0}showUtilityOnLine(e){this.gutterUtilityContainer!=null&&(this.gutterUtilityLine=e,e.numberElement.appendChild(this.gutterUtilityContainer))}hideUtility(){this.gutterUtilityContainer?.remove(),this.gutterUtilityLine=void 0}currentSelectionEnds(){const e=this.getCurrentSelectionRange();return e==null?void 0:this.selectionEnds(e)}selectionEnds(e){const n={lineNumber:e.start,side:e.side},t={lineNumber:e.end,side:e.endSide??e.side},i=this.selectionPointRowIndex(n),a=this.selectionPointRowIndex(t);if(!(i==null||a==null))return i>a?{top:t,bottom:n}:{top:n,bottom:t}}selectionPointRowIndex(e){const n=this.getLineIndex(e.lineNumber,e.side);if(n!=null)return this.isSplitDiff()?n[1]:n[0]}targetForSelectionPoint(e){if(this.pre==null)return;const n=this.getLineIndex(e.lineNumber,e.side);if(n==null)return;const t=this.mode==="diff"?`${n[0]},${n[1]}`:`${n[0]}`,i=this.pre.querySelectorAll(`[data-column-number="${e.lineNumber}"][data-line-index="${t}"]`);for(const a of i){if(!(a instanceof HTMLElement))continue;const r=this.resolvePointerTarget(L(a));if(w(r)&&!(this.mode==="diff"&&e.side!=null&&r.side!==e.side))return r}}attachDocumentPointerListeners(){this.hasDocumentPointerListeners||(document.addEventListener("pointermove",this.handleDocumentPointerMove),document.addEventListener("pointerup",this.handleDocumentPointerUp),document.addEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!0)}detachDocumentPointerListeners(){this.hasDocumentPointerListeners&&(document.removeEventListener("pointermove",this.handleDocumentPointerMove),document.removeEventListener("pointerup",this.handleDocumentPointerUp),document.removeEventListener("pointercancel",this.handleDocumentPointerCancel),this.hasDocumentPointerListeners=!1)}clearPointerSession(){this.pointerSession={mode:"idle"}}clearPendingSingleLineState(){this.pointerSession.mode==="pendingSingleLineUnselect"&&(this.pointerSession={mode:"idle"})}selectionInfoFromPath(e,n){const t=this.resolvePointerTarget(e);if(w(t)&&!(n&&!t.numberColumn)&&t.splitLineIndex!=null)return{lineIndex:t.splitLineIndex,lineNumber:t.lineNumber,eventSide:this.mode==="diff"?t.side:void 0}}resolveSelectionInfo(e,n){const t=this.resolveSelectionPath(e,n);return t!=null?this.selectionInfoFromPath(t,n.requireNumberColumn):void 0}selectionPointFromPath(e){const n=this.resolvePointerTarget(e);if(w(n))return{lineNumber:n.lineNumber,side:this.mode==="diff"?n.side:void 0}}resolveSelectionPoint(e,n){const t=this.resolveSelectionPath(e,n);return t!=null?this.selectionPointFromPath(t):void 0}resolveSelectionPath(e,n){const t=n.excludeUtility!==!1;switch(n.source){case"event-path":return this.pathFromEventPath(e.composedPath(),t);case"coordinates-first":{const i=this.pathFromCoordinates(e,t);return i!==void 0?i??void 0:this.pathFromEventPath(e.composedPath(),t)}}}pathFromCoordinates(e,n){const t=this.hitTest(e);if(t!==void 0)return t===null?null:this.pathFromElement(t,n)??null}pathFromEventPath(e,n){if(!(n&&E(e))){for(const t of e)if(t instanceof Element)return this.pathFromElement(t,n)}}pathFromElement(e,n){const t=L(e);if(n&&E(t))return;const i=fe(e);return i!=null?L(i):this.pathFromAnnotationSlot(e)}pathFromAnnotationSlot(e){const n=ue(ce(e));if(n==null)return;const t=this.targetForSelectionPoint(n);return t!=null?L(t.lineElement):void 0}hitTest(e){if(!Number.isFinite(e.clientX)||!Number.isFinite(e.clientY))return;const n=this.pre?.getRootNode(),t=z(n)?n:z(document)?document:void 0;if(t!=null)return t.elementFromPoint(e.clientX,e.clientY)}getLineIndex(e,n){const{getLineIndex:t}=this.options;return t!=null?t(e,n):[e-1,e-1]}getCurrentSelectionRange(){return this.proposedSelectedRange!==void 0?this.proposedSelectedRange:this.selectedRange}clearProposedSelection(){this.proposedSelectedRange=void 0}updateSelection(e,n,t=!0){const i=this.getCurrentSelectionRange();let a;if(e==null)a=null;else{const r=this.selectionAnchor?.side??n,s=this.selectionAnchor?.lineNumber??e;a=this.buildSelectionRange(s,e,r,n)}H(i??void 0,a??void 0)||(this.activeLineHighlightSide=void 0,this.activeLineNumberOnly=!1,this.options.controlledSelection===!0?this.proposedSelectedRange=a:(this.selectedRange=a,this.queuedSelectionRender??=requestAnimationFrame(this.renderSelection)),this.placeUtility(),t&&this.notifySelectionChangeDelta())}getIndexesFromSelection(e,n){if(this.pre==null)return;const t=this.getLineIndex(e.start,e.side),i=this.getLineIndex(e.end,e.endSide??e.side);return t!=null&&i!=null?{start:n?t[1]:t[0],end:n?i[1]:i[0]}:void 0}highlightLineNumberOnly(){return this.activeLineHighlightSide!=null?this.activeLineNumberOnly:this.activeLineNumberOnly||this.editorAttached}renderSelection=()=>{if(this.queuedSelectionRender!=null&&(cancelAnimationFrame(this.queuedSelectionRender),this.queuedSelectionRender=void 0),this.pre==null||this.renderedSelectionRange===this.selectedRange)return;const e=this.pre.querySelectorAll("[data-selected-line]");for(const o of e)o.removeAttribute("data-selected-line");if(this.renderedSelectionRange=this.selectedRange,this.selectedRange==null)return;const{children:n}=this.pre;if(n.length===0)return;if(n.length>2)throw console.error(n),new Error("InteractionManager.renderSelection: Somehow there are more than 2 code elements...");const t=this.pre.getAttribute("data-diff-type")==="split",i=this.getIndexesFromSelection(this.selectedRange,t);if(i==null)throw console.error({rowRange:i,selectedRange:this.selectedRange}),new Error("InteractionManager.renderSelection: No valid rowRange");const a=i.start===i.end,r=Math.min(i.start,i.end),s=Math.max(i.start,i.end),l=this.highlightLineNumberOnly();for(const o of n){const d=this.activeLineHighlightSide;if(d!=null&&(d==="additions"&&o.hasAttribute("data-deletions")||d==="deletions"&&o.hasAttribute("data-additions")))continue;const[c,m]=o.children,h=m.children.length;if(h!==c.children.length)throw new Error("InteractionManager.renderSelection: gutter and content children dont match, something is wrong");for(let f=0;f<h;f++){const u=m.children[f],v=c.children[f];if(!(u instanceof HTMLElement)||!(v instanceof HTMLElement))continue;const b=this.parseLineIndex(u,t);if((b??0)>s)break;if(b==null||b<r)continue;let g=a?"single":b===r?"first":b===s?"last":"";v.setAttribute("data-selected-line",g),!l&&(u.setAttribute("data-selected-line",g),v.nextSibling instanceof HTMLElement&&u.nextSibling instanceof HTMLElement&&(u.nextSibling.hasAttribute("data-line-annotation")||u.nextSibling.hasAttribute("data-merge-conflict-actions"))&&(a?(g="last",u.setAttribute("data-selected-line","first")):b===r?g="":b===s&&u.setAttribute("data-selected-line",""),u.nextSibling.setAttribute("data-selected-line",g),v.nextSibling.setAttribute("data-selected-line",g)))}}};notifySelectionCommitted(){this.options.onLineSelected?.(this.getCurrentSelectionRange()??null)}notifySelectionChangeDelta(){this.options.onLineSelectionChange?.(this.getCurrentSelectionRange()??null)}notifySelectionStart(e){this.options.onLineSelectionStart?.(e)}notifySelectionEnd(e){this.options.onLineSelectionEnd?.(e)}toEventBaseProps(e){return this.mode==="file"?{type:"line",lineElement:e.lineElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn,numberElement:e.numberElement}:{type:"diff-line",annotationSide:e.side,lineType:e.lineType,lineElement:e.lineElement,numberElement:e.numberElement,lineNumber:e.lineNumber,numberColumn:e.numberColumn}}toTokenEventBaseProps({lineCharEnd:e,lineCharStart:n,lineNumber:t,side:i,tokenElement:a,tokenText:r}){return this.mode==="file"?{type:"token",lineCharEnd:e,lineCharStart:n,lineNumber:t,tokenElement:a,tokenText:r}:{type:"token",lineCharEnd:e,lineCharStart:n,lineNumber:t,side:i,tokenElement:a,tokenText:r}}buildSelectedLineRange(e,n){return this.buildSelectionRange(e.lineNumber,n.lineNumber,e.side,n.side)}buildSelectionRange(e,n,t,i){return{start:e,end:n,...t!=null?{side:t}:{},...t!==i&&i!=null?{endSide:i}:{}}}resolvePointerTarget(e){let n=!1,t,i,a,r,s,l,o,d,c,m;for(const f of e){if(!(f instanceof HTMLElement))continue;if(m==null&&f.hasAttribute("data-merge-conflict-action")){const g=f.getAttribute("data-merge-conflict-action")??void 0,y=f.getAttribute("data-merge-conflict-conflict-index")??void 0,x=y!=null?Number.parseInt(y,10):NaN;le(g)&&Number.isFinite(x)&&(m={kind:"merge-conflict-action",resolution:g,conflictIndex:x})}if(l==null&&f.hasAttribute("data-char")){l=f;const g=f.getAttribute("data-char");if(g!=null){const y=Number.parseInt(g,10);if(!Number.isNaN(y)){const x=f.textContent??"",N=y+x.length;(x.trim()!==""||this.options.enableTokenInteractionsOnWhitespace===!0)&&(o={tokenElement:l,lineCharStart:y,lineCharEnd:N,tokenText:x});continue}}}const u=s==null?f.getAttribute("data-column-number")??void 0:void 0;if(u!=null){s=f,c=Number.parseInt(u,10),n=!0,t=O(f),r=f.getAttribute("data-line-index")??void 0;continue}const v=a==null?f.getAttribute("data-line")??void 0:void 0;if(v!=null){a=f,c=Number.parseInt(v,10),t=O(f),r=f.getAttribute("data-line-index")??void 0;continue}if(d==null&&(f.hasAttribute("data-expand-button")||f.hasAttribute("data-unmodified-lines"))){d={hunkIndex:void 0,direction:f.hasAttribute("data-expand-up")?"up":f.hasAttribute("data-expand-down")?"down":"both",all:f.hasAttribute("data-expand-all-button")};continue}const b=d!=null?f.getAttribute("data-expand-index")??void 0:void 0;if(d!=null&&b!=null){const g=Number.parseInt(b,10);Number.isNaN(g)||(d.hunkIndex=g);continue}if(i==null&&f.hasAttribute("data-code")){i=f;break}}if(m!=null)return m;if(d?.hunkIndex!=null)return{type:"line-info",hunkIndex:d.hunkIndex,direction:d.direction,all:d.all};if(a??=r!=null?D(i,`[data-line][data-line-index="${r}"]`):void 0,s??=r!=null?D(i,`[data-column-number][data-line-index="${r}"]`):void 0,i==null||a==null||s==null||t==null||c==null||Number.isNaN(c))return;const h=this.parseLineIndex(a,this.isSplitDiff());return o!=null?this.mode==="file"?{kind:"token",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:void 0,splitLineIndex:h,...o}:{kind:"token",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:F(t,i),splitLineIndex:h,...o}:this.mode==="file"?{kind:"line",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:void 0,splitLineIndex:h}:{kind:"line",lineType:t,lineElement:a,lineNumber:c,numberColumn:n,numberElement:s,side:F(t,i),splitLineIndex:h}}isSplitDiff(){return this.pre?.getAttribute("data-diff-type")==="split"}parseLineIndex(e,n){const t=(e.getAttribute("data-line-index")??"").split(",").map(i=>Number.parseInt(i,10)).filter(i=>!Number.isNaN(i));if(n&&t.length===2)return t[1];if(!n)return t[0]}};function Me({enableTokenInteractionsOnWhitespace:e,enableGutterUtility:n,lineHoverHighlight:t,onGutterUtilityClick:i,onLineClick:a,onLineEnter:r,onLineLeave:s,onLineNumberClick:l,onTokenClick:o,onTokenEnter:d,onTokenLeave:c,renderGutterUtility:m,__debugPointerEvents:h,enableLineSelection:f,controlledSelection:u,onLineSelected:v,onLineSelectionStart:b,onLineSelectionChange:g,onLineSelectionEnd:y},x,N,W){return{enableTokenInteractionsOnWhitespace:e,enableGutterUtility:oe({enableGutterUtility:n,renderGutterUtility:m,onGutterUtilityClick:i}),usesCustomGutterUtility:m!=null,lineHoverHighlight:t,onGutterUtilityClick:i,onHunkExpand:x,onMergeConflictActionClick:W,onLineClick:a,onLineEnter:r,onLineLeave:s,onLineNumberClick:l,onTokenClick:o,onTokenEnter:d,onTokenLeave:c,__debugPointerEvents:h,enableLineSelection:f,controlledSelection:u,onLineSelected:v,onLineSelectionStart:b,onLineSelectionChange:g,onLineSelectionEnd:y,getLineIndex:N}}function oe({enableGutterUtility:e,renderGutterUtility:n,onGutterUtilityClick:t}){if(t!=null&&n!=null)throw new Error("Cannot use both 'onGutterUtilityClick' and 'renderGutterUtility'. Use only one gutter utility API.");return e??!1}function w(e){return e!=null&&"kind"in e&&e.kind==="line"}function A(e){return e!=null&&"kind"in e&&e.kind==="token"}function T(e){return w(e)||A(e)}function se(e){return"type"in e&&e.type==="line-info"}function de(e){return"kind"in e&&e.kind==="merge-conflict-action"}function le(e){return e==="current"||e==="incoming"||e==="both"}function D(e,n){const t=e?.querySelector(n);return t instanceof HTMLElement?t:void 0}function L(e){const n=[];let t=e;for(;t!=null;)n.push(t),t=t.parentNode;return n}function fe(e){const n=e.closest("[data-line], [data-column-number]");if(n instanceof HTMLElement)return n;const t=e.closest('[data-line-annotation], [data-gutter-buffer="annotation"]');if(!(t instanceof HTMLElement))return;const i=t.previousElementSibling;return i instanceof HTMLElement&&(i.hasAttribute("data-line")||i.hasAttribute("data-column-number"))?i:void 0}function ce(e){const n=e.closest('[slot^="annotation-"]');if(n instanceof HTMLElement)return n.getAttribute("slot")??void 0;if(e instanceof HTMLElement){const t=e.getAttribute("name")??void 0;return t!=null&&t.startsWith("annotation-")?t:void 0}}function ue(e){if(e==null)return;const n=/^annotation-(?:(additions|deletions)-)?(\d+)$/.exec(e);if(n==null)return;const t=Number.parseInt(n[2],10);if(!(!Number.isFinite(t)||t<=0))return{lineNumber:t,side:n[1]}}function z(e){return e!=null&&typeof e.elementFromPoint=="function"}function F(e,n){switch(e){case"change-deletion":return"deletions";case"change-addition":return"additions";default:return n.hasAttribute("data-deletions")?"deletions":"additions"}}function O(e){const n=e.getAttribute("data-line-type");if(n!=null)switch(n){case"change-deletion":case"change-addition":case"context":case"context-expanded":return n;default:return}}function E(e){for(const n of e)if(n instanceof HTMLElement&&(n.hasAttribute("data-utility-button")||n.hasAttribute("data-gutter-utility-slot")||n.getAttribute("slot")==="gutter-utility-slot"||n.getAttribute("name")==="gutter-utility-slot"))return!0;return!1}function k(e="none",n,...t){switch(e){case"none":return;case"both":break;case"click":if(n!=="click")return;break;case"move":if(n!=="move")return;break}console.log(...t)}var Ue=class S{static resizeObserver;static managersByElement=new Map;static getResizeObserver(){const n=S.resizeObserver??new ResizeObserver(S.handleSharedResizeEntries);return S.resizeObserver=n,n}static handleSharedResizeEntries(n){const t=new Map;for(const i of n){const a=S.managersByElement.get(i.target);if(a==null)continue;const r=t.get(a);r==null?t.set(a,[i]):r.push(i)}for(const[i,a]of t)i.handleResizeEntries(a)}observedNodes=new Map;setup(n,t){const i=new Set;let a=0;const r=new Map(this.observedNodes);this.observedNodes.clear();for(const s of n.children){if(a===2)break;const l=(()=>{if(s instanceof HTMLElement&&s.tagName==="CODE")return s})();if(l==null)continue;a++;let o=r.get(l);if(o!=null&&o.type!=="code")throw new Error("ResizeManager.setup: somehow a code node is being used for an annotation, should be impossible");let d=l.firstElementChild;d instanceof HTMLElement||(d=null),o!=null?(this.observedNodes.set(l,o),r.delete(l),o.numberElement!==d?(o.numberElement!=null&&(this.unobserve(o.numberElement),r.delete(o.numberElement)),d!=null&&(this.observe(d),r.delete(d),this.observedNodes.set(d,o)),o.numberElement=d,o.numberWidth=0):o.numberElement!=null?(r.delete(o.numberElement),this.observedNodes.set(o.numberElement,o)):o.numberWidth=0):(o={type:"code",codeElement:l,numberElement:d,codeWidth:"auto",numberWidth:0},this.observedNodes.set(l,o),this.observe(l),d!=null&&(this.observedNodes.set(d,o),this.observe(d)))}if(a>1&&!t){const s=n.querySelectorAll('[data-line-annotation*=","]'),l=new Map;for(const o of s){if(!(o instanceof HTMLElement))continue;const d=o.getAttribute("data-line-annotation")??"";if(!/^-?\d+,-?\d+$/.test(d)){console.error("DiffFileRenderer.setupResizeObserver: Invalid element or annotation",{lineAnnotation:d,element:o});continue}let c=l.get(d);c==null&&(c=[],l.set(d,c)),c.push(o)}for(const[o,d]of l){if(d.length!==2){console.error("DiffFileRenderer.setupResizeObserver: Bad Pair",o,d);continue}const[c,m]=d,h=c.firstElementChild,f=m.firstElementChild;if(!(c instanceof HTMLElement)||!(m instanceof HTMLElement)||!(h instanceof HTMLElement)||!(f instanceof HTMLElement))continue;let u=r.get(h);if(u!=null){this.observedNodes.set(h,u),this.observedNodes.set(f,u),r.delete(h),r.delete(f);continue}const v=h.getBoundingClientRect().height,b=f.getBoundingClientRect().height;u={type:"annotations",column1:{container:c,child:h,childHeight:v},column2:{container:m,child:f,childHeight:b},currentHeight:"auto"},i.add({child1:h,child2:f,item:u,newHeight:Math.max(v,b)})}for(const o of i)this.applyNewHeight(o.item,o.newHeight),this.observedNodes.set(o.child1,o.item),this.observedNodes.set(o.child2,o.item),this.observe(o.child1),this.observe(o.child2);i.clear()}for(const[s,l]of r)this.unobserve(s),l.type==="code"?ge(l):pe(l);r.clear()}cleanUp(){for(const n of this.observedNodes.keys())this.unobserve(n);this.observedNodes.clear()}observe(n){const{managersByElement:t}=S,i=t.get(n);if(i!==this){if(i!=null&&i!==this)throw new Error("ResizeManager.observe: element is already owned by another ResizeManager");t.set(n,this),S.getResizeObserver().observe(n)}}unobserve(n){const{managersByElement:t,resizeObserver:i}=S,a=t.get(n);if(a!=null){if(a!==this)throw new Error("ResizeManager.unobserve: element is owned by another ResizeManager");t.delete(n),i?.unobserve(n),i!=null&&t.size===0&&(i.disconnect(),S.resizeObserver=void 0)}}handleResizeEntries(n){const t=new Map,i=new Set;for(const a of n){const{target:r,borderBoxSize:s,contentBoxSize:l}=a;if(!(r instanceof HTMLElement)){console.error("ResizeManager.handleResizeEntries: Invalid element for ResizeObserver",a);continue}const o=this.observedNodes.get(r);if(o==null){console.error("ResizeManager.handleResizeEntries: Not a valid observed node",a);continue}if(o.type==="annotations"){const d=(()=>{if(r===o.column1.child)return o.column1;if(r===o.column2.child)return o.column2})();if(d==null){console.error("ResizeManager.handleResizeEntries: Couldn't find a column for",{item:o,target:r});continue}d.childHeight=s[0].blockSize,i.add(o)}else if(o.type==="code"){const d=t.get(o)??{},c=l[0].inlineSize;r===o.codeElement?d.codeInlineSize=c:r===o.numberElement&&(d.numberInlineSize=c),t.set(o,d)}}this.applyAnnotationUpdates(i),i.clear(),this.applyColumnUpdates(t),t.clear()}applyAnnotationUpdates(n){for(const t of n)this.applyNewHeight(t,Math.max(t.column1.childHeight,t.column2.childHeight))}applyColumnUpdates=n=>{for(const[t,i]of n){const a=i.codeInlineSize!=null?he(i.codeInlineSize):t.codeWidth,r=i.numberInlineSize!=null?me(i.numberInlineSize):t.numberWidth,s=a!==t.codeWidth,l=r!==t.numberWidth;if(!(!s&&!l)&&(t.codeWidth=a,t.numberWidth=r,s&&t.codeElement.style.setProperty("--diffs-column-width",`${typeof a=="number"?`${a}px`:"auto"}`),l&&t.codeElement.style.setProperty("--diffs-column-number-width",`${r===0?"auto":`${r}px`}`),s||l&&a!=="auto")){const o=typeof a=="number"?Math.max(a-r,0):0;t.codeElement.style.setProperty("--diffs-column-content-width",`${o>0?`${o}px`:"auto"}`)}}};applyNewHeight(n,t){t!==n.currentHeight&&(n.currentHeight=Math.max(t,0),n.column1.container.style.setProperty("--diffs-annotation-min-height",`${n.currentHeight}px`),n.column2.container.style.setProperty("--diffs-annotation-min-height",`${n.currentHeight}px`))}};function he(e){const n=Math.max(Math.floor(e),0);return n===0?"auto":n}function me(e){return Math.max(Math.ceil(e),0)}function ge(e){e.codeElement.isConnected&&(e.codeElement.style.removeProperty("--diffs-column-content-width"),e.codeElement.style.removeProperty("--diffs-column-number-width"),e.codeElement.style.removeProperty("--diffs-column-width"))}function pe(e){e.column1.container.isConnected&&e.column1.container.style.removeProperty("--diffs-annotation-min-height"),e.column2.container.isConnected&&e.column2.container.style.removeProperty("--diffs-annotation-min-height")}function Re(e){for(const n of Array.isArray(e)?e:[e])if(!(n==="text"||n==="ansi")&&!ne.has(n))return!1;return!0}function He(e){for(const n of G(e))if(!te.has(n))return!1;return!0}function De(e,n){return e==null||n==null?e===n:e.startingLine===n.startingLine&&e.totalLines===n.totalLines&&e.bufferBefore===n.bufferBefore&&e.bufferAfter===n.bufferAfter}function ze(e){return p({tagName:"div",children:[p({tagName:"div",children:e.annotations?.map(n=>p({tagName:"slot",properties:{name:n}})),properties:{"data-annotation-content":""}})],properties:{"data-line-annotation":`${e.hunkIndex},${e.lineIndex}`}})}function be(e){switch(e){case"file":return"diffs-icon-file-code";case"change":return"diffs-icon-symbol-modified";case"new":return"diffs-icon-symbol-added";case"deleted":return"diffs-icon-symbol-deleted";case"rename-pure":case"rename-changed":return"diffs-icon-symbol-moved"}}function Fe({fileOrDiff:e,mode:n,stickyHeader:t}){const i="type"in e?e:void 0,a={"data-diffs-header":n,"data-change-type":i?.type,"data-sticky":t?"":void 0};return p({tagName:"div",children:[n==="custom"?p({tagName:"slot",properties:{name:V}}):ve({name:e.name,prevName:"prevName"in e?e.prevName:void 0,iconType:i?.type??"file"}),...n==="custom"?[]:[xe(i)]],properties:a})}function ve({name:e,prevName:n,iconType:t}){const i=[p({tagName:"slot",properties:{name:Y}}),I({name:be(t),properties:{"data-change-icon":t}})];return n!=null&&(i.push(p({tagName:"div",children:[p({tagName:"bdi",children:[C(n)]})],properties:{"data-prev-name":""}})),i.push(I({name:"diffs-icon-arrow-right-short",properties:{"data-rename-icon":""}}))),i.push(p({tagName:"div",children:[p({tagName:"bdi",children:[C(e)]})],properties:{"data-title":""}})),i.push(p({tagName:"slot",properties:{name:X}})),p({tagName:"div",children:i,properties:{"data-header-content":""}})}function xe(e){const n=[];if(e!=null){let t=0,i=0;for(const a of e.hunks)t+=a.additionLines,i+=a.deletionLines;(i>0||t===0)&&n.push(p({tagName:"span",children:[C(`-${i}`)],properties:{"data-deletions-count":""}})),(t>0||i===0)&&n.push(p({tagName:"span",children:[C(`+${t}`)],properties:{"data-additions-count":""}}))}return n.push(p({tagName:"slot",properties:{name:j}})),p({tagName:"div",children:n,properties:{"data-metadata":""}})}function Oe(e){return p({tagName:"pre",properties:ye(e)})}function ye({diffIndicators:e,disableBackground:n,disableLineNumbers:t,overflow:i,split:a,totalLines:r,type:s,customProperties:l}){return{...l,"data-diff":s==="diff"?"":void 0,"data-file":s==="file"?"":void 0,"data-diff-type":s==="diff"?a?"split":"single":void 0,"data-overflow":i,"data-disable-line-numbers":t?"":void 0,"data-background":n?void 0:"","data-indicators":e==="bars"||e==="classic"?e:void 0,tabIndex:0,style:`--diffs-min-number-column-width-default:${`${r}`.length}ch;`}}function Be(e,{theme:n,preferredHighlighter:t="shiki-js"}){return{langs:[e??"text"],themes:G(n),preferredHighlighter:t}}function $e(e){return`annotation-${"side"in e?`${e.side}-`:""}${e.lineNumber}`}const Ge="-1,-1";function _e(e){return e?.some(n=>n.lineNumber===0)??!1}function qe(e){const n=e[0];return n!=null&&n.length>0?n:void 0}function We(e){return e.startingLine===0&&e.totalLines>0}function Ve(e,n){return p({tagName:"div",children:e,properties:{"data-content":"",style:`grid-row: span ${n}`}})}function Ye(e){return e.useTokenTransformer===!0||e.onTokenClick!=null||e.onTokenEnter!=null||e.onTokenLeave!=null}const Xe=`<svg data-icon-sprite aria-hidden="true" width="0" height="0">
2
2
  <symbol id="diffs-icon-arrow-right-short" viewBox="0 0 16 16">
3
3
  <path d="M8.47 4.22a.75.75 0 0 0 0 1.06l1.97 1.97H3.75a.75.75 0 0 0 0 1.5h6.69l-1.97 1.97a.75.75 0 1 0 1.06 1.06l3.25-3.25a.75.75 0 0 0 0-1.06L9.53 4.22a.75.75 0 0 0-1.06 0"/>
4
4
  </symbol>
package/dist/index.html CHANGED
@@ -540,15 +540,15 @@
540
540
  }
541
541
  }
542
542
  </style>
543
- <script type="module" crossorigin src="/assets/main-DOlk_lfi.js"></script>
543
+ <script type="module" crossorigin src="/assets/main-DoiadX0a.js"></script>
544
544
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
545
545
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-Bz1tRBxM.js">
546
546
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CXhN0IMY.js">
547
547
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
548
548
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-BKkUfl9q.js">
549
549
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-t_7AcMTv.js">
550
- <link rel="modulepreload" crossorigin href="/assets/index-fmzQmSSv.js">
551
- <link rel="modulepreload" crossorigin href="/assets/runtimeSurface-X62LLBLv.js">
550
+ <link rel="modulepreload" crossorigin href="/assets/index-I2QYqABE.js">
551
+ <link rel="modulepreload" crossorigin href="/assets/runtimeSurface-CFwnvks_.js">
552
552
  <link rel="stylesheet" crossorigin href="/assets/index-BaLCg7tL.css">
553
553
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-css-Cp579UoJ.css">
554
554
  </head>
@@ -89,14 +89,14 @@
89
89
  }
90
90
  </style>
91
91
 
92
- <script type="module" crossorigin src="/assets/miniChat-Dy9h0B6G.js"></script>
92
+ <script type="module" crossorigin src="/assets/miniChat-Ck6MEZ9Q.js"></script>
93
93
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
94
94
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-Bz1tRBxM.js">
95
95
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CXhN0IMY.js">
96
96
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
97
97
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-BKkUfl9q.js">
98
98
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-t_7AcMTv.js">
99
- <link rel="modulepreload" crossorigin href="/assets/index-fmzQmSSv.js">
99
+ <link rel="modulepreload" crossorigin href="/assets/index-I2QYqABE.js">
100
100
  <link rel="stylesheet" crossorigin href="/assets/index-BaLCg7tL.css">
101
101
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-css-Cp579UoJ.css">
102
102
  </head>
package/dist/mobile.html CHANGED
@@ -63,14 +63,14 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-CWrtn0Si.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-BucKVm1P.js"></script>
67
67
  <link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
68
68
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-Bz1tRBxM.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CXhN0IMY.js">
70
70
  <link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
71
71
  <link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-BKkUfl9q.js">
72
72
  <link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-t_7AcMTv.js">
73
- <link rel="modulepreload" crossorigin href="/assets/index-fmzQmSSv.js">
73
+ <link rel="modulepreload" crossorigin href="/assets/index-I2QYqABE.js">
74
74
  <link rel="stylesheet" crossorigin href="/assets/index-BaLCg7tL.css">
75
75
  <link rel="stylesheet" crossorigin href="/assets/vendor-katex-css-Cp579UoJ.css">
76
76
  </head>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -13,7 +13,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
13
13
  - `extension-name.js` owns path-free extension display names for `extensions.list` and the `source` of runtime `extension.error` events. A single-file extension is named after its file; an `index` entry point is named after its nearest non-generic directory, or the package root for package extensions. Neither surface ever carries a server path.
14
14
  - `extension-tool-render.js` owns daemon-side rendering for Pi extension tools that define `renderCall` or `renderResult`. Built-in tools are excluded so PiChamber retains native tool card rendering. Global Pi TUI theme symbols are installed once without overriding an existing theme. Partial updates render both the collapsed and expanded result slots (the browser draws the expanded slot only when a row is expanded), are throttled at 250ms with a trailing timer and component `invalidate()` trigger, the latest live render of a running tool is kept and included in session detail so a client opening mid-run sees the working state, settled results are rendered only for messages a history page selects (never for the whole branch) and memoized per toolResult message for history replay, and rendered ANSI lines are bounded to 100 columns, ≤200 lines, and ≤2000 characters per line. Its exported `renderComponentLines` helper carries those same bounds for message renders.
15
15
  - `extension-message-render.js` owns daemon-side rendering for `pi.registerMessageRenderer(customType, renderer)`. The renderer is resolved from the owning session's `extensionRunner` (a missing lookup function or a throwing lookup means no render) and called once collapsed (`expanded: false`) and once expanded (`expanded: true`) with `outputPad: 0`, `keyText()`/`keyHint()` from `extension-keybindings.js`, and the same extension theme tool renders use; each component renders at 100 columns through the shared line bounds, and every rendered line passes through attachment redaction. Live `extension.message` events and replayed `custom_message` history entries both carry optional `render: { message, messageExpanded? }` beside `customType`/`details` (public routes re-apply the same 200-line/2000-char caps and drop malformed shapes). Replay rebuilds the `{ role: 'custom', customType, content, display, details, timestamp }` input from the persisted entry so the renderer sees identical input live and on replay; renders resolve lazily for only the history page actually returned (the same pending-render mechanism as settled tool renders) and are memoized per entry. A missing/throwing renderer, a falsy component, or an empty collapsed slot omits `render` entirely; a failing or line-identical expanded slot omits `messageExpanded`. Renderer failure never breaks publication: the message still goes out with text/details, and other messages and sessions are unaffected. Only displayable messages (`display !== false`) render.
16
- - `extension-custom-host.js` owns `ctx.ui.custom()` surfaces: component lifetime, the TUI stub (`stop()`/`start()` throw), key focus, nested overlays from `tui.showOverlay`, overlay handles, render scheduling (the first change after a quiet spell draws on the next tick, later ones at most every 33 ms), and frames. Overlays are placed by pi-tui's own `resolveOverlayLayout` on a screen the size of the browser's chat pane (`screenColumns`); inline surfaces render at the composer column width (`columns`). Each session has one size, set by the client that last sent input, Close, or a viewport report with `claim` (the driver; the browser claims on a tap on a surface or its dimmed pane). A new top-level surface goes to the client whose `clientId` came with the session's latest prompt, steer, or follow-up (`openerClientFor`), at once if that client reported a size, else on its first report; a viewport report without `claim` never takes over otherwise, and a size change applies after 150 ms. Extension code never throws into a timer: an `overlayOptions` function that throws keeps its last options, any other render-time failure closes that surface, and a surface whose first render fails is removed before `custom()` rejects. A factory that resolves after its session closed or reloaded resolves `custom()` with `undefined` and shows nothing. Overlays a factory shows with `tui.showOverlay` before returning (Pi's overlay focus demo shows its panels from the constructor) become children of the surface once it opens, so its Close takes them along and keys sent to it reach the panel it focused; if the surface never opens they are removed, and `hideOverlay()` from a factory only touches its own overlays. `focus` (the browser's tab stack, `extensions.custom.focus`) does what `handle.focus()` does for a shown nested panel, makes the sender the driver, and redraws that panel's family, since extensions read `isFocused()` while rendering; it refuses top-level surfaces and hidden panels. Input requests are capped at 256 items and 65,536 characters in all (`isValidCustomInputItems`, checked by the route and here); keys stay with the surface they were sent to and its nested overlays, a non-capturing overlay takes keys only while it or an overlay it opened holds focus (as pi-tui hands keys to the focused component), and keys for an open surface that takes none right now are dropped with an accepted reply, not a not-open one. SGR mouse reports (`\x1b[<b;x;y(M|m)`, cells local to the surface) never reach `handleInput`: they become pi-tui `TuiMouseEvent`s routed as pi-tui's alt screen does (`dispatchMouseEvent`; the press target keeps the gesture, a release on the press cell adds a `click` with a 500 ms click count, `capture`, `focus` and render defaults follow pi-tui). Mouse reports also reach non-capturing overlays, and a `focus` answer gives one the keys; since PiChamber sends no extension shortcuts, a press on a non-capturing overlay whose component has `handleInput` also gives it focus. Frame lines are capped at `MAX_CUSTOM_LINE_CHARS` (16,384) by `capLine`, which never cuts inside an escape sequence or a surrogate pair. Every surface ends exactly once (`done`, Close, render error, session close, reload, daemon stop) with a resolved promise, a disposed component, and an `extension.custom.dismiss`. Capturing top-level surfaces register with `pendingInput`, and an open surface blocks idle disposal. `extension.custom` metadata and dismissals are ordinary replayed events; `extension.custom.frame` is published with `publishTransient`, which shares the sequence and stream epoch but skips the replay log, so a subscriber that attached by replay is sent each open surface's full frame afterwards (`keyframes`), and snapshots and `sessions.open` detail carry `extensionSurfaces` with full frames. The bridge's `custom()` delegates here; the bridge reports `mode: 'tui'`, so extensions that check `ctx.mode === 'tui'` (Pi's `snake`, `todo`, `question` examples, the MCP manager) open surfaces. `setHeader`, `setFooter`, `setEditorComponent` and `onTerminalInput` stay no-ops.
16
+ - `extension-custom-host.js` owns `ctx.ui.custom()` surfaces: component lifetime, the TUI stub (`stop()`/`start()` throw), key focus, nested overlays from `tui.showOverlay`, overlay handles, render scheduling (the first change after a quiet spell draws on the next tick, later ones at most every 33 ms), and frames. Overlays are placed by pi-tui's own `resolveOverlayLayout` on a screen the size of the browser's chat pane (`screenColumns`); inline surfaces render at the composer column width (`columns`). Each session has one size, set by the client that last sent input, the Esc button, or a viewport report with `claim` (the driver; the browser claims on a tap on a surface or its dimmed pane). A new top-level surface goes to the client whose `clientId` came with the session's latest prompt, steer, or follow-up (`openerClientFor`), at once if that client reported a size, else on its first report; a viewport report without `claim` never takes over otherwise, and a size change applies after 150 ms. Extension code never throws into a timer: an `overlayOptions` function that throws keeps its last options, any other render-time failure closes that surface, and a surface whose first render fails is removed before `custom()` rejects. A factory that resolves after its session closed or reloaded resolves `custom()` with `undefined` and shows nothing. Overlays a factory shows with `tui.showOverlay` before returning (Pi's overlay focus demo shows its panels from the constructor) become children of the surface once it opens, so ending it takes them along and keys sent to it reach the panel it focused; if the surface never opens they are removed, and `hideOverlay()` from a factory only touches its own overlays. `focus` (the browser's tab stack, `extensions.custom.focus`) does what `handle.focus()` does for a shown nested panel, makes the sender the driver, and redraws that panel's family, since extensions read `isFocused()` while rendering; it refuses top-level surfaces and hidden panels. The Esc button (`extensions.custom.close`, top-level surfaces and nested panels alike) presses Esc (`\x1b`) for the user through `handleInput`, once per press, because Pi has no host Close, `custom()` takes no cancel signal, and extensions that keep a handle to their overlay (pi-btw) only learn it closed from their own Esc handler. The Esc goes where a key typed at the surface would (an overlay it opened and focused, such as a confirmation, else the surface's component), even when the surface is non-capturing, unfocused, or hidden, and never reaches another surface or the session's turn. It does nothing a typed Esc would not: a component that closes itself ends with `done`, and one that stays open (an Esc that only stopped a running answer, a confirmation it opened, or a component that ignores Esc) stays open until the next press, as in Pi. Only a target with no `handleInput`, or whose Esc throws, is ended at once, so a surface that can never take a key cannot block the session: `custom()` resolves `undefined`, nested overlays go with it, and the dismissal is `cancelled`. `close` answers `{ closed: true }` once the Esc is delivered; the client keeps the surface until the dismissal arrives. Input requests are capped at 256 items and 65,536 characters in all (`isValidCustomInputItems`, checked by the route and here); keys stay with the surface they were sent to and its nested overlays, a non-capturing overlay takes keys only while it or an overlay it opened holds focus (as pi-tui hands keys to the focused component), and keys for an open surface that takes none right now are dropped with an accepted reply, not a not-open one. SGR mouse reports (`\x1b[<b;x;y(M|m)`, cells local to the surface) never reach `handleInput`: they become pi-tui `TuiMouseEvent`s routed as pi-tui's alt screen does (`dispatchMouseEvent`; the press target keeps the gesture, a release on the press cell adds a `click` with a 500 ms click count, `capture`, `focus` and render defaults follow pi-tui). Mouse reports also reach non-capturing overlays, and a `focus` answer gives one the keys; since PiChamber sends no extension shortcuts, a press on a non-capturing overlay whose component has `handleInput` also gives it focus. Frame lines are capped at `MAX_CUSTOM_LINE_CHARS` (16,384) by `capLine`, which never cuts inside an escape sequence or a surrogate pair. Every surface ends exactly once (`done`, the Esc button on a surface that takes no keys, render error, session close, reload, daemon stop) with a resolved promise, a disposed component, and an `extension.custom.dismiss`. Capturing top-level surfaces register with `pendingInput`, and an open surface blocks idle disposal. `extension.custom` metadata and dismissals are ordinary replayed events; `extension.custom.frame` is published with `publishTransient`, which shares the sequence and stream epoch but skips the replay log, so a subscriber that attached by replay is sent each open surface's full frame afterwards (`keyframes`), and snapshots and `sessions.open` detail carry `extensionSurfaces` with full frames. The bridge's `custom()` delegates here; the bridge reports `mode: 'tui'`, so extensions that check `ctx.mode === 'tui'` (Pi's `snake`, `todo`, `question` examples, the MCP manager) open surfaces. `setHeader`, `setFooter`, `setEditorComponent` and `onTerminalInput` stay no-ops.
17
17
  - `extension-keybindings.js` owns the `KeybindingHints` (`keyText()`, `keyHint()`) that Pi 1.5.0 passes to tool renderers and message renderers. Pi's keybindings are terminal shortcuts, and PiChamber binds none of them: rows expand on click. So `keyText()` returns an empty string and `keyHint()` returns only the description, styled `muted` as in Pi, with no leading space. A Pi hint such as `(40 more lines, ctrl+o to expand)` reads `(40 more lines, to expand)`. Neither function throws.
18
18
  - `session-daemon.js`
19
19
  - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` with a daemon-owned UI bridge that reports `mode: 'tui'`, because the daemon hosts `ctx.ui.custom()` components; terminal chrome (`setHeader`, `setFooter`, `setEditorComponent`, `onTerminalInput`) stays a no-op. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
@@ -53,7 +53,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
53
53
  - The public health route deliberately whitelists its response fields (state, protocol version, capability names, and the opaque public `streamEpoch`). It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
54
54
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
55
55
  - Frames are LF-delimited JSON. One frame has a 16 MiB maximum. Complete frames are parsed before the client bounds the remaining incomplete frame. Invalid JSON reports `MALFORMED_DAEMON_RESPONSE`; an oversized response reports `DAEMON_RESPONSE_TOO_LARGE`. A malformed, oversized, unauthenticated, or invalid request closes the connection.
56
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/models.add/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/pendingInput/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. `sessions.pendingInput` takes no arguments, is never session-scoped or routed to engines, and returns `{ sessions: [{ sessionId, directory, pending }], sequence, streamEpoch }` for sessions with a non-null summary; `runtime.health` advertises it. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes plus the requested directory's runtime (started when it is not resident); the returned catalog comes from that directory's runtime via `providers.list`. Concurrent refreshes share one task per resolved directory, never across directories; refreshes for different directories run one after another so their temporary catalog keys never interleave. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction, passing the same `getDeviceId` login option as the Pi CLI (backed by the runtime `SettingsManager.getOrCreateDeviceId()`) because flows such as Sign in with ChatGPT reject logins without a stable installation ID. A failed attempt projects Pi's error message (with its causes, URL query strings stripped so a pasted callback never echoes an authorization code, capped at 500 characters) beside the stable `PROVIDER_AUTH_REQUIRED` code; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.models.add` appends one model (`id` required; optional `name`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, and `maxTokens`) atomically without replacing the provider. The model configuration store owns normalization and validation. The daemon rejects duplicate or unavailable live models, seeds a missing file provider only from authoritative live metadata when safely representable, rejects extension registrations with an explicit `models` array, and uses the same deferred recreation as `providers.models.set`. A successful recreation publishes a provider-catalog invalidation so connected settings views load the new authoritative catalog. Provider edits preserve unexposed existing model metadata server-side while public projections remain credential-blind. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` returns cached or incrementally scanned header, first-prompt, and name fields. For a row whose runtime is resident, the list uses `sessionManager.getSessionName()` instead of the disk name, so unflushed renames and clears show immediately. Each listed row whose runtime is resident in this daemon (including unpersisted resident sessions) carries `live: { lifecycle, sequence, retry?, runStartedAt?, serverNow }`, sampled synchronously with the current event `sequence` from the same retry/streaming/run-start state as snapshots; rows without a resident runtime carry no `live`, which clients treat as unknown rather than idle. Every Pi row additionally carries `inputState: { pending, sequence }` from the pending-input index (`pending` is `null` when authoritatively nothing is pending, stamped with the same observed sequence as `live`), so every device learns blocked sessions without opening them. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first prompt, and rename). Like the Pi CLI, the daemon never persists an auto-title: on the first conversation prompt of an unnamed session it publishes the derived title live without appending `session_info`, and lists derive the same title from the first user prompt. Renames of a resident session call Pi's `session.setSessionName`, which appends `session_info` and emits `session_info_changed` to listeners and extensions; the subscriber publishes the single `session.updated`. Non-resident renames open the file and append, as Pi's session picker does, and publish directly. `session.updated` with `title: ''` means Pi cleared the name; clients fall back to the title derived from the first prompt, and older clients ignore empty titles to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Nested tool execution events carrying a non-empty `parentToolCallId` are skipped because Pi records nested calls on the parent tool result and omits them from transcript messages. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal of persisted sessions, and clear on explicit session deletion, confirmed ephemeral expiration (which publishes `session.deleted`), or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
56
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/models.add/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/pendingInput/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. `sessions.pendingInput` takes no arguments, is never session-scoped or routed to engines, and returns `{ sessions: [{ sessionId, directory, pending }], sequence, streamEpoch }` for sessions with a non-null summary; `runtime.health` advertises it. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes plus the requested directory's runtime (started when it is not resident); the returned catalog comes from that directory's runtime via `providers.list`. Concurrent refreshes share one task per resolved directory, never across directories; refreshes for different directories run one after another so their temporary catalog keys never interleave. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction, passing the same `getDeviceId` login option as the Pi CLI (backed by the runtime `SettingsManager.getOrCreateDeviceId()`) because flows such as Sign in with ChatGPT reject logins without a stable installation ID. A failed attempt projects Pi's error message (with its causes, URL query strings stripped so a pasted callback never echoes an authorization code, capped at 500 characters) beside the stable `PROVIDER_AUTH_REQUIRED` code; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.models.add` appends one model (`id` required; optional `name`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, and `maxTokens`) atomically without replacing the provider. The model configuration store owns normalization and validation. The daemon rejects duplicate or unavailable live models, seeds a missing file provider only from authoritative live metadata when safely representable, rejects extension registrations with an explicit `models` array, and uses the same deferred recreation as `providers.models.set`. A successful recreation publishes a provider-catalog invalidation so connected settings views load the new authoritative catalog. Provider edits preserve unexposed existing model metadata server-side while public projections remain credential-blind. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` returns cached or incrementally scanned header, first-prompt, and name fields. For a row whose runtime is resident, the list uses `sessionManager.getSessionName()` instead of the disk name, so unflushed renames and clears show immediately. Unpersisted resident sessions are listed too, except the fresh empty session a runtime starts with when it is started only to answer a folder's catalogs (`providers.list`, `resources.list`, `extensions.list`, runtime recreation) with no JSONL to reopen: nobody asked for it, so it stays out of listings until it holds a non-`custom` message (a user prompt, an assistant reply, or anything else that is not an extension's custom message) or a name, since what an extension adds at `session_start` lands in every such session, otherwise every folder switch would add an untitled "Awaiting first prompt" row. Each listed row whose runtime is resident in this daemon (including unpersisted resident sessions) carries `live: { lifecycle, sequence, retry?, runStartedAt?, serverNow }`, sampled synchronously with the current event `sequence` from the same retry/streaming/run-start state as snapshots; rows without a resident runtime carry no `live`, which clients treat as unknown rather than idle. Every Pi row additionally carries `inputState: { pending, sequence }` from the pending-input index (`pending` is `null` when authoritatively nothing is pending, stamped with the same observed sequence as `live`), so every device learns blocked sessions without opening them. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first prompt, and rename). Like the Pi CLI, the daemon never persists an auto-title: on the first conversation prompt of an unnamed session it publishes the derived title live without appending `session_info`, and lists derive the same title from the first user prompt. Renames of a resident session call Pi's `session.setSessionName`, which appends `session_info` and emits `session_info_changed` to listeners and extensions; the subscriber publishes the single `session.updated`. Non-resident renames open the file and append, as Pi's session picker does, and publish directly. `session.updated` with `title: ''` means Pi cleared the name; clients fall back to the title derived from the first prompt, and older clients ignore empty titles to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Nested tool execution events carrying a non-empty `parentToolCallId` are skipped because Pi records nested calls on the parent tool result and omits them from transcript messages. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal of persisted sessions, and clear on explicit session deletion, confirmed ephemeral expiration (which publishes `session.deleted`), or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
57
57
  - Each event and reconnect snapshot has a monotonic sequence. Replay is capability-negotiated: the subscriber stamps its cursor with the `streamEpoch` it was established under, a marker-less cursor fails as `DAEMON_PROTOCOL_MISMATCH`, and a cursor from a retired epoch resyncs from a snapshot instead of replaying — even when this daemon's sequence numerically overtook the old cursor, replaying from it would silently skip the head of the new space. Every event, snapshot, and health result carries an opaque random `streamEpoch` regenerated on every daemon process start (never derived from daemon id, profile key, pid, or any private identity); `runtime.health` advertises the `events.streamEpoch` capability, session reads stamp it so clients can reject stale-epoch responses, and a snapshot published because the cursor could not be replayed is additionally stamped `resync: true` as a recovery baseline. A reconnect replays the retained contiguous suffix after its cursor when available, otherwise it receives an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions. The suffix lives in `session-replay.js` and is bounded by both count (1,024 events) and encoded wire bytes (8 MiB): eviction removes whole oldest events first and never truncates content, each event is serialized once and the cached line is reused for live broadcast and replay, and live delivery stays full-fidelity even for events too large to retain. The byte budget counts encoded wire bytes, not heap, and snapshots assign sequence numbers without replay insertion so numeric gaps from private snapshots are intentional. A single oversized event clears the retained suffix without being retained, an empty ring never replays, and a cursor beyond the latest sequence resynchronizes from a snapshot; contiguity is judged on the global suffix while delivery stays session-filtered, so a filtered client never replays through a gap. A missed suffix recovers through `session.snapshot` plus `sessions.open` hydrate, which re-reads persisted entries for tool finals and lifecycle.
58
58
  - Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (`session.prompt` with `preflightResult(disposition)` where `disposition` is `'started'`, `'queued'`, or `'handled'`); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (`session.prompt` promise rejecting without calling `preflightResult`) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from the SDK preflight disposition: `'queued'` keeps the metadata, `'handled'` and registered extension commands never do, and `'started'` keeps it only while the session is still streaming; only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. A registered extension command running without an agent turn (waiting on `custom()`, a dialog, or its own work) keeps the session busy, as Pi's interactive mode holds input until the command returns: the daemon publishes `session.lifecycle: busy` with `command: '/name'` when it dispatches, snapshots, `getSession`, and list live status report the same, and prompt, steer, and follow-up fail as `SESSION_BUSY` until it returns, because the SDK would start a second run beside the command (steering only queues behind a streaming turn). While the command's own agent turn streams, input behaves normally; when that turn settles and the command still runs, the busy frame with `command` is published again instead of idle, and the settled turn neither completes a requested shutdown nor re-arms idle disposal. A command that returns or throws publishes idle from its own settlement, whatever the send generation (a steer into the command's turn moves it on), unless a turn still streams, whose `agent_settled` then publishes idle. `!cmd` (`sessions.bash`) and `sessions.compact` are refused the same way. The busy check runs again after the model and attachment awaits, so two clients cannot both start beside a command. Command detection follows Pi's `_tryExecuteExtensionCommand`: the text (with appended attachment notes) must start with `/`, and the name up to the first space must match a registered `invocationName` exactly. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
59
59
  - Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId` and the health-verified `streamEpoch`, the daemon claims `kind + sessionId + operationId + streamEpoch` BEFORE Pi activation, and an identical same-epoch retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same full key with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). An intent from another daemon lifetime fails as `STALE_STREAM_EPOCH` (HTTP 409) before Pi or attachment-consumption side effects. The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId + streamEpoch` identity; a missing epoch returns `unknown`, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime receipt guarantee, only within the retention window. A restart loses receipts, but the replacement daemon rejects the retired epoch instead of replaying the old intent. Receipt lookup and replay protection remain separate read-only contracts.