@pi-chamber/web 1.0.6-rc.6 → 1.0.6

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 (54) hide show
  1. package/dist/assets/{DiagramView-BxBfOrN5.js → DiagramView-DsCdfDOP.js} +1 -1
  2. package/dist/assets/{DiffView-CSC9GMrb.js → DiffView-BWo7yT-P.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-C_MNWp6w.js → FileSaveConflictDialog-IFbuQCcP.js} +1 -1
  4. package/dist/assets/{FilesView-DeN6KmNt.js → FilesView-DLIQkVep.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-CrtJwlqV.js → GitHubDetailScaffold-CxGg6x7R.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-g6w8K95J.js → GitHubLinkPicker-BmqbTUpE.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-lAi2ywE3.js → GitHubListPrimitives-a1DxU6Zp.js} +1 -1
  8. package/dist/assets/{GitView-D9_em8Vx.js → GitView-DbqM8Qi1.js} +3 -3
  9. package/dist/assets/{IssuesSurface-DCiHe6TE.js → IssuesSurface-B2EfICtZ.js} +1 -1
  10. package/dist/assets/{JsonTreeView-D64mTfTx.js → JsonTreeView-DzVqgwz-.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-DwE90rTA.js → MarkdownRendererImpl-7yTzCIEI.js} +1 -1
  12. package/dist/assets/{PatchDiff-CcIwURzW.js → PatchDiff-Dvfm6eOV.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-tN7awL0-.js → PierreDiffViewer-ByYaUifK.js} +1 -1
  14. package/dist/assets/{PullRequestsSurface-iX4r3QlS.js → PullRequestsSurface-1IP_dDn8.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-DrrM0ObM.js → SessionSwitcherContent-DVxWhG4x.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-B9_0JwY7.js → SessionSwitcherDropdown-DiBGmmtD.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-Bpgp2gLO.js → SessionUnreadDot-qw67HcBO.js} +1 -1
  18. package/dist/assets/SettingsView-CMTIIpWD.js +6 -0
  19. package/dist/assets/{SettingsWindow-Bepcpy0R.js → SettingsWindow-DZUSs5Is.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dl9-vpvL.js → ToolOutputDialog-pgTNzNPN.js} +1 -1
  21. package/dist/assets/{ToolPartDiffPreview-CLlHEPYD.js → ToolPartDiffPreview-Cvnr4JkU.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-D9OpUpR3.js → VirtualizedFileDiff-D8dSHI_H.js} +1 -1
  23. package/dist/assets/{computeVirtualFileMetrics-CDv_UBXL.js → computeVirtualFileMetrics-g1aOl5nF.js} +1 -1
  24. package/dist/assets/{contextFileOpenGuard-BJ2sAhZG.js → contextFileOpenGuard-IWdho_6z.js} +1 -1
  25. package/dist/assets/{fileTreeStatus-B2PDFobt.js → fileTreeStatus-trDHgX4B.js} +1 -1
  26. package/dist/assets/{gitStatusPredicates-BDdOjxH_.js → gitStatusPredicates-CfBh9Rne.js} +1 -1
  27. package/dist/assets/{githubLink-wwC2_C_9.js → githubLink-CuQ2WFBa.js} +1 -1
  28. package/dist/assets/{index-MXKT8Ir9.js → index-CK9t5Znh.js} +1 -1
  29. package/dist/assets/{main-CnW7qm2b.js → main-DOlk_lfi.js} +2 -2
  30. package/dist/assets/{main-DmHVgAh0.js → main-UnRe9F68.js} +4 -4
  31. package/dist/assets/{markdownCore-DOFhfL5i.js → markdownCore-DuZmdypZ.js} +1 -1
  32. package/dist/assets/{miniChat-D_Wl2jlx.js → miniChat-Dy9h0B6G.js} +2 -2
  33. package/dist/assets/{mobile-Cl-KcfGW.js → mobile-CWrtn0Si.js} +2 -2
  34. package/dist/assets/{pi-session-focus-preference-BqEU9Iq6.js → pi-session-focus-preference-q-s-Bhf0.js} +1 -1
  35. package/dist/assets/{renderDiffWithHighlighter-U7WjeGm9.js → renderDiffWithHighlighter-HRnE6vfE.js} +1 -1
  36. package/dist/assets/{renderElectronMiniChatApp-BJxNc9OP.js → renderElectronMiniChatApp-OZ2fG5eY.js} +2 -2
  37. package/dist/assets/{renderFileWithHighlighter-DiwpFgMp.js → renderFileWithHighlighter-tJRUQWjE.js} +1 -1
  38. package/dist/assets/{renderMobileApp-d5KpyvBc.js → renderMobileApp-D1nkBJLP.js} +3 -3
  39. package/dist/assets/runtimeEndpointReset-Bby2E_Je.js +62 -0
  40. package/dist/assets/{useAppFontEffects-FKnY7Fe2.js → useAppFontEffects-BFgKpDYT.js} +40 -40
  41. package/dist/assets/{useGitHubRemoteSearch-4QMXIODG.js → useGitHubRemoteSearch-MxC4J-VO.js} +1 -1
  42. package/dist/assets/{useSwitcherItems-DtCNsq8u.js → useSwitcherItems-D5TsQEbM.js} +1 -1
  43. package/dist/assets/{web-components-D5QImbWv.js → web-components-B_NMC-2c.js} +1 -1
  44. package/dist/index.html +1 -1
  45. package/dist/mini-chat.html +1 -1
  46. package/dist/mobile.html +1 -1
  47. package/package.json +1 -1
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  49. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +60 -1
  50. package/server/lib/pi/session-daemon/session-daemon.js +34 -10
  51. package/server/lib/pi/session-daemon/session-engine-router.js +5 -1
  52. package/server/lib/pi/session-daemon/session-engine-router.test.js +21 -0
  53. package/dist/assets/SettingsView-C4hec1iy.js +0 -6
  54. package/dist/assets/runtimeEndpointReset-Cd4yJDsk.js +0 -62
@@ -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-FKnY7Fe2.js";import{a6 as U,K as Fe,bb as ze,bc as Ie}from"./runtimeEndpointReset-Cd4yJDsk.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-lAi2ywE3.js";import{c as Ye}from"./vendor-zustand-CXhN0IMY.js";import{K as Ue,C as Ve,D as Qe}from"./GitHubDetailScaffold-CrtJwlqV.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-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 +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-FKnY7Fe2.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-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,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-FKnY7Fe2.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-CDv_UBXL.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-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">
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,7 +540,7 @@
540
540
  }
541
541
  }
542
542
  </style>
543
- <script type="module" crossorigin src="/assets/main-CnW7qm2b.js"></script>
543
+ <script type="module" crossorigin src="/assets/main-DOlk_lfi.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">
@@ -89,7 +89,7 @@
89
89
  }
90
90
  </style>
91
91
 
92
- <script type="module" crossorigin src="/assets/miniChat-D_Wl2jlx.js"></script>
92
+ <script type="module" crossorigin src="/assets/miniChat-Dy9h0B6G.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">
package/dist/mobile.html CHANGED
@@ -63,7 +63,7 @@
63
63
  })();
64
64
  </script>
65
65
 
66
- <script type="module" crossorigin src="/assets/mobile-Cl-KcfGW.js"></script>
66
+ <script type="module" crossorigin src="/assets/mobile-CWrtn0Si.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">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "1.0.6-rc.6",
3
+ "version": "1.0.6",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -29,7 +29,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
29
29
  - `pending-input.js` owns the daemon-level pending-input index (`PENDING_INPUT_KINDS`, `MAX_PENDING_INPUT_COUNT`, `normalizePendingInputSummary`, `createPendingInputIndex`). It folds daemon-hosted blocking requests and engine-reported summaries into one derived per-session summary (`{ count, kind, since }`, `null` when authoritatively nothing is pending), publishes the canonical `session.input` event (`{ pending, serverNow }`, with `serverNow` sampled from the injected `now` at publish time) only on actual change, and prefers hosted requests when both sources exist. It is synchronous with no timers; idle re-arm on last-settle is an injected callback.
30
30
  - `user-bash.js` owns user shell commands (`!cmd`, and `!!cmd` with `excludeFromContext`) through `sessions.bash` / `sessions.abortBash`. It allows one running command per session. It calls Pi's `emitUserBash` first: an extension may return `result` (recorded as is) or `operations` (passed to `executeBash`), and a throwing extension fails the command with no local fallback, matching the Pi CLI. Pi's `recordBashResult` defers while the agent is streaming, so a command may finish before it is recorded. The module observes `sessionManager.appendMessage` for `bashExecution` entries and publishes `session.bash.recorded` with the authoritative entry id, so the live row and the transcript row reconcile without heuristics. Live output is coalesced to one `session.bash.output` event per 100 ms window, each capped at 16 KB. A window that overflows publishes a `reset` frame with the 16 KB tail instead of the full burst. The live tail kept for snapshots and session details (`bashExecutions`) is capped at 64 KB, as is recorded output projected into transcripts (`pichamber.bash` extension rows). These caps bound replay-log growth, which retains every published event. Running commands block idle disposal, and nothing runs or is retained for sessions that never use `!cmd`.
31
31
  - `engines/index.js` is the single engine registration point: one exported array of engine factories. It ships empty in main.
32
- - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest `session_info` anywhere in the file). Each daemon owns a per-file metadata cache (`createPiSessionJsonlListCache`) keyed by path and validated by dev/ino + size + mtime: an unchanged file costs one `stat`, a file that grew in place is scanned only from the last complete newline, and a shrunk, replaced, or rewritten file is rescanned. Scans stream in 256KB chunks and only `JSON.parse` lines whose raw bytes contain `"session_info"` (or `"user"` until the first prompt is found). Pi semantics apply: the latest `session_info` wins, and an empty or whitespace name is an explicit clear. Entries for files no longer in the directory are pruned on each list. Files in one directory are listed with at most eight concurrent reads; one unreadable or header-malformed file still fails that directory. Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
32
+ - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest `session_info` anywhere in the file). Each daemon owns a per-file metadata cache (`createPiSessionJsonlListCache`) keyed by path and validated by dev/ino + size + mtime: an unchanged file costs one `stat`, a file that grew in place is scanned only from the last complete newline, and a shrunk, replaced, or rewritten file is rescanned. Scans stream in 256KB chunks and only `JSON.parse` lines whose raw bytes contain `"session_info"` (or `"user"` until the first prompt is found). Pi semantics apply: the latest `session_info` wins, and an empty or whitespace name is an explicit clear. Entries for files no longer in the directory are pruned on each list. Files in one directory are listed with at most eight concurrent reads; one unreadable or header-malformed file still fails that directory. Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. `sessions.list` and `sessions.delete` accept a folder that no longer exists (a removed worktree or temporary folder still has sessions in the store, which auto-archive and the sidebar must reach). Deletion finds such a session after a daemon restart too (`findPersistedSession` with `allowRemovedDirectory`), never records the removed folder as a known project, and engine-owned deletes resolve the same way (`resolveSessionStoreDirectory` in the engine router); the path must still be absolute, and an existing path that is not a folder (a file, or a foreign Windows path such as `C:/Users/...` on Linux, which is not absolute there) is rejected with `INVALID_ARGUMENT`. Opening or creating a session still requires the folder to exist. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
33
33
  - `supervisor.js` resolves server-only overrides, creates the credential, serializes start/reuse/stop through an owner-only lock, validates daemon identity through `runtime.health`, forwards server-owned commands only after that identity check, and starts or stops the detached process. Reuse requires the ready-state sidecar `entrypoint` to match this checkout's `daemon-process.js`; a healthy same-profile daemon with a different entrypoint is claimed and then shut down through authenticated IPC so local `bun run dev` cannot keep answering `getSession` without the live-turn overlay. When the parent is Electron, the child is spawned with `ELECTRON_RUN_AS_NODE=1` so packaged Windows/macOS/Linux apps run the daemon as Node instead of a hidden second Electron GUI process. A daemon spawn failure (synchronous throw or the child's async 'error' event, e.g. when the executable vanished) is captured, never left as an uncaught 'error' event, ends the readiness wait early, and surfaces as code-only `DAEMON_SPAWN_FAILED` without the executable path.
34
34
  - `../server/server-profile.js` derives one stable daemon profile per server: installed web is `web-p<port>`, development web is `web-dev-p<port>`, installed desktop is `desktop`, and development desktop is `desktop-dev`. `PICHAMBER_SERVER_PROFILE` overrides the derivation with a hashed `custom-<hash>` key so raw input never becomes a path, while preserving whether the launcher is a development build for stale-code replacement. The profile key is stable across restarts; the server instance id is a fresh UUID per launch. Development launchers (`scripts/dev-web-hmr.mjs`, `scripts/dev-web-full.mjs`, `cross-env` in the `dev:server` scripts, `PICHAMBER_ELECTRON_DEV`) explicitly mark themselves so stopping development can never terminate the installed daemon.
35
35
  - `../server/cross-process-lock.js` serializes critical sections across servers sharing one data directory (exclusive create, owner nonce, dead-pid steal, bounded wait). It backs the daemon operation lock pattern and every shared read-modify-write store below.
@@ -1,5 +1,5 @@
1
1
  import { afterEach, describe, expect, it } from 'vitest';
2
- import { mkdir, mkdtemp } from 'node:fs/promises';
2
+ import { mkdir, mkdtemp, stat, writeFile } from 'node:fs/promises';
3
3
  import { createConnection } from 'node:net';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
@@ -227,6 +227,65 @@ describe('session daemon list live status', () => {
227
227
  expect(Object.keys(live).sort()).toEqual(['lifecycle', 'retry', 'runStartedAt', 'sequence', 'serverNow']);
228
228
  });
229
229
 
230
+ it("lists a removed folder's sessions from the session store, and rejects a path that is not a folder", async () => {
231
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-list-live-'));
232
+ await mkdir(join(root, 'agent'), { recursive: true });
233
+ const removed = join(root, 'removed-worktree');
234
+ const listedDirectories = [];
235
+ const { daemon, endpoint } = await startDaemon(root, new FakeSession('unused'), async ({ cwd }) => {
236
+ listedDirectories.push(cwd);
237
+ return cwd === removed ? [{ ...diskRow(removed, 'orphan'), cwd: removed }] : [];
238
+ });
239
+ daemons.push(daemon);
240
+ const client = connectClient(endpoint);
241
+ sockets.push(client);
242
+ await client.authenticate();
243
+
244
+ const listed = await client.request('sessions.list', { directory: removed });
245
+ expect(listed.error).toBeUndefined();
246
+ expect(listed.result.sessions.map((item) => item.session.id)).toEqual(['orphan']);
247
+ expect(listedDirectories).toContain(removed);
248
+
249
+ // A failed request closes the connection with an error frame, so each case gets its own client.
250
+ const rejects = async (directory) => {
251
+ const other = connectClient(endpoint);
252
+ sockets.push(other);
253
+ await other.authenticate();
254
+ other.socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId: 'bad', command: 'sessions.list', payload: { directory } })}\n`);
255
+ return (await other.next((message) => message.kind === 'error')).error.code;
256
+ };
257
+ const file = join(root, 'not-a-folder.txt');
258
+ await writeFile(file, 'x');
259
+ expect(await rejects(file)).toBe('INVALID_ARGUMENT');
260
+ expect(await rejects('relative/folder')).toBe('INVALID_ARGUMENT');
261
+ // A Windows client's home is not an absolute path on a POSIX server.
262
+ if (process.platform !== 'win32') expect(await rejects('C:/Users/Someone')).toBe('INVALID_ARGUMENT');
263
+ });
264
+
265
+ it("deletes a removed folder's session from a freshly started daemon", async () => {
266
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-list-live-'));
267
+ await mkdir(join(root, 'agent'), { recursive: true });
268
+ const removed = join(root, 'removed-worktree');
269
+ // The transcript lives in the session store; its folder is gone.
270
+ const sessionFile = join(root, 'orphan.jsonl');
271
+ await writeFile(sessionFile, `${JSON.stringify({ type: 'session', id: 'orphan', cwd: removed })}\n`);
272
+ // A new daemon has never seen the folder, as after a restart.
273
+ const { daemon, endpoint } = await startDaemon(root, new FakeSession('unused'), async ({ cwd }) => (
274
+ cwd === removed ? [{ ...diskRow(root, 'orphan'), cwd: removed }] : []
275
+ ));
276
+ daemons.push(daemon);
277
+ const client = connectClient(endpoint);
278
+ sockets.push(client);
279
+ await client.authenticate();
280
+
281
+ const deleted = await client.request('sessions.delete', { sessionId: 'orphan', directory: removed });
282
+ expect(deleted.error).toBeUndefined();
283
+ await expect(stat(sessionFile)).rejects.toMatchObject({ code: 'ENOENT' });
284
+ // The removed folder does not become a known project.
285
+ const projects = await client.request('projects.list', {});
286
+ expect(JSON.stringify(projects.result)).not.toContain('removed-worktree');
287
+ });
288
+
230
289
  it('an unpersisted resident session is listed with its live status too', async () => {
231
290
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-list-live-'));
232
291
  await mkdir(join(root, 'agent'), { recursive: true });
@@ -544,6 +544,26 @@ export function createSessionDaemon({
544
544
  return activeDirectory || cwd;
545
545
  };
546
546
 
547
+ // Listing or deleting a folder's sessions reads Pi's session store, not the
548
+ // folder, so a folder that has since been removed still resolves: its
549
+ // sessions stay listable, archivable, and deletable. A path that exists must
550
+ // still be a directory, and opening or creating a session keeps the strict
551
+ // check in `resolveDirectory`.
552
+ const resolveSessionStoreDirectory = async (requested) => {
553
+ if (typeof requested !== 'string' || requested.trim().length === 0) return activeDirectory || cwd;
554
+ const trimmed = requested.trim();
555
+ const normalized = trimmed === '~' ? homedir() : trimmed;
556
+ if (!isAbsolute(normalized)) {
557
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The directory path must be absolute.');
558
+ }
559
+ try {
560
+ await stat(normalized);
561
+ } catch (error) {
562
+ if (error?.code === 'ENOENT') return normalized;
563
+ }
564
+ return resolveDirectory(normalized);
565
+ };
566
+
547
567
  const deriveSessionTitle = (text, maxLength = 50) => {
548
568
  if (!text || typeof text !== 'string') return '';
549
569
  const cleaned = text
@@ -1499,7 +1519,7 @@ export function createSessionDaemon({
1499
1519
  };
1500
1520
 
1501
1521
  const listSessionItems = async (requestedDirectory) => {
1502
- const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1522
+ const targetDir = await resolveSessionStoreDirectory(requestedDirectory);
1503
1523
  const inflight = listInflightByDirectory.get(targetDir);
1504
1524
  if (inflight) return inflight;
1505
1525
  const pending = listSessionItemsUnshared(targetDir).finally(() => {
@@ -1541,15 +1561,18 @@ export function createSessionDaemon({
1541
1561
  publish('session.updated', { title: redactAttachmentPaths(title) }, sessionId, targetDir);
1542
1562
  };
1543
1563
 
1544
- const findPersistedSession = async (sessionId, requestedDirectory) => {
1564
+ // Deletion passes `allowRemovedDirectory`: a session whose folder has since
1565
+ // been removed is still found in the store. Opening keeps the strict check.
1566
+ const findPersistedSession = async (sessionId, requestedDirectory, { allowRemovedDirectory = false } = {}) => {
1545
1567
  if (typeof sessionId !== 'string' || sessionId.length === 0) {
1546
1568
  throw new SessionDaemonProtocolError('INVALID_SESSION', 'The Pi session does not exist.');
1547
1569
  }
1570
+ const resolve = allowRemovedDirectory ? resolveSessionStoreDirectory : resolveDirectory;
1548
1571
  const candidateDirs = new Set();
1549
1572
  let requestedTargetDirectory;
1550
1573
  if (requestedDirectory) {
1551
1574
  try {
1552
- requestedTargetDirectory = await resolveDirectory(requestedDirectory);
1575
+ requestedTargetDirectory = await resolve(requestedDirectory);
1553
1576
  candidateDirs.add(requestedTargetDirectory);
1554
1577
  } catch {}
1555
1578
  }
@@ -1587,8 +1610,9 @@ export function createSessionDaemon({
1587
1610
  const named = await findPiSessionJsonlById({ sessionId, agentDir });
1588
1611
  if (named?.path && named.cwd) {
1589
1612
  await validatePiSessionJsonlFile(named.path);
1590
- const directory = await resolveDirectory(named.cwd);
1591
- knownDirectories.add(directory);
1613
+ // `resolveDirectory` records an existing folder as known; a removed
1614
+ // one is never added.
1615
+ const directory = await resolve(named.cwd);
1592
1616
  return { target: { id: sessionId, path: named.path }, directory };
1593
1617
  }
1594
1618
  } catch {
@@ -1629,8 +1653,7 @@ export function createSessionDaemon({
1629
1653
  lines.close();
1630
1654
  if (fileId === sessionId && sessionCwd) {
1631
1655
  await validatePiSessionJsonlFile(fullPath);
1632
- const validated = await resolveDirectory(sessionCwd);
1633
- knownDirectories.add(validated);
1656
+ const validated = await resolve(sessionCwd);
1634
1657
  return { target: { id: sessionId, path: fullPath }, directory: validated };
1635
1658
  }
1636
1659
  } catch {}
@@ -3793,7 +3816,7 @@ export function createSessionDaemon({
3793
3816
  throw new SessionDaemonProtocolError('RUNTIME_DISPOSAL_FAILED', 'The Pi session runtime could not be disposed.');
3794
3817
  }
3795
3818
  const active = runtimeRegistry?.findBySessionId(sessionId);
3796
- let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
3819
+ let targetDir = requestedDirectory ? await resolveSessionStoreDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
3797
3820
  const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
3798
3821
  if (active) {
3799
3822
  if (active.session?.isStreaming) await active.session.abort();
@@ -3804,7 +3827,7 @@ export function createSessionDaemon({
3804
3827
  if (active && typeof activeSessionFile === 'string' && activeSessionFile.length > 0) {
3805
3828
  await rm(activeSessionFile, { force: true });
3806
3829
  } else if (!active) {
3807
- const { target, directory } = await findPersistedSession(sessionId, targetDir);
3830
+ const { target, directory } = await findPersistedSession(sessionId, targetDir, { allowRemovedDirectory: true });
3808
3831
  targetDir = directory;
3809
3832
  await acquireResidentLease({ cwd: targetDir, sessionId });
3810
3833
  try {
@@ -4281,6 +4304,7 @@ export function createSessionDaemon({
4281
4304
  const engineRouter = createSessionEngineRouter({
4282
4305
  getRegistry: () => engineRegistry,
4283
4306
  resolveDirectory,
4307
+ resolveSessionStoreDirectory,
4284
4308
  sessionInput,
4285
4309
  redact: (value) => redactAttachmentValues(value),
4286
4310
  createError: (code, message) => new SessionDaemonProtocolError(code, message),
@@ -4677,7 +4701,7 @@ export function createSessionDaemon({
4677
4701
  return;
4678
4702
  }
4679
4703
  const listDir = message.payload?.directory || message.payload?.cwd;
4680
- const listTargetDir = listDir ? await resolveDirectory(listDir) : (activeDirectory || cwd);
4704
+ const listTargetDir = await resolveSessionStoreDirectory(listDir);
4681
4705
  const merged = await engineRouter.mergeSessionList(sessions, listTargetDir);
4682
4706
  writeFrame(socket, {
4683
4707
  protocolVersion: PROTOCOL_VERSION,