@av-pi-studio/web-client 0.0.59 → 0.0.60

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 (79) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/web/assets/BinaryFallbackViewer-ClYyn4IS.css +1 -0
  3. package/dist/web/assets/{BinaryFallbackViewer-BPcn4yCY.js → BinaryFallbackViewer-yIyZW16D.js} +2 -2
  4. package/dist/web/assets/{BinaryFallbackViewer-BPcn4yCY.js.map → BinaryFallbackViewer-yIyZW16D.js.map} +1 -1
  5. package/dist/web/assets/ChatPanel-DDk43VVt.js +3 -0
  6. package/dist/web/assets/ChatPanel-DDk43VVt.js.map +1 -0
  7. package/dist/web/assets/ChatPanel-qE6vr3IJ.css +1 -0
  8. package/dist/web/assets/{CodeView-DNKpvKfm.js → CodeView-QYCEkfyO.js} +2 -2
  9. package/dist/web/assets/{CodeView-DNKpvKfm.js.map → CodeView-QYCEkfyO.js.map} +1 -1
  10. package/dist/web/assets/DiffView-CUctPSBA.css +1 -0
  11. package/dist/web/assets/DiffView-CrQA2QN6.js +3 -0
  12. package/dist/web/assets/{DiffView-E-36gscH.js.map → DiffView-CrQA2QN6.js.map} +1 -1
  13. package/dist/web/assets/FilePanel-DnHbd9i_.js +2 -0
  14. package/dist/web/assets/{FilePanel-1jMXusYi.js.map → FilePanel-DnHbd9i_.js.map} +1 -1
  15. package/dist/web/assets/FilePanel-bWuYWz8t.css +1 -0
  16. package/dist/web/assets/ImageViewer-Bh1rkSDM.css +1 -0
  17. package/dist/web/assets/ImageViewer-C4xbKf7H.js +2 -0
  18. package/dist/web/assets/ImageViewer-C4xbKf7H.js.map +1 -0
  19. package/dist/web/assets/MarkdownFileViewer-BOOIyc8-.css +1 -0
  20. package/dist/web/assets/MarkdownFileViewer-dvpIuide.js +2 -0
  21. package/dist/web/assets/MarkdownFileViewer-dvpIuide.js.map +1 -0
  22. package/dist/web/assets/MoleculeViewerPanel-BNHZ9nNu.js +2 -0
  23. package/dist/web/assets/MoleculeViewerPanel-BNHZ9nNu.js.map +1 -0
  24. package/dist/web/assets/MoleculeViewerPanel-CHZ8q0jD.css +1 -0
  25. package/dist/web/assets/{StatusBadge-CJBuPnrc.js → StatusBadge-DFSeaZ3p.js} +2 -2
  26. package/dist/web/assets/{StatusBadge-CJBuPnrc.js.map → StatusBadge-DFSeaZ3p.js.map} +1 -1
  27. package/dist/web/assets/StatusBadge-DmrnYEhp.css +1 -0
  28. package/dist/web/assets/TerminalPanel-C1yf8u8e.css +1 -0
  29. package/dist/web/assets/{TerminalPanel-BQZ0KqJv.js → TerminalPanel-Db3aR8Ro.js} +2 -2
  30. package/dist/web/assets/{TerminalPanel-BQZ0KqJv.js.map → TerminalPanel-Db3aR8Ro.js.map} +1 -1
  31. package/dist/web/assets/TextViewer-C7Qx8B8k.js +2 -0
  32. package/dist/web/assets/TextViewer-C7Qx8B8k.js.map +1 -0
  33. package/dist/web/assets/TextViewer-C7Vnqw_v.css +1 -0
  34. package/dist/web/assets/VideoViewer-BM1PeKnI.js +2 -0
  35. package/dist/web/assets/VideoViewer-BM1PeKnI.js.map +1 -0
  36. package/dist/web/assets/VideoViewer-CCmuaDLl.css +1 -0
  37. package/dist/web/assets/index-CJ1RqoGo.css +1 -0
  38. package/dist/web/assets/index-CP2RuEUB.js +3 -0
  39. package/dist/web/assets/index-CP2RuEUB.js.map +1 -0
  40. package/dist/web/assets/{markdown-9_X86EBj.js → markdown-BCnETsl_.js} +2 -2
  41. package/dist/web/assets/{markdown-9_X86EBj.js.map → markdown-BCnETsl_.js.map} +1 -1
  42. package/dist/web/assets/markdown-DZO6X1Zb.css +1 -0
  43. package/dist/web/assets/{use-file-download-BTSuk1Eh.js → use-file-download-fsjornMU.js} +2 -2
  44. package/dist/web/assets/{use-file-download-BTSuk1Eh.js.map → use-file-download-fsjornMU.js.map} +1 -1
  45. package/dist/web/assets/{use-file-watch-DZfGlL1N.js → use-file-watch-hwGslaA9.js} +2 -2
  46. package/dist/web/assets/{use-file-watch-DZfGlL1N.js.map → use-file-watch-hwGslaA9.js.map} +1 -1
  47. package/dist/web/index.html +2 -2
  48. package/package.json +3 -3
  49. package/dist/web/assets/BinaryFallbackViewer-BnBkar4_.css +0 -1
  50. package/dist/web/assets/ChatPanel-8Tj813-O.js +0 -3
  51. package/dist/web/assets/ChatPanel-8Tj813-O.js.map +0 -1
  52. package/dist/web/assets/ChatPanel-DBXDoy3Z.css +0 -1
  53. package/dist/web/assets/DiffView-E-36gscH.js +0 -3
  54. package/dist/web/assets/DiffView-txOCMsXo.css +0 -1
  55. package/dist/web/assets/FilePanel-1jMXusYi.js +0 -2
  56. package/dist/web/assets/FilePanel-CympQkwn.css +0 -1
  57. package/dist/web/assets/FilePanel.module-CqISrbT-.js +0 -2
  58. package/dist/web/assets/FilePanel.module-CqISrbT-.js.map +0 -1
  59. package/dist/web/assets/ImageViewer-Cimj0SFJ.js +0 -2
  60. package/dist/web/assets/ImageViewer-Cimj0SFJ.js.map +0 -1
  61. package/dist/web/assets/ImageViewer-ijzMsq8H.css +0 -1
  62. package/dist/web/assets/MarkdownFileViewer-BChv2tKK.js +0 -2
  63. package/dist/web/assets/MarkdownFileViewer-BChv2tKK.js.map +0 -1
  64. package/dist/web/assets/MarkdownFileViewer-BD5Ri_Fb.css +0 -1
  65. package/dist/web/assets/MoleculeViewerPanel-B-0MaJMt.css +0 -1
  66. package/dist/web/assets/MoleculeViewerPanel-CtODGGih.js +0 -2
  67. package/dist/web/assets/MoleculeViewerPanel-CtODGGih.js.map +0 -1
  68. package/dist/web/assets/StatusBadge-4JuIxBe-.css +0 -1
  69. package/dist/web/assets/TerminalPanel-CfG2gRmZ.css +0 -1
  70. package/dist/web/assets/TextViewer-3yEorz3A.js +0 -2
  71. package/dist/web/assets/TextViewer-3yEorz3A.js.map +0 -1
  72. package/dist/web/assets/TextViewer-Bcv3IFDK.css +0 -1
  73. package/dist/web/assets/VideoViewer-BBuZ4wou.css +0 -1
  74. package/dist/web/assets/VideoViewer-CbBaI4CK.js +0 -2
  75. package/dist/web/assets/VideoViewer-CbBaI4CK.js.map +0 -1
  76. package/dist/web/assets/index-CEP1cIKf.js +0 -3
  77. package/dist/web/assets/index-CEP1cIKf.js.map +0 -1
  78. package/dist/web/assets/index-DCtlhAPI.css +0 -1
  79. package/dist/web/assets/markdown-DEdmq7db.css +0 -1
@@ -1,2 +0,0 @@
1
- import{r as f,j as s}from"./vendor-react-CWo7Do4s.js";import{C as j}from"./vendor-04vXFIXe.js";import{a as g,r as l,c as w,d as E,B as h,V as D,S as x}from"./index-CEP1cIKf.js";import{u as N,c as S}from"./vendor-query-BGIh-vlp.js";import{u as K}from"./use-file-watch-DZfGlL1N.js";import{D as k}from"./DiffView-E-36gscH.js";import{p as n}from"./FilePanel.module-CqISrbT-.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";function q(e,o,t,i=!0){const r=g(a=>a.client);return N({queryKey:l.fileDiff(e,o,t),queryFn:async()=>{if(!r)throw new Error("not connected");return{patch:(await r.connection.request("file_diff_request",{path:e,cwd:o,staged:t})).patch??""}},enabled:!!r&&!!e&&!!o&&i})}const B=new Set(["text","markdown","image"]);function C(e,o,t){const i=S(),r=B.has(t)?w(e,o):null,{changedAt:a}=K(r);f.useEffect(()=>{a!==null&&(i.invalidateQueries({queryKey:l.fileRead(e)}),i.invalidateQueries({queryKey:l.fileDownload(e)}),i.invalidateQueries({queryKey:l.fileDiffByPath(e)}))},[a,e,i])}function y(e){return"path"in e}function F(e){return"staged"in e}function H({tab:e}){var p;const o=e.kind==="diff",t=e.data,i=y(t)?t.path:"",r=y(t)&&F(t)?t.staged:!1,[a,d]=f.useState(o?"diff":"file"),u=e.workspaceCwd||"~",m=E(i);C(i,u,m);const c=q(i,u,r,a==="diff"),v=D[m];return s.jsxs("div",{className:n.panel,children:[s.jsxs("div",{className:n.header,children:[s.jsx("span",{className:n.path,children:i}),s.jsx("span",{className:n.size,children:a==="diff"?r?"staged":"unstaged":null}),s.jsxs("div",{className:n.viewToggle,children:[s.jsx(h,{size:"xs",variant:a==="file"?"default":"ghost",onClick:()=>d("file"),children:"File"}),s.jsx(h,{size:"xs",variant:a==="diff"?"default":"ghost",onClick:()=>d("diff"),children:"Diff"})]})]}),s.jsx("div",{className:j(n.body,"file-body"),children:a==="file"?s.jsx(f.Suspense,{fallback:s.jsxs("div",{className:n.emptyState,children:[s.jsx(x,{size:"sm"})," Loading..."]}),children:s.jsx(v,{path:i})}):c.isLoading?s.jsxs("div",{className:n.emptyState,children:[s.jsx(x,{size:"sm"})," Loading diff..."]}):c.isError?s.jsxs("div",{className:n.emptyState,children:["Error: ",c.error instanceof Error?c.error.message:"unknown error"]}):(p=c.data)!=null&&p.patch?s.jsx(k,{patch:c.data.patch}):s.jsx("div",{className:n.diffEmpty,children:"No changes (file matches HEAD)"})})]})}export{H as FilePanel};
2
- //# sourceMappingURL=FilePanel-1jMXusYi.js.map
@@ -1 +0,0 @@
1
- ._panel_hkv3d_1{display:flex;flex-direction:column;height:100%;min-height:0}._header_hkv3d_7{display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--pi-color-surface, #16181a);border-bottom:1px solid var(--pi-color-border, #353b46);font-size:var(--pi-font-size-xs);flex-shrink:0}._path_hkv3d_17{color:var(--pi-color-accentBright, #a2b4d7);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._size_hkv3d_24{color:var(--pi-color-foregroundMuted, #9aa0a6);font-size:var(--pi-font-size-2xs);flex-shrink:0}._viewToggle_hkv3d_29{display:flex;gap:2px;flex-shrink:0}._body_hkv3d_34{flex:1;overflow:auto;min-height:0}._emptyState_hkv3d_39{display:flex;align-items:center;justify-content:center;gap:8px;color:var(--pi-color-foregroundMuted, #9aa0a6);font-size:var(--pi-font-size-xs);padding:20px}._diffEmpty_hkv3d_48{padding:30px;text-align:center;color:var(--pi-color-foregroundMuted, #9aa0a6);font-size:var(--pi-font-size-xs)}
@@ -1,2 +0,0 @@
1
- const e="_panel_hkv3d_1",t="_header_hkv3d_7",_="_path_hkv3d_17",d="_size_hkv3d_24",o="_viewToggle_hkv3d_29",p="_body_hkv3d_34",a="_emptyState_hkv3d_39",h="_diffEmpty_hkv3d_48",s={panel:e,header:t,path:_,size:d,viewToggle:o,body:p,emptyState:a,diffEmpty:h};export{s as p};
2
- //# sourceMappingURL=FilePanel.module-CqISrbT-.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"FilePanel.module-CqISrbT-.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
- import{j as e}from"./vendor-react-CWo7Do4s.js";import{S as a}from"./index-CEP1cIKf.js";import{u as t}from"./use-file-download-BTSuk1Eh.js";import{p as s}from"./FilePanel.module-CqISrbT-.js";import"./vendor-query-BGIh-vlp.js";import"./vendor-04vXFIXe.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";const m="_wrap_1al28_1",n="_image_1al28_14",o={wrap:m,image:n};function y({path:i}){const r=t(i);return r.isLoading?e.jsxs("div",{className:s.emptyState,children:[e.jsx(a,{size:"sm"})," Loading image..."]}):r.isError?e.jsxs("div",{className:s.emptyState,children:["Error: ",r.error instanceof Error?r.error.message:"unknown error"]}):r.data?e.jsx("div",{className:o.wrap,children:e.jsx("img",{className:o.image,src:r.data.objectUrl,alt:i.split("/").pop()||i})}):null}export{y as ImageViewer};
2
- //# sourceMappingURL=ImageViewer-Cimj0SFJ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ImageViewer-Cimj0SFJ.js","sources":["../../../src/features/files/ImageViewer.tsx"],"sourcesContent":["/**\n * ImageViewer — renders a binary image file by downloading it over the file-transfer binary\n * frames (`useFileDownload`) and displaying the resulting object URL (POC_TO_APP_PLAN_UI.md §4.5\n * follow-up: modular file preview). A checkerboard background shows through transparent PNGs.\n */\n\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport panelStyles from \"./FilePanel.module.css\";\nimport styles from \"./ImageViewer.module.css\";\n\nexport function ImageViewer({ path }: ViewerProps) {\n const query = useFileDownload(path);\n\n if (query.isLoading) {\n return (\n <div className={panelStyles.emptyState}>\n <Spinner size=\"sm\" /> Loading image...\n </div>\n );\n }\n if (query.isError) {\n return (\n <div className={panelStyles.emptyState}>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </div>\n );\n }\n if (!query.data) return null;\n\n return (\n <div className={styles.wrap}>\n <img className={styles.image} src={query.data.objectUrl} alt={path.split(\"/\").pop() || path} />\n </div>\n );\n}\n"],"names":["ImageViewer","path","query","useFileDownload","jsxs","panelStyles","jsx","Spinner","styles"],"mappings":"ofAYO,SAASA,EAAY,CAAE,KAAAC,GAAqB,CACjD,MAAMC,EAAQC,EAAgBF,CAAI,EAElC,OAAIC,EAAM,UAENE,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAC1B,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,mBAAA,EACvB,EAGAL,EAAM,QAENE,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAAY,SAAA,CAAA,UAC9BH,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,KAGTI,MAAC,OAAI,UAAWE,EAAO,KACrB,SAAAF,MAAC,MAAA,CAAI,UAAWE,EAAO,MAAO,IAAKN,EAAM,KAAK,UAAW,IAAKD,EAAK,MAAM,GAAG,EAAE,IAAA,GAASA,CAAA,CAAM,CAAA,CAC/F,EALsB,IAO1B"}
@@ -1 +0,0 @@
1
- ._wrap_1al28_1{display:flex;align-items:center;justify-content:center;height:100%;min-height:0;overflow:auto;padding:20px;background:repeating-conic-gradient(var(--pi-color-surfaceSunken, #111) 0% 25%,var(--pi-color-surface, #16181a) 0% 50%) 0 0 / 20px 20px}._image_1al28_14{max-width:100%;max-height:100%;object-fit:contain}
@@ -1,2 +0,0 @@
1
- import{r as d,j as r}from"./vendor-react-CWo7Do4s.js";import{S as c,B as a}from"./index-CEP1cIKf.js";import{u as m,C as l}from"./CodeView-DNKpvKfm.js";import{M as p}from"./markdown-9_X86EBj.js";import{p as n}from"./FilePanel.module-CqISrbT-.js";import"./vendor-query-BGIh-vlp.js";import"./vendor-04vXFIXe.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";const x="_wrap_khhx0_1",u="_toolbar_khhx0_6",h="_rendered_khhx0_17",t={wrap:x,toolbar:u,rendered:h};function C({path:o}){const e=m(o),[s,i]=d.useState("preview");return e.isLoading?r.jsxs("div",{className:n.emptyState,children:[r.jsx(c,{size:"sm"})," Loading..."]}):e.isError?r.jsxs("div",{className:n.emptyState,children:["Error: ",e.error instanceof Error?e.error.message:"unknown error"]}):e.data?r.jsxs("div",{className:t.wrap,children:[r.jsxs("div",{className:t.toolbar,children:[r.jsx(a,{size:"xs",variant:s==="preview"?"default":"ghost",onClick:()=>i("preview"),children:"Preview"}),r.jsx(a,{size:"xs",variant:s==="source"?"default":"ghost",onClick:()=>i("source"),children:"Source"})]}),s==="preview"?r.jsx("div",{className:t.rendered,children:r.jsx(p,{text:e.data.content})}):r.jsx(l,{path:o,content:e.data.content})]}):null}export{C as MarkdownFileViewer};
2
- //# sourceMappingURL=MarkdownFileViewer-BChv2tKK.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MarkdownFileViewer-BChv2tKK.js","sources":["../../../src/features/files/MarkdownFileViewer.tsx"],"sourcesContent":["/**\n * MarkdownFileViewer — renders a `.md`/`.mdx` file's content through the app's sanitized\n * Markdown renderer (`timeline/markdown.tsx`, react-markdown + remark-gfm — no\n * `dangerouslySetInnerHTML` of user content), with a Preview/Source toggle since raw markdown is\n * sometimes what you actually want to read (POC_TO_APP_PLAN_UI.md §4.5 follow-up: modular file\n * preview).\n */\n\nimport { useState } from \"react\";\nimport { Button } from \"@pi-studio-ui/components/primitives/Button.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { useFileRead } from \"@pi-studio-ui/hooks/use-file-read.js\";\nimport { Markdown } from \"@pi-studio-ui/timeline/markdown.js\";\nimport { CodeView } from \"./CodeView.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport panelStyles from \"./FilePanel.module.css\";\nimport styles from \"./MarkdownFileViewer.module.css\";\n\ntype Mode = \"preview\" | \"source\";\n\nexport function MarkdownFileViewer({ path }: ViewerProps) {\n const query = useFileRead(path);\n const [mode, setMode] = useState<Mode>(\"preview\");\n\n if (query.isLoading) {\n return (\n <div className={panelStyles.emptyState}>\n <Spinner size=\"sm\" /> Loading...\n </div>\n );\n }\n if (query.isError) {\n return (\n <div className={panelStyles.emptyState}>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </div>\n );\n }\n if (!query.data) return null;\n\n return (\n <div className={styles.wrap}>\n <div className={styles.toolbar}>\n <Button size=\"xs\" variant={mode === \"preview\" ? \"default\" : \"ghost\"} onClick={() => setMode(\"preview\")}>\n Preview\n </Button>\n <Button size=\"xs\" variant={mode === \"source\" ? \"default\" : \"ghost\"} onClick={() => setMode(\"source\")}>\n Source\n </Button>\n </div>\n {mode === \"preview\" ? (\n <div className={styles.rendered}>\n <Markdown text={query.data.content} />\n </div>\n ) : (\n <CodeView path={path} content={query.data.content} />\n )}\n </div>\n );\n}\n"],"names":["MarkdownFileViewer","path","query","useFileRead","mode","setMode","useState","jsxs","panelStyles","jsx","Spinner","styles","Button","Markdown","CodeView"],"mappings":"glBAoBO,SAASA,EAAmB,CAAE,KAAAC,GAAqB,CACxD,MAAMC,EAAQC,EAAYF,CAAI,EACxB,CAACG,EAAMC,CAAO,EAAIC,EAAAA,SAAe,SAAS,EAEhD,OAAIJ,EAAM,UAENK,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAC1B,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,aAAA,EACvB,EAGAR,EAAM,QAENK,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAAY,SAAA,CAAA,UAC9BN,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,KAGTK,EAAAA,KAAC,MAAA,CAAI,UAAWI,EAAO,KACrB,SAAA,CAAAJ,EAAAA,KAAC,MAAA,CAAI,UAAWI,EAAO,QACrB,SAAA,CAAAF,EAAAA,IAACG,EAAA,CAAO,KAAK,KAAK,QAASR,IAAS,UAAY,UAAY,QAAS,QAAS,IAAMC,EAAQ,SAAS,EAAG,SAAA,UAExG,EACAI,EAAAA,IAACG,EAAA,CAAO,KAAK,KAAK,QAASR,IAAS,SAAW,UAAY,QAAS,QAAS,IAAMC,EAAQ,QAAQ,EAAG,SAAA,QAAA,CAEtG,CAAA,EACF,EACCD,IAAS,UACRK,MAAC,MAAA,CAAI,UAAWE,EAAO,SACrB,eAACE,EAAA,CAAS,KAAMX,EAAM,KAAK,OAAA,CAAS,EACtC,EAEAO,EAAAA,IAACK,GAAS,KAAAb,EAAY,QAASC,EAAM,KAAK,OAAA,CAAS,CAAA,EAEvD,EAnBsB,IAqB1B"}
@@ -1 +0,0 @@
1
- ._wrap_khhx0_1{height:100%;min-height:0;overflow:auto}._toolbar_khhx0_6{position:sticky;top:0;z-index:1;display:flex;justify-content:flex-end;gap:2px;padding:6px 10px;background:var(--pi-color-surface, #16181a);border-bottom:1px solid var(--pi-color-border, #353b46)}._rendered_khhx0_17{padding:16px 20px;max-width:860px}
@@ -1 +0,0 @@
1
- ._wrap_9zlgh_1{display:flex;flex-direction:column;height:100%;min-height:0;position:relative}._molViewer_9zlgh_8{flex:1;min-height:0}._emptyState_9zlgh_12{display:flex;align-items:center;justify-content:center;gap:8px;color:var(--pi-color-foregroundMuted, #9aa0a6);font-size:var(--pi-font-size-xs);padding:20px}._badges_9zlgh_21{position:absolute;top:8px;right:8px;z-index:1;display:flex;flex-direction:column;align-items:flex-end;gap:4px}._panel_15zlw_1{display:flex;flex-direction:column;height:100%;min-height:0}
@@ -1,2 +0,0 @@
1
- import{r as l,j as o}from"./vendor-react-CWo7Do4s.js";import{a as R,S as N,h as M}from"./index-CEP1cIKf.js";import{v as T}from"./vendor-molviewer-CARaM-YQ.js";import{S}from"./StatusBadge-CJBuPnrc.js";import{u as A}from"./use-file-download-BTSuk1Eh.js";import{u as F}from"./use-file-watch-DZfGlL1N.js";import"./vendor-query-BGIh-vlp.js";import"./vendor-04vXFIXe.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";function V(e,t){return!e||!t?null:{url:t,name:e.split("/").pop()||e}}function z({changedAt:e,lastAppliedAt:t,modified:a}){return!(e===null||a||e===t)}const L={empty_path:"Nothing to save.",too_large:"File is too large to save (over 5 MiB).",not_found:"The file no longer exists.",unreadable:"The file could not be read.",not_a_file:"That path is not a file."};async function H(e,t,a){const n=await e.connection.request("file_write_request",{path:t,content:a});if(!n.ok){const r=n.error??"";throw new Error(L[r]??r??"Failed to save")}}const I={"--canvas":"var(--pi-color-surface0)","--well":"var(--pi-color-surface0)","--recess":"var(--pi-color-surface1)","--chrome":"var(--pi-color-surface1)","--control":"var(--pi-color-surface2)","--control-hover":"var(--pi-color-surfaceHover)","--control-strong-hover":"var(--pi-color-surfaceHover)","--border-control":"var(--pi-color-border)","--border-input":"var(--pi-color-border)","--popover":"var(--pi-color-surface1)","--popover-item-hover":"var(--pi-color-surfaceHover)","--row-hover":"var(--pi-color-surfaceHover)","--border-popover":"var(--pi-color-border)","--text-primary":"var(--pi-color-foreground)","--text-on-control":"var(--pi-color-foreground)"},B="_wrap_9zlgh_1",k="_molViewer_9zlgh_8",q="_emptyState_9zlgh_12",O="_badges_9zlgh_21",c={wrap:B,molViewer:k,emptyState:q,badges:O};function P({path:e,isActive:t,onModifiedChange:a}){var _;const n=R(s=>s.client),r=A(e??"",!!e),{changedAt:i}=F(e),x=l.useRef(null),v=l.useRef(!1),[u,m]=l.useState(null),[d,E]=l.useState(!1),[h,p]=l.useState(null),f=l.useRef(null),b=V(e,(_=r.data)==null?void 0:_.objectUrl);l.useEffect(()=>{z({changedAt:i,lastAppliedAt:f.current,modified:d})&&(f.current=i,r.refetch())},[i,d,r.refetch]);const j=i!==null&&i!==f.current&&d;async function y(s){if(e){if(!n){p("Not connected — cannot save.");return}p(null);try{await H(n,e,s.text()),s.saved()}catch(g){p(g instanceof Error?g.message:"Failed to save")}}}const w=(r.isError?r.error instanceof Error?r.error.message:"download failed":null)??(u==null?void 0:u.message)??null;return e&&r.isPending?o.jsx("div",{className:c.wrap,children:o.jsxs("div",{className:c.emptyState,children:[o.jsx(N,{size:"sm"})," Loading..."]})}):w?o.jsx("div",{className:c.wrap,children:o.jsxs("div",{className:c.emptyState,children:["Error: ",w]})}):o.jsxs("div",{className:c.wrap,"data-molecule-active":t?"true":"false",children:[o.jsxs("div",{className:c.badges,children:[j&&o.jsx(S,{label:"File changed on disk",variant:"muted"}),h&&o.jsx(S,{label:`Save failed: ${h}`,variant:"error"})]}),o.jsx(T,{ref:x,className:c.molViewer,theme:I,source:b,sourceMode:v.current?"update":"replace",onLoad:()=>{v.current=!0,m(null)},onLoadError:s=>m(s.error),onModifiedChange:s=>{E(s),a==null||a(s)},onSave:e?y:void 0})]})}const W="_panel_15zlw_1",$={panel:W};function se({tab:e}){const{path:t}=e.data,n=M(r=>r.activeTabId)===e.id;return o.jsx("div",{className:$.panel,children:o.jsx(P,{path:t,isActive:n})})}export{se as MoleculeViewerPanel};
2
- //# sourceMappingURL=MoleculeViewerPanel-CtODGGih.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MoleculeViewerPanel-CtODGGih.js","sources":["../../../src/features/files/molecule-source.ts","../../../src/features/files/molecule-reload.ts","../../../src/features/files/write-file.ts","../../../src/features/files/molecule-theme.ts","../../../src/features/files/MoleculeViewer.tsx","../../../src/features/files/MoleculeViewerPanel.tsx"],"sourcesContent":["/**\n * Pure derivation of molviewer's `{ url, name }` source shape, kept in its own module (no\n * `@molviewer/core` import) so it is unit-testable without pulling in the WebGL viewer bundle —\n * merely importing `@molviewer/core` touches `document` at module scope, which jsdom-less/node\n * test environments don't have.\n */\nimport type { MolViewerSource } from \"@molviewer/core\";\n\n/** `name` is load-bearing: molviewer resolves the file format from its extension. */\nexport function moleculeSource(\n path: string | null,\n objectUrl: string | null | undefined,\n): MolViewerSource | null {\n if (!path || !objectUrl) return null;\n return { url: objectUrl, name: path.split(\"/\").pop() || path };\n}\n","/**\n * Pure reload-gating decision for the molecule viewer's live reload (task-006/007). Kept in its\n * own module — like `molecule-source.ts` — so it is unit-testable without importing\n * `@molviewer/core` (which touches `document` at module scope).\n *\n * The gate is intentionally just \"are there unsaved in-viewer edits right now\" — no timestamp or\n * echo-suppression window. A future in-viewer \"Save\" cannot self-trigger a clobber: a save can\n * only happen while `modified` is `true`, and the earliest it flips back to `false` is after the\n * write completes — at which point a reload triggered by that same write is a content no-op.\n */\nexport interface ShouldApplyRefreshArgs {\n /** Timestamp of the last `file_changed` push for this path, or `null` if none yet. */\n changedAt: number | null;\n /** Timestamp of the last push this component actually reloaded for, or `null`. */\n lastAppliedAt: number | null;\n /** Whether the viewer currently has unsaved in-viewer edits. */\n modified: boolean;\n}\n\nexport function shouldApplyRefresh({\n changedAt,\n lastAppliedAt,\n modified,\n}: ShouldApplyRefreshArgs): boolean {\n if (changedAt === null) return false; // No change pushed yet.\n if (modified) return false; // Unsaved edits — leave the user's work alone.\n if (changedAt === lastAppliedAt) return false; // Already applied this push — no reload loop.\n return true;\n}\n","/**\n * Shared `file_write_request` caller for save flows (currently the molecule viewer's `onSave`,\n * `MoleculeViewer.tsx`) — one place for the wire call and the server error-code → user-facing\n * message mapping, structured the same way as the sibling `move-entry.ts`. Overwrite-only: the\n * daemon 404s `not_found` for a missing target (`FileExplorerService.writeFile`); there is no\n * create-on-write.\n */\n\nimport type { PiStudioClient } from \"@av-pi-studio/client\";\n\nconst ERROR_MESSAGES: Record<string, string> = {\n empty_path: \"Nothing to save.\",\n too_large: \"File is too large to save (over 5 MiB).\",\n not_found: \"The file no longer exists.\",\n unreadable: \"The file could not be read.\",\n not_a_file: \"That path is not a file.\",\n};\n\n/** Overwrite `path`'s content on disk. Throws an Error carrying a user-facing message on\n * failure. */\nexport async function writeFile(\n client: PiStudioClient,\n path: string,\n content: string,\n): Promise<void> {\n const response = await client.connection.request<{ ok: boolean; error?: string }>(\n \"file_write_request\",\n { path, content },\n );\n if (!response.ok) {\n const code = response.error ?? \"\";\n throw new Error(ERROR_MESSAGES[code] ?? code ?? \"Failed to save\");\n }\n}\n","/**\n * MOLVIEWER_THEME — pi-studio's background/foreground override for `<MolViewer>`'s `theme` prop.\n *\n * `theme` is documented as raw CSS custom properties applied inline to the component's root\n * (`docs/molviewer-core-doc.md` § UI composition) — a completely separate knob from\n * `initialView.backgroundColor` (the WebGL scene's clear color) and `colorScheme` (per-atom\n * coloring). Neither of those is touched here; this only changes chrome DOM elements (sidebar,\n * toolbars, panels, buttons, dropdowns), never the rendered molecule itself.\n *\n * Values are `var(--pi-color-*)` references, not resolved hex — a CSS custom property may hold\n * another `var()` reference and it chains through the cascade like any other value, so\n * molviewer's chrome tracks pi-studio's live theme (light/dark, custom accent) automatically,\n * with no React re-render needed when appearance settings change.\n *\n * Scope is deliberately narrow, per product decision: panel backgrounds, primary text, and —\n * where molviewer exposes an equivalent — the surfaces of its own interactive controls (buttons)\n * and popovers (dropdowns/menus), all mapped onto pi-studio's existing surface/hover/border scale\n * (`Button.module.css`, `Select.module.css`, the `.item[data-highlighted]` hover pattern used\n * across every pi-studio dropdown). Molviewer's semantic/interactive colors that pi-studio has no\n * equivalent for — accent, selection, danger/success/warning, its five-step muted text scale,\n * axis colors — are its own design language and are left untouched.\n *\n * Molviewer's shipped defaults, for reference (`@molviewer/core/dist/style.css`'s `:root` block):\n * --canvas #0a0c10 --well #0e1116 --recess #0f1217 --chrome #12151b\n * --control #1e232c --control-hover #262c37 --control-strong-hover #2b323e\n * --popover #171b22 --popover-item-hover #232935 --row-hover #161a21\n * --border-control #333b48 --border-input #2b323e --border-popover #3b4453\n * --text-primary #e6e9ef --text-on-control #dfe5ee\n */\nexport const MOLVIEWER_THEME: Record<string, string> = {\n // Panel backgrounds (sidebar, toolbars, recessed panels).\n \"--canvas\": \"var(--pi-color-surface0)\",\n \"--well\": \"var(--pi-color-surface0)\",\n \"--recess\": \"var(--pi-color-surface1)\",\n \"--chrome\": \"var(--pi-color-surface1)\",\n // Buttons and other controls.\n \"--control\": \"var(--pi-color-surface2)\",\n \"--control-hover\": \"var(--pi-color-surfaceHover)\",\n \"--control-strong-hover\": \"var(--pi-color-surfaceHover)\",\n \"--border-control\": \"var(--pi-color-border)\",\n \"--border-input\": \"var(--pi-color-border)\",\n // Dropdowns / menus.\n \"--popover\": \"var(--pi-color-surface1)\",\n \"--popover-item-hover\": \"var(--pi-color-surfaceHover)\",\n \"--row-hover\": \"var(--pi-color-surfaceHover)\",\n \"--border-popover\": \"var(--pi-color-border)\",\n // Text.\n \"--text-primary\": \"var(--pi-color-foreground)\",\n \"--text-on-control\": \"var(--pi-color-foreground)\",\n};\n","/**\n * MoleculeViewer — mounts `<MolViewer>` for both molecule-tab shapes: a file-backed tab (fetch\n * the file, hand molviewer the bytes) and an empty (\"+\"-menu) tab (no source — molviewer's own\n * drag-drop empty state, `ui.emptyState`'s `FirstRunCard`).\n *\n * Content is fetched through `useFileDownload` (chunked binary transfer, uncapped), not\n * `useFileRead` (`file_read_request`, UTF-8 text, inline-size capped): molviewer wants raw bytes\n * and the object URL that hook already produces is exactly molviewer's `{ url, name }` source\n * shape — no decode step, no new fetch hook.\n *\n * Live reload (task-006/007): `useFileWatch` pushes a new `changedAt` whenever the daemon detects\n * the file changed on disk. `shouldApplyRefresh` (kept in its own pure module, see\n * `molecule-reload.ts`) gates the reaction on there being no unsaved in-viewer edits; when it\n * clears, `download.refetch()` mints a fresh object URL, the `source` prop changes, and\n * `MolViewer` reloads with `sourceMode=\"update\"` — camera/selection survive. When it's gated by\n * unsaved edits, a small stale-file indicator surfaces instead of silently diverging.\n *\n * Save (`onSave`, `@molviewer/core@0.4.0`): only wired when `path` is non-null — a file-backed\n * tab writes the viewer's current serialization straight back to that same absolute path via\n * `file_write_request` (`write-file.ts`); the empty (\"+\"-menu) tab has nowhere to write and gets\n * no Save button at all (passing `onSave` is what draws it). `e.saved()` is called only after the\n * daemon confirms the write, which is what greys the button out and flips the viewer back to\n * clean — a failed write leaves it live so the user can retry. Note `e.fileName` is molviewer's\n * own load-time basename (`moleculeSource`'s `name`, extension only, no directory), not a usable\n * write target — the absolute `path` prop already in scope is what gets written.\n */\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { MolViewer, type MolViewerHandle, type SaveEvent } from \"@molviewer/core\";\nimport \"@molviewer/core/style.css\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { StatusBadge } from \"@pi-studio-ui/components/primitives/StatusBadge.js\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport { useFileWatch } from \"@pi-studio-ui/hooks/use-file-watch.js\";\nimport { moleculeSource } from \"./molecule-source.js\";\nimport { shouldApplyRefresh } from \"./molecule-reload.js\";\nimport { writeFile } from \"./write-file.js\";\nimport { MOLVIEWER_THEME } from \"./molecule-theme.js\";\nimport styles from \"./MoleculeViewer.module.css\";\n\nexport interface MoleculeViewerProps {\n /** Absolute path of the file to render, or null for an empty (\"New molecule view\") tab. */\n path: string | null;\n /** True when this viewer's tab is the visible one. Molstar's own `ResizeObserver` on its canvas\n * container re-fits on becoming visible (verified in the installed bundle), so this is not\n * currently used to drive a manual re-fit — kept as the escape hatch task-010's visual\n * verification may still need. */\n isActive?: boolean;\n /** Mirrors `MolViewerProps.onModifiedChange` upward for a future parent-level consumer (e.g. a\n * tab-strip \"unsaved changes\" mark) — independent of this component's own internal `modified`\n * state below, which drives the live-reload gate. */\n onModifiedChange?: (modified: boolean) => void;\n}\n\nexport function MoleculeViewer({ path, isActive, onModifiedChange }: MoleculeViewerProps) {\n const client = useConnectionStore((s) => s.client);\n const download = useFileDownload(path ?? \"\", Boolean(path));\n const { changedAt } = useFileWatch(path);\n const handleRef = useRef<MolViewerHandle>(null);\n // First load of this tab's file refits the camera (\"replace\"); every reload after that (the\n // same file changing on disk, task-007) preserves camera/selection/undo (\"update\"). A mounted\n // MoleculeViewer corresponds to exactly one tab for its whole lifetime (task-004 mints a new\n // tab id per path), so this never needs to reset for a \"new\" path mid-lifetime.\n const hasLoadedRef = useRef(false);\n const [loadError, setLoadError] = useState<Error | null>(null);\n const [modified, setModified] = useState(false);\n const [saveError, setSaveError] = useState<string | null>(null);\n // Ref, not state: recording \"which push we last acted on\" doesn't need its own render — it's\n // read by the same effect that writes it, and by the stale-indicator check below.\n const lastAppliedAtRef = useRef<number | null>(null);\n\n const source = moleculeSource(path, download.data?.objectUrl);\n\n useEffect(() => {\n if (!shouldApplyRefresh({ changedAt, lastAppliedAt: lastAppliedAtRef.current, modified })) {\n return;\n }\n lastAppliedAtRef.current = changedAt;\n void download.refetch();\n // Only `download.refetch` itself needs to be stable across renders for this effect to behave\n // correctly; depending on the whole `download` query object would re-run on every unrelated\n // status change it produces.\n }, [changedAt, modified, download.refetch]);\n\n // A push arrived but couldn't be applied because of unsaved edits — surface that rather than\n // silently diverging. Reading the ref during render is safe here: it only ever changes inside\n // the effect above, which always runs before the next paint that could observe a stale value.\n const hasUnappliedChange =\n changedAt !== null && changedAt !== lastAppliedAtRef.current && modified;\n\n async function handleSave(e: SaveEvent) {\n if (!path) return;\n if (!client) {\n setSaveError(\"Not connected — cannot save.\");\n return;\n }\n setSaveError(null);\n try {\n await writeFile(client, path, e.text());\n e.saved();\n } catch (err) {\n setSaveError(err instanceof Error ? err.message : \"Failed to save\");\n }\n }\n\n const downloadErrorMessage = download.isError\n ? download.error instanceof Error\n ? download.error.message\n : \"download failed\"\n : null;\n const errorMessage = downloadErrorMessage ?? loadError?.message ?? null;\n\n if (path && download.isPending) {\n return (\n <div className={styles.wrap}>\n <div className={styles.emptyState}>\n <Spinner size=\"sm\" /> Loading...\n </div>\n </div>\n );\n }\n if (errorMessage) {\n return (\n <div className={styles.wrap}>\n <div className={styles.emptyState}>Error: {errorMessage}</div>\n </div>\n );\n }\n\n return (\n <div className={styles.wrap} data-molecule-active={isActive ? \"true\" : \"false\"}>\n <div className={styles.badges}>\n {hasUnappliedChange && <StatusBadge label=\"File changed on disk\" variant=\"muted\" />}\n {saveError && <StatusBadge label={`Save failed: ${saveError}`} variant=\"error\" />}\n </div>\n <MolViewer\n ref={handleRef}\n className={styles.molViewer}\n theme={MOLVIEWER_THEME}\n source={source}\n sourceMode={hasLoadedRef.current ? \"update\" : \"replace\"}\n onLoad={() => {\n hasLoadedRef.current = true;\n setLoadError(null);\n }}\n onLoadError={(e) => setLoadError(e.error)}\n onModifiedChange={(m) => {\n setModified(m);\n onModifiedChange?.(m);\n }}\n onSave={path ? handleSave : undefined}\n />\n </div>\n );\n}\n","/**\n * MoleculeViewerPanel — thin `PanelProps` adapter for a `kind: \"molecule\"` tab. No header, no\n * File/Diff toggle (a molecule tab has neither — diffs come from the git Changes panel\n * independently, `ChangesPanel.tsx`); it owns the panel-filling height chain and hands off to\n * `MoleculeViewer` for everything else.\n */\n\nimport { useTabStore, type MoleculeTabData } from \"@pi-studio-ui/stores/tab-store.js\";\nimport type { PanelProps } from \"@pi-studio-ui/features/workspace/panel-registry.js\";\nimport { MoleculeViewer } from \"./MoleculeViewer.js\";\nimport styles from \"./MoleculeViewerPanel.module.css\";\n\nexport function MoleculeViewerPanel({ tab }: PanelProps) {\n const { path } = tab.data as MoleculeTabData;\n const activeTabId = useTabStore((s) => s.activeTabId);\n const isActive = activeTabId === tab.id;\n\n return (\n <div className={styles.panel}>\n <MoleculeViewer path={path} isActive={isActive} />\n </div>\n );\n}\n"],"names":["moleculeSource","path","objectUrl","shouldApplyRefresh","changedAt","lastAppliedAt","modified","ERROR_MESSAGES","writeFile","client","content","response","code","MOLVIEWER_THEME","MoleculeViewer","isActive","onModifiedChange","useConnectionStore","download","useFileDownload","useFileWatch","handleRef","useRef","hasLoadedRef","loadError","setLoadError","useState","setModified","saveError","setSaveError","lastAppliedAtRef","source","_a","useEffect","hasUnappliedChange","handleSave","e","err","errorMessage","jsx","styles","jsxs","Spinner","StatusBadge","MolViewer","m","MoleculeViewerPanel","tab","useTabStore","s"],"mappings":"oiBASO,SAASA,EACdC,EACAC,EACwB,CACxB,MAAI,CAACD,GAAQ,CAACC,EAAkB,KACzB,CAAE,IAAKA,EAAW,KAAMD,EAAK,MAAM,GAAG,EAAE,IAAA,GAASA,CAAA,CAC1D,CCIO,SAASE,EAAmB,CACjC,UAAAC,EACA,cAAAC,EACA,SAAAC,CACF,EAAoC,CAGlC,MAFI,EAAAF,IAAc,MACdE,GACAF,IAAcC,EAEpB,CClBA,MAAME,EAAyC,CAC7C,WAAY,mBACZ,UAAW,0CACX,UAAW,6BACX,WAAY,8BACZ,WAAY,0BACd,EAIA,eAAsBC,EACpBC,EACAR,EACAS,EACe,CACf,MAAMC,EAAW,MAAMF,EAAO,WAAW,QACvC,qBACA,CAAE,KAAAR,EAAM,QAAAS,CAAA,CAAQ,EAElB,GAAI,CAACC,EAAS,GAAI,CAChB,MAAMC,EAAOD,EAAS,OAAS,GAC/B,MAAM,IAAI,MAAMJ,EAAeK,CAAI,GAAKA,GAAQ,gBAAgB,CAClE,CACF,CCJO,MAAMC,EAA0C,CAErD,WAAY,2BACZ,SAAU,2BACV,WAAY,2BACZ,WAAY,2BAEZ,YAAa,2BACb,kBAAmB,+BACnB,yBAA0B,+BAC1B,mBAAoB,yBACpB,iBAAkB,yBAElB,YAAa,2BACb,uBAAwB,+BACxB,cAAe,+BACf,mBAAoB,yBAEpB,iBAAkB,6BAClB,oBAAqB,4BACvB,sICMO,SAASC,EAAe,CAAE,KAAAb,EAAM,SAAAc,EAAU,iBAAAC,GAAyC,OACxF,MAAMP,EAASQ,EAAoB,GAAM,EAAE,MAAM,EAC3CC,EAAWC,EAAgBlB,GAAQ,GAAI,EAAQA,CAAK,EACpD,CAAE,UAAAG,CAAA,EAAcgB,EAAanB,CAAI,EACjCoB,EAAYC,EAAAA,OAAwB,IAAI,EAKxCC,EAAeD,EAAAA,OAAO,EAAK,EAC3B,CAACE,EAAWC,CAAY,EAAIC,EAAAA,SAAuB,IAAI,EACvD,CAACpB,EAAUqB,CAAW,EAAID,EAAAA,SAAS,EAAK,EACxC,CAACE,EAAWC,CAAY,EAAIH,EAAAA,SAAwB,IAAI,EAGxDI,EAAmBR,EAAAA,OAAsB,IAAI,EAE7CS,EAAS/B,EAAeC,GAAM+B,EAAAd,EAAS,OAAT,YAAAc,EAAe,SAAS,EAE5DC,EAAAA,UAAU,IAAM,CACT9B,EAAmB,CAAE,UAAAC,EAAW,cAAe0B,EAAiB,QAAS,SAAAxB,CAAA,CAAU,IAGxFwB,EAAiB,QAAU1B,EACtBc,EAAS,QAAA,EAIhB,EAAG,CAACd,EAAWE,EAAUY,EAAS,OAAO,CAAC,EAK1C,MAAMgB,EACJ9B,IAAc,MAAQA,IAAc0B,EAAiB,SAAWxB,EAElE,eAAe6B,EAAWC,EAAc,CACtC,GAAKnC,EACL,IAAI,CAACQ,EAAQ,CACXoB,EAAa,8BAA8B,EAC3C,MACF,CACAA,EAAa,IAAI,EACjB,GAAI,CACF,MAAMrB,EAAUC,EAAQR,EAAMmC,EAAE,MAAM,EACtCA,EAAE,MAAA,CACJ,OAASC,EAAK,CACZR,EAAaQ,aAAe,MAAQA,EAAI,QAAU,gBAAgB,CACpE,EACF,CAOA,MAAMC,GALuBpB,EAAS,QAClCA,EAAS,iBAAiB,MACxBA,EAAS,MAAM,QACf,kBACF,QACyCM,GAAA,YAAAA,EAAW,UAAW,KAEnE,OAAIvB,GAAQiB,EAAS,UAEjBqB,EAAAA,IAAC,OAAI,UAAWC,EAAO,KACrB,SAAAC,EAAAA,KAAC,MAAA,CAAI,UAAWD,EAAO,WACrB,SAAA,CAAAD,EAAAA,IAACG,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,aAAA,CAAA,CACvB,CAAA,CACF,EAGAJ,EAEAC,EAAAA,IAAC,OAAI,UAAWC,EAAO,KACrB,SAAAC,EAAAA,KAAC,MAAA,CAAI,UAAWD,EAAO,WAAY,SAAA,CAAA,UAAQF,CAAA,CAAA,CAAa,CAAA,CAC1D,EAKFG,OAAC,OAAI,UAAWD,EAAO,KAAM,uBAAsBzB,EAAW,OAAS,QACrE,SAAA,CAAA0B,EAAAA,KAAC,MAAA,CAAI,UAAWD,EAAO,OACpB,SAAA,CAAAN,GAAsBK,EAAAA,IAACI,EAAA,CAAY,MAAM,uBAAuB,QAAQ,QAAQ,EAChFf,SAAce,EAAA,CAAY,MAAO,gBAAgBf,CAAS,GAAI,QAAQ,OAAA,CAAQ,CAAA,EACjF,EACAW,EAAAA,IAACK,EAAA,CACC,IAAKvB,EACL,UAAWmB,EAAO,UAClB,MAAO3B,EACP,OAAAkB,EACA,WAAYR,EAAa,QAAU,SAAW,UAC9C,OAAQ,IAAM,CACZA,EAAa,QAAU,GACvBE,EAAa,IAAI,CACnB,EACA,YAAcW,GAAMX,EAAaW,EAAE,KAAK,EACxC,iBAAmBS,GAAM,CACvBlB,EAAYkB,CAAC,EACb7B,GAAA,MAAAA,EAAmB6B,EACrB,EACA,OAAQ5C,EAAOkC,EAAa,MAAA,CAAA,CAC9B,EACF,CAEJ,sCC/IO,SAASW,GAAoB,CAAE,IAAAC,GAAmB,CACvD,KAAM,CAAE,KAAA9C,GAAS8C,EAAI,KAEfhC,EADciC,EAAaC,GAAMA,EAAE,WAAW,IACnBF,EAAI,GAErC,OACER,EAAAA,IAAC,OAAI,UAAWC,EAAO,MACrB,SAAAD,EAAAA,IAACzB,EAAA,CAAe,KAAAb,EAAY,SAAAc,CAAA,CAAoB,CAAA,CAClD,CAEJ"}
@@ -1 +0,0 @@
1
- ._badge_1flwd_3{display:inline-flex;align-items:center;justify-content:center;padding:1px 6px;border-radius:9999px;border:1px solid;font-size:var(--pi-font-size-xs);font-family:var(--pi-font-ui, system-ui, sans-serif);font-weight:500;white-space:nowrap;line-height:1.5}
@@ -1 +0,0 @@
1
- ._wrap_1wr9d_1{display:flex;flex-direction:column;flex:1 1 auto;min-height:0;height:100%;width:100%;overflow:hidden;background:var(--pi-terminal-bg, #181b1a)}._terminal_1wr9d_11{flex:1 1 auto;min-height:0;width:100%;overflow:hidden;padding:6px 8px}._status_1wr9d_18{display:flex;align-items:center;justify-content:center;gap:8px;height:100%;color:var(--pi-color-foregroundMuted, #9aa0a6);font-size:var(--pi-font-size-sm)}
@@ -1,2 +0,0 @@
1
- import{r as h,j as r}from"./vendor-react-CWo7Do4s.js";import{r as N,S as u,B as j}from"./index-CEP1cIKf.js";import{u as _,F as b,C as y}from"./CodeView-DNKpvKfm.js";import{u as k}from"./vendor-query-BGIh-vlp.js";import{u as E}from"./use-file-download-BTSuk1Eh.js";import{p as d}from"./FilePanel.module-CqISrbT-.js";import"./vendor-04vXFIXe.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";function z(s){const{enabled:n,download:e,decode:o}=s;return{isLoading:n&&(e.isLoading||e.hasObjectUrl&&o.isLoading),isError:e.isError||o.isError,error:e.isError?e.error:o.error,data:o.data}}function v(s,n=!0){var a;const e=E(s,n),o=(a=e.data)==null?void 0:a.objectUrl,t=k({queryKey:N.fileText(s,o??null),queryFn:async()=>({content:await(await fetch(o)).text()}),enabled:n&&!!o});return z({enabled:n,download:{isLoading:e.isLoading,isError:e.isError,error:e.error,hasObjectUrl:!!o},decode:{isLoading:t.isLoading,isError:t.isError,error:t.error,data:t.data}})}function U(s){const{maxDisplayBytes:n,inline:e,streamed:o,download:t}=s;if(e.isLoading)return{kind:"loading"};if(e.tooLarge){const{size:a}=e.tooLarge;return a>n?{kind:"too-large",size:a,maxDisplayBytes:n,downloading:t.requested&&t.isLoading,downloadUrl:t.objectUrl,downloadName:t.fileName}:o.isLoading?{kind:"streaming",size:a}:o.isError?{kind:"stream-error",size:a,message:o.errorMessage??"stream failed"}:o.content!==null?{kind:"streamed",size:a,content:o.content}:{kind:"loading"}}return e.isError?{kind:"error",message:e.errorMessage??"unknown error"}:e.content!==null?{kind:"inline",content:e.content}:{kind:"loading"}}const B="_wrap_hx688_1",F="_note_hx688_7",D="_body_hx688_15",M="_tooLarge_hx688_19",l={wrap:B,note:F,body:D,tooLarge:M},L=30*1024*1024;function c(s){return`${(s/(1024*1024)).toFixed(1)} MB`}function X({path:s}){var x,f,p,w;const n=_(s),e=n.error instanceof b?n.error:null,o=e!==null&&e.size<=L,t=v(s,o),[a,g]=h.useState(!1),m=E(s,a),i=U({maxDisplayBytes:L,inline:{isLoading:n.isLoading,isError:n.isError,tooLarge:e?{size:e.size}:null,errorMessage:n.error instanceof Error?n.error.message:null,content:((x=n.data)==null?void 0:x.content)??null},streamed:{isLoading:t.isLoading,isError:t.isError,errorMessage:t.error instanceof Error?t.error.message:null,content:((f=t.data)==null?void 0:f.content)??null},download:{requested:a,isLoading:m.isLoading,objectUrl:((p=m.data)==null?void 0:p.objectUrl)??null,fileName:((w=m.data)==null?void 0:w.fileName)??null}});switch(i.kind){case"loading":return r.jsxs("div",{className:d.emptyState,children:[r.jsx(u,{size:"sm"})," Loading..."]});case"inline":return r.jsx(y,{path:s,content:i.content});case"streaming":return r.jsxs("div",{className:d.emptyState,children:[r.jsx(u,{size:"sm"})," Streaming ",c(i.size)," file..."]});case"stream-error":return r.jsxs("div",{className:d.emptyState,children:["Error: ",i.message]});case"streamed":return r.jsxs("div",{className:l.wrap,children:[r.jsxs("div",{className:l.note,children:[c(i.size)," file streamed"]}),r.jsx("div",{className:l.body,children:r.jsx(y,{path:s,content:i.content})})]});case"too-large":{const S=s.split("/").pop()||s;return r.jsx("div",{className:d.emptyState,children:r.jsxs("div",{className:l.tooLarge,children:[r.jsxs("div",{children:[c(i.size)," — too large to display (display ceiling is"," ",c(i.maxDisplayBytes),")."]}),i.downloading?r.jsx(u,{size:"sm"}):i.downloadUrl?r.jsx("a",{href:i.downloadUrl,download:i.downloadName||S,children:r.jsx(j,{size:"sm",children:"Save file"})}):r.jsx(j,{size:"sm",onClick:()=>g(!0),children:"Download"})]})})}case"error":return r.jsxs("div",{className:d.emptyState,children:["Error: ",i.message]})}}export{L as MAX_DISPLAY_BYTES,X as TextViewer};
2
- //# sourceMappingURL=TextViewer-3yEorz3A.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"TextViewer-3yEorz3A.js","sources":["../../../src/hooks/file-text-state.ts","../../../src/hooks/use-file-text.ts","../../../src/features/files/text-viewer-state.ts","../../../src/features/files/TextViewer.tsx"],"sourcesContent":["/**\n * Pure query-state merge for `use-file-text` (task-009), kept DOM/React-free so the\n * loading/error/data composition across the two dependent queries it wraps (download → decode)\n * is unit-testable directly, without `renderHook` (no jsdom test environment in this repo).\n */\n\nexport interface FileTextResult {\n content: string;\n}\n\nexport interface FileTextMergeInputs {\n enabled: boolean;\n download: { isLoading: boolean; isError: boolean; error: unknown; hasObjectUrl: boolean };\n decode: {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n };\n}\n\nexport interface FileTextQueryState {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n}\n\nexport function mergeFileTextState(input: FileTextMergeInputs): FileTextQueryState {\n const { enabled, download, decode } = input;\n return {\n isLoading: enabled && (download.isLoading || (download.hasObjectUrl && decode.isLoading)),\n isError: download.isError || decode.isError,\n error: download.isError ? download.error : decode.error,\n data: decode.data,\n };\n}\n","/**\n * `use-file-text` — tier-2 fallback for `TextViewer` (task-009): decodes a file's bytes to UTF-8\n * text via the already-uncapped chunked binary download path (`useFileDownload` →\n * `file_download_token_request`/`file_download_request`), for files over `file_read_request`'s\n * inline cap (`MAX_INLINE_FILE_READ_BYTES`, `packages/server/src/files/limits.ts`). Same\n * transport the molecule viewer uses for its own (binary-safe) source — no new RPC, no new\n * transport, just a text decode over the resulting blob.\n *\n * Note the daemon asymmetry documented on `useFileDownload`'s own RPCs: the download path is\n * registered only in the production bootstrap (`bootstrap.ts`), not `dev-bootstrap.ts`. Under\n * `npm run dev:daemon` a file above the inline cap fails this fetch rather than rendering — that\n * surfaces as the normal error state below, which is the intended behavior (see task-009 notes).\n *\n * The loading/error/data merge across the two dependent queries (download → decode) is the pure,\n * DOM-free `mergeFileTextState` (`file-text-state.ts`) — this hook is a thin wrapper feeding it\n * live query state.\n */\n\nimport { useQuery } from \"@tanstack/react-query\";\nimport { rpcKeys } from \"@pi-studio-ui/lib/connection/rpc-keys.js\";\nimport { useFileDownload } from \"./use-file-download.js\";\nimport { mergeFileTextState, type FileTextResult } from \"./file-text-state.js\";\n\nexport type { FileTextResult };\n\nexport function useFileText(path: string, enabled = true) {\n const download = useFileDownload(path, enabled);\n const objectUrl = download.data?.objectUrl;\n\n const decode = useQuery({\n queryKey: rpcKeys.fileText(path, objectUrl ?? null),\n queryFn: async (): Promise<FileTextResult> => {\n const content = await (await fetch(objectUrl as string)).text();\n return { content };\n },\n enabled: enabled && Boolean(objectUrl),\n });\n\n return mergeFileTextState({\n enabled,\n download: {\n isLoading: download.isLoading,\n isError: download.isError,\n error: download.error,\n hasObjectUrl: Boolean(objectUrl),\n },\n decode: {\n isLoading: decode.isLoading,\n isError: decode.isError,\n error: decode.error,\n data: decode.data,\n },\n });\n}\n","/**\n * Pure tier-selection logic for `TextViewer` (task-009), kept in its own DOM-free module so the\n * three-state branch (inline / streamed / download-only) is unit-testable without mounting\n * CodeMirror or React — mirrors `molecule-reload.ts`'s `shouldApplyRefresh` extraction for the\n * same reason: this repo has no jsdom test environment configured anywhere.\n */\n\nexport type TextViewerState =\n | { kind: \"loading\" }\n | { kind: \"inline\"; content: string }\n | { kind: \"streaming\"; size: number }\n | { kind: \"streamed\"; size: number; content: string }\n | { kind: \"stream-error\"; size: number; message: string }\n | {\n kind: \"too-large\";\n size: number;\n maxDisplayBytes: number;\n downloading: boolean;\n downloadUrl: string | null;\n downloadName: string | null;\n }\n | { kind: \"error\"; message: string };\n\nexport interface TextViewerInputs {\n maxDisplayBytes: number;\n inline: {\n isLoading: boolean;\n isError: boolean;\n /** `{ size }` when the failure was specifically `FileTooLargeError`; `null` for a generic\n * read failure (network/permission/etc). */\n tooLarge: { size: number } | null;\n errorMessage: string | null;\n content: string | null;\n };\n streamed: {\n isLoading: boolean;\n isError: boolean;\n errorMessage: string | null;\n content: string | null;\n };\n download: {\n requested: boolean;\n isLoading: boolean;\n objectUrl: string | null;\n fileName: string | null;\n };\n}\n\n/** Selects exactly one `TextViewerState` from the current query states. Pure — no hooks, no I/O. */\nexport function selectTextViewerState(input: TextViewerInputs): TextViewerState {\n const { maxDisplayBytes, inline, streamed, download } = input;\n\n if (inline.isLoading) return { kind: \"loading\" };\n\n if (inline.tooLarge) {\n const { size } = inline.tooLarge;\n if (size > maxDisplayBytes) {\n return {\n kind: \"too-large\",\n size,\n maxDisplayBytes,\n downloading: download.requested && download.isLoading,\n downloadUrl: download.objectUrl,\n downloadName: download.fileName,\n };\n }\n if (streamed.isLoading) return { kind: \"streaming\", size };\n if (streamed.isError) {\n return { kind: \"stream-error\", size, message: streamed.errorMessage ?? \"stream failed\" };\n }\n if (streamed.content !== null) return { kind: \"streamed\", size, content: streamed.content };\n return { kind: \"loading\" };\n }\n\n if (inline.isError) {\n return { kind: \"error\", message: inline.errorMessage ?? \"unknown error\" };\n }\n\n if (inline.content !== null) return { kind: \"inline\", content: inline.content };\n return { kind: \"loading\" };\n}\n","/**\n * TextViewer — the default viewer for source/text files: fetches the UTF-8 preview via\n * `useFileRead` and renders it through `CodeView` (line gutter + Shiki highlighting). Registered\n * in `viewer-registry.ts` as the fallback for any file not claimed by a more specific viewer.\n *\n * Three size tiers (task-009 — raising `file_read_request`'s old 512 KiB ceiling):\n * 1. `size <= MAX_INLINE_FILE_READ_BYTES` (server-side, 5 MiB) — the `useFileRead` JSON round\n * trip above, unchanged.\n * 2. `MAX_INLINE_FILE_READ_BYTES < size <= MAX_DISPLAY_BYTES` (30 MiB) — transparently refetch via\n * the uncapped chunked binary download path (`use-file-text.ts`) and render the same\n * `CodeView`, with a muted note that the file was streamed rather than read inline.\n * 3. `size > MAX_DISPLAY_BYTES` — a terminal state: no render attempt, just the size, why, and a\n * download action (`BinaryFallbackViewer`'s existing on-demand download pattern).\n *\n * Which tier applies is the pure, DOM-free `selectTextViewerState` (`text-viewer-state.ts`) — this\n * component is a thin switch-render over it.\n */\n\nimport { useState } from \"react\";\nimport { Button } from \"@pi-studio-ui/components/primitives/Button.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { useFileRead, FileTooLargeError } from \"@pi-studio-ui/hooks/use-file-read.js\";\nimport { useFileText } from \"@pi-studio-ui/hooks/use-file-text.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport { CodeView } from \"./CodeView.js\";\nimport { selectTextViewerState } from \"./text-viewer-state.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport styles from \"./FilePanel.module.css\";\nimport textStyles from \"./TextViewer.module.css\";\n\n/** Display ceiling above the inline cap. `CodeView`'s CodeMirror instance enables\n * `EditorView.lineWrapping`, which makes it measure line heights across the whole document —\n * well past interactive above this size, so files this large get a terminal download-only state\n * instead of an attempted render. Deliberately not configurable (task-009 notes). */\nexport const MAX_DISPLAY_BYTES = 30 * 1024 * 1024;\n\nfunction formatMegabytes(bytes: number): string {\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function TextViewer({ path }: ViewerProps) {\n const inline = useFileRead(path);\n const tooLarge = inline.error instanceof FileTooLargeError ? inline.error : null;\n const displayable = tooLarge !== null && tooLarge.size <= MAX_DISPLAY_BYTES;\n\n const streamed = useFileText(path, displayable);\n const [downloadRequested, setDownloadRequested] = useState(false);\n const download = useFileDownload(path, downloadRequested);\n\n const state = selectTextViewerState({\n maxDisplayBytes: MAX_DISPLAY_BYTES,\n inline: {\n isLoading: inline.isLoading,\n isError: inline.isError,\n tooLarge: tooLarge ? { size: tooLarge.size } : null,\n errorMessage: inline.error instanceof Error ? inline.error.message : null,\n content: inline.data?.content ?? null,\n },\n streamed: {\n isLoading: streamed.isLoading,\n isError: streamed.isError,\n errorMessage: streamed.error instanceof Error ? streamed.error.message : null,\n content: streamed.data?.content ?? null,\n },\n download: {\n requested: downloadRequested,\n isLoading: download.isLoading,\n objectUrl: download.data?.objectUrl ?? null,\n fileName: download.data?.fileName ?? null,\n },\n });\n\n switch (state.kind) {\n case \"loading\":\n return (\n <div className={styles.emptyState}>\n <Spinner size=\"sm\" /> Loading...\n </div>\n );\n case \"inline\":\n return <CodeView path={path} content={state.content} />;\n case \"streaming\":\n return (\n <div className={styles.emptyState}>\n <Spinner size=\"sm\" /> Streaming {formatMegabytes(state.size)} file...\n </div>\n );\n case \"stream-error\":\n return <div className={styles.emptyState}>Error: {state.message}</div>;\n case \"streamed\":\n return (\n <div className={textStyles.wrap}>\n <div className={textStyles.note}>{formatMegabytes(state.size)} file streamed</div>\n <div className={textStyles.body}>\n <CodeView path={path} content={state.content} />\n </div>\n </div>\n );\n case \"too-large\": {\n const name = path.split(\"/\").pop() || path;\n return (\n <div className={styles.emptyState}>\n <div className={textStyles.tooLarge}>\n <div>\n {formatMegabytes(state.size)} — too large to display (display ceiling is{\" \"}\n {formatMegabytes(state.maxDisplayBytes)}).\n </div>\n {state.downloading ? (\n <Spinner size=\"sm\" />\n ) : state.downloadUrl ? (\n <a href={state.downloadUrl} download={state.downloadName || name}>\n <Button size=\"sm\">Save file</Button>\n </a>\n ) : (\n <Button size=\"sm\" onClick={() => setDownloadRequested(true)}>\n Download\n </Button>\n )}\n </div>\n </div>\n );\n }\n case \"error\":\n return <div className={styles.emptyState}>Error: {state.message}</div>;\n }\n}\n"],"names":["mergeFileTextState","input","enabled","download","decode","useFileText","path","useFileDownload","objectUrl","_a","useQuery","rpcKeys","selectTextViewerState","maxDisplayBytes","inline","streamed","size","MAX_DISPLAY_BYTES","formatMegabytes","bytes","TextViewer","useFileRead","tooLarge","FileTooLargeError","displayable","downloadRequested","setDownloadRequested","useState","state","_b","_c","_d","jsxs","styles","jsx","Spinner","CodeView","textStyles","name","Button"],"mappings":"+gBA4BO,SAASA,EAAmBC,EAAgD,CACjF,KAAM,CAAE,QAAAC,EAAS,SAAAC,EAAU,OAAAC,CAAA,EAAWH,EACtC,MAAO,CACL,UAAWC,IAAYC,EAAS,WAAcA,EAAS,cAAgBC,EAAO,WAC9E,QAASD,EAAS,SAAWC,EAAO,QACpC,MAAOD,EAAS,QAAUA,EAAS,MAAQC,EAAO,MAClD,KAAMA,EAAO,IAAA,CAEjB,CCXO,SAASC,EAAYC,EAAcJ,EAAU,GAAM,OACxD,MAAMC,EAAWI,EAAgBD,EAAMJ,CAAO,EACxCM,GAAYC,EAAAN,EAAS,OAAT,YAAAM,EAAe,UAE3BL,EAASM,EAAS,CACtB,SAAUC,EAAQ,SAASL,EAAME,GAAa,IAAI,EAClD,QAAS,UAEA,CAAE,QADO,MAAO,MAAM,MAAMA,CAAmB,GAAG,KAAA,CAChD,GAEX,QAASN,GAAW,EAAQM,CAAS,CACtC,EAED,OAAOR,EAAmB,CACxB,QAAAE,EACA,SAAU,CACR,UAAWC,EAAS,UACpB,QAASA,EAAS,QAClB,MAAOA,EAAS,MAChB,aAAc,EAAQK,CAAS,EAEjC,OAAQ,CACN,UAAWJ,EAAO,UAClB,QAASA,EAAO,QAChB,MAAOA,EAAO,MACd,KAAMA,EAAO,IAAA,CACf,CACD,CACH,CCJO,SAASQ,EAAsBX,EAA0C,CAC9E,KAAM,CAAE,gBAAAY,EAAiB,OAAAC,EAAQ,SAAAC,EAAU,SAAAZ,GAAaF,EAExD,GAAIa,EAAO,UAAW,MAAO,CAAE,KAAM,SAAA,EAErC,GAAIA,EAAO,SAAU,CACnB,KAAM,CAAE,KAAAE,GAASF,EAAO,SACxB,OAAIE,EAAOH,EACF,CACL,KAAM,YACN,KAAAG,EACA,gBAAAH,EACA,YAAaV,EAAS,WAAaA,EAAS,UAC5C,YAAaA,EAAS,UACtB,aAAcA,EAAS,QAAA,EAGvBY,EAAS,UAAkB,CAAE,KAAM,YAAa,KAAAC,CAAA,EAChDD,EAAS,QACJ,CAAE,KAAM,eAAgB,KAAAC,EAAM,QAASD,EAAS,cAAgB,eAAA,EAErEA,EAAS,UAAY,KAAa,CAAE,KAAM,WAAY,KAAAC,EAAM,QAASD,EAAS,OAAA,EAC3E,CAAE,KAAM,SAAA,CACjB,CAEA,OAAID,EAAO,QACF,CAAE,KAAM,QAAS,QAASA,EAAO,cAAgB,eAAA,EAGtDA,EAAO,UAAY,KAAa,CAAE,KAAM,SAAU,QAASA,EAAO,OAAA,EAC/D,CAAE,KAAM,SAAA,CACjB,yHC9CaG,EAAoB,GAAK,KAAO,KAE7C,SAASC,EAAgBC,EAAuB,CAC9C,MAAO,IAAIA,GAAS,KAAO,OAAO,QAAQ,CAAC,CAAC,KAC9C,CAEO,SAASC,EAAW,CAAE,KAAAd,GAAqB,aAChD,MAAMQ,EAASO,EAAYf,CAAI,EACzBgB,EAAWR,EAAO,iBAAiBS,EAAoBT,EAAO,MAAQ,KACtEU,EAAcF,IAAa,MAAQA,EAAS,MAAQL,EAEpDF,EAAWV,EAAYC,EAAMkB,CAAW,EACxC,CAACC,EAAmBC,CAAoB,EAAIC,EAAAA,SAAS,EAAK,EAC1DxB,EAAWI,EAAgBD,EAAMmB,CAAiB,EAElDG,EAAQhB,EAAsB,CAClC,gBAAiBK,EACjB,OAAQ,CACN,UAAWH,EAAO,UAClB,QAASA,EAAO,QAChB,SAAUQ,EAAW,CAAE,KAAMA,EAAS,MAAS,KAC/C,aAAcR,EAAO,iBAAiB,MAAQA,EAAO,MAAM,QAAU,KACrE,UAASL,EAAAK,EAAO,OAAP,YAAAL,EAAa,UAAW,IAAA,EAEnC,SAAU,CACR,UAAWM,EAAS,UACpB,QAASA,EAAS,QAClB,aAAcA,EAAS,iBAAiB,MAAQA,EAAS,MAAM,QAAU,KACzE,UAASc,EAAAd,EAAS,OAAT,YAAAc,EAAe,UAAW,IAAA,EAErC,SAAU,CACR,UAAWJ,EACX,UAAWtB,EAAS,UACpB,YAAW2B,EAAA3B,EAAS,OAAT,YAAA2B,EAAe,YAAa,KACvC,WAAUC,EAAA5B,EAAS,OAAT,YAAA4B,EAAe,WAAY,IAAA,CACvC,CACD,EAED,OAAQH,EAAM,KAAA,CACZ,IAAK,UACH,OACEI,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,WACrB,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,aAAA,EACvB,EAEJ,IAAK,SACH,OAAOD,EAAAA,IAACE,EAAA,CAAS,KAAA9B,EAAY,QAASsB,EAAM,QAAS,EACvD,IAAK,YACH,OACEI,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,WACrB,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,cAAYjB,EAAgBU,EAAM,IAAI,EAAE,UAAA,EAC/D,EAEJ,IAAK,eACH,OAAOI,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,WAAY,SAAA,CAAA,UAAQL,EAAM,OAAA,EAAQ,EAClE,IAAK,WACH,OACEI,EAAAA,KAAC,MAAA,CAAI,UAAWK,EAAW,KACzB,SAAA,CAAAL,EAAAA,KAAC,MAAA,CAAI,UAAWK,EAAW,KAAO,SAAA,CAAAnB,EAAgBU,EAAM,IAAI,EAAE,gBAAA,EAAc,EAC5EM,EAAAA,IAAC,MAAA,CAAI,UAAWG,EAAW,KACzB,SAAAH,EAAAA,IAACE,EAAA,CAAS,KAAA9B,EAAY,QAASsB,EAAM,OAAA,CAAS,CAAA,CAChD,CAAA,EACF,EAEJ,IAAK,YAAa,CAChB,MAAMU,EAAOhC,EAAK,MAAM,GAAG,EAAE,OAASA,EACtC,OACE4B,EAAAA,IAAC,OAAI,UAAWD,EAAO,WACrB,SAAAD,EAAAA,KAAC,MAAA,CAAI,UAAWK,EAAW,SACzB,SAAA,CAAAL,OAAC,MAAA,CACE,SAAA,CAAAd,EAAgBU,EAAM,IAAI,EAAE,8CAA4C,IACxEV,EAAgBU,EAAM,eAAe,EAAE,IAAA,EAC1C,EACCA,EAAM,YACLM,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EACjBP,EAAM,kBACP,IAAA,CAAE,KAAMA,EAAM,YAAa,SAAUA,EAAM,cAAgBU,EAC1D,SAAAJ,MAACK,EAAA,CAAO,KAAK,KAAK,SAAA,WAAA,CAAS,EAC7B,EAEAL,EAAAA,IAACK,EAAA,CAAO,KAAK,KAAK,QAAS,IAAMb,EAAqB,EAAI,EAAG,SAAA,UAAA,CAE7D,CAAA,CAAA,CAEJ,CAAA,CACF,CAEJ,CACA,IAAK,QACH,OAAOM,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,WAAY,SAAA,CAAA,UAAQL,EAAM,OAAA,EAAQ,CAAA,CAEtE"}
@@ -1 +0,0 @@
1
- ._wrap_hx688_1{display:flex;flex-direction:column;height:100%;min-height:0}._note_hx688_7{padding:4px 14px;font-size:var(--pi-font-size-2xs);color:var(--pi-color-foregroundMuted, #9aa0a6);background:var(--pi-color-surface, #16181a);border-bottom:1px solid var(--pi-color-border, #353b46);flex-shrink:0}._body_hx688_15{flex:1;min-height:0}._tooLarge_hx688_19{display:flex;flex-direction:column;align-items:center;gap:12px}
@@ -1 +0,0 @@
1
- ._wrap_1c9y4_1{display:flex;align-items:center;justify-content:center;height:100%;min-height:0;padding:20px;background:var(--pi-color-surfaceSunken, #111)}._video_1c9y4_10{max-width:100%;max-height:100%}
@@ -1,2 +0,0 @@
1
- import{j as o}from"./vendor-react-CWo7Do4s.js";import{S as t}from"./index-CEP1cIKf.js";import{u as a}from"./use-file-download-BTSuk1Eh.js";import{p as e}from"./FilePanel.module-CqISrbT-.js";import"./vendor-query-BGIh-vlp.js";import"./vendor-04vXFIXe.js";import"./vendor-markdown-YvkQLm_s.js";import"./vendor-highlight-Efc6A-g6.js";import"./vendor-icons-o8-A85LK.js";import"./vendor-overlays-BnmaUbKw.js";import"./vendor-dnd-CH6z-X6S.js";const n="_wrap_1c9y4_1",m="_video_1c9y4_10",i={wrap:n,video:m};function _({path:s}){const r=a(s);return r.isLoading?o.jsxs("div",{className:e.emptyState,children:[o.jsx(t,{size:"sm"})," Loading video..."]}):r.isError?o.jsxs("div",{className:e.emptyState,children:["Error: ",r.error instanceof Error?r.error.message:"unknown error"]}):r.data?o.jsx("div",{className:i.wrap,children:o.jsx("video",{className:i.video,src:r.data.objectUrl,controls:!0})}):null}export{_ as VideoViewer};
2
- //# sourceMappingURL=VideoViewer-CbBaI4CK.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"VideoViewer-CbBaI4CK.js","sources":["../../../src/features/files/VideoViewer.tsx"],"sourcesContent":["/**\n * VideoViewer — renders a binary video file via the file-transfer binary download\n * (`useFileDownload`) into a native `<video>` element (POC_TO_APP_PLAN_UI.md §4.5 follow-up:\n * modular file preview).\n */\n\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport panelStyles from \"./FilePanel.module.css\";\nimport styles from \"./VideoViewer.module.css\";\n\nexport function VideoViewer({ path }: ViewerProps) {\n const query = useFileDownload(path);\n\n if (query.isLoading) {\n return (\n <div className={panelStyles.emptyState}>\n <Spinner size=\"sm\" /> Loading video...\n </div>\n );\n }\n if (query.isError) {\n return (\n <div className={panelStyles.emptyState}>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </div>\n );\n }\n if (!query.data) return null;\n\n return (\n <div className={styles.wrap}>\n {/* eslint-disable-next-line jsx-a11y/media-has-caption -- arbitrary local file, no caption track available */}\n <video className={styles.video} src={query.data.objectUrl} controls />\n </div>\n );\n}\n"],"names":["VideoViewer","path","query","useFileDownload","jsxs","panelStyles","jsx","Spinner","styles"],"mappings":"ofAYO,SAASA,EAAY,CAAE,KAAAC,GAAqB,CACjD,MAAMC,EAAQC,EAAgBF,CAAI,EAElC,OAAIC,EAAM,UAENE,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAC1B,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,mBAAA,EACvB,EAGAL,EAAM,QAENE,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAY,WAAY,SAAA,CAAA,UAC9BH,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,WAGR,MAAA,CAAI,UAAWM,EAAO,KAErB,eAAC,QAAA,CAAM,UAAWA,EAAO,MAAO,IAAKN,EAAM,KAAK,UAAW,SAAQ,GAAC,EACtE,EANsB,IAQ1B"}
@@ -1,3 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatPanel-8Tj813-O.js","assets/vendor-react-CWo7Do4s.js","assets/vendor-query-BGIh-vlp.js","assets/vendor-icons-o8-A85LK.js","assets/markdown-9_X86EBj.js","assets/vendor-highlight-Efc6A-g6.js","assets/vendor-markdown-YvkQLm_s.js","assets/vendor-04vXFIXe.js","assets/markdown-DEdmq7db.css","assets/StatusBadge-CJBuPnrc.js","assets/StatusBadge-4JuIxBe-.css","assets/DiffView-E-36gscH.js","assets/DiffView-txOCMsXo.css","assets/vendor-overlays-BnmaUbKw.js","assets/vendor-dnd-CH6z-X6S.js","assets/ChatPanel-DBXDoy3Z.css","assets/FilePanel-1jMXusYi.js","assets/use-file-watch-DZfGlL1N.js","assets/FilePanel.module-CqISrbT-.js","assets/FilePanel-CympQkwn.css","assets/TerminalPanel-BQZ0KqJv.js","assets/vendor-terminal-BhzX2_ts.js","assets/vendor-terminal-DYP7pi_n.css","assets/TerminalPanel-CfG2gRmZ.css","assets/MoleculeViewerPanel-CtODGGih.js","assets/vendor-molviewer-CARaM-YQ.js","assets/vendor-molviewer-Bychyqid.css","assets/use-file-download-BTSuk1Eh.js","assets/MoleculeViewerPanel-B-0MaJMt.css","assets/TextViewer-3yEorz3A.js","assets/CodeView-DNKpvKfm.js","assets/CodeView-Bbd7h9aM.css","assets/TextViewer-Bcv3IFDK.css","assets/MarkdownFileViewer-BChv2tKK.js","assets/MarkdownFileViewer-BD5Ri_Fb.css","assets/ImageViewer-Cimj0SFJ.js","assets/ImageViewer-ijzMsq8H.css","assets/VideoViewer-CbBaI4CK.js","assets/VideoViewer-BBuZ4wou.css","assets/BinaryFallbackViewer-BPcn4yCY.js","assets/BinaryFallbackViewer-BnBkar4_.css"])))=>i.map(i=>d[i]);
2
- var ss=Object.defineProperty;var os=(e,t,n)=>t in e?ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var N=(e,t,n)=>os(e,typeof t!="symbol"?t+"":t,n);import{r as w,j as a,c as rs}from"./vendor-react-CWo7Do4s.js";import{Q as as,a as is,u as un,b as cs,c as Me,d as ls}from"./vendor-query-BGIh-vlp.js";import{A as l,B as u,C as W,D as fn,E as D,F as ve,G as fe,H as A,I as b,J as U,K as G,L as lt,M as Ee,N as ke}from"./vendor-04vXFIXe.js";import{L as ds,P as us,a as fs,b as ps,c as hs,E as Et,d as ms,S as gs,A as _s,T as Nt,C as Rt,e as pn,F as ys,f as hn,g as mn,h as Mt,i as gn,G as _n,j as ws,M as yn,X as bt,k as Ne,l as wn,m as xt,n as at,o as Je,p as bs,D as xs,U as Ss,R as vs,q as bn,r as ks,s as Is,t as js,u as Cs,v as Ts,w as Es}from"./vendor-icons-o8-A85LK.js";import{R as Ke,T as Ve,P as Ge,C as Xe,I as P,S as Se,D as Ns,a as Rs,b as Ms,c as qs,d as zt,e as St}from"./vendor-overlays-BnmaUbKw.js";import{u as Bs,a as $s,D as Ds,c as As,S as Ps,h as Os,P as Fs,b as zs,C as Ws}from"./vendor-dnd-CH6z-X6S.js";import{_ as pe}from"./vendor-highlight-Efc6A-g6.js";import"./vendor-markdown-YvkQLm_s.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const i of r.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=n(o);fetch(o.href,r)}})();const Ls=new as;function xn(e){const t=e.trim().replace(/^#/,""),n=t.length===3?t.split("").map(s=>s+s).join(""):t;if(n.length!==6||/[^0-9a-fA-F]/.test(n))throw new Error(`Invalid hex color: ${e}`);return{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}function Hs(e){return Math.max(0,Math.min(255,Math.round(e)))}function Us({r:e,g:t,b:n}){const s=o=>Hs(o).toString(16).padStart(2,"0");return`#${s(e)}${s(t)}${s(n)}`}function Ks(e){const{r:t,g:n,b:s}=xn(e),o=r=>{const i=r/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4};return .2126*o(t)+.7152*o(n)+.0722*o(s)}function qt(e,t="#18181b",n="#ffffff"){return Ks(e)>.45?t:n}function Vs(e,t){const{r:n,g:s,b:o}=xn(e),r=Math.max(0,Math.min(1,t));return Us({r:n+(255-n)*r,g:s+(255-s)*r,b:o+(255-o)*r})}function Qe(e){const t=e.trim().replace(/^#/,"");return(t.length===3||t.length===6)&&!/[^0-9a-fA-F]/.test(t)}const ne=(e,t,n,s,o,r,i,c,d,h,m)=>({50:e,100:t,200:n,300:s,400:o,500:r,600:i,700:c,800:d,900:h,950:m}),S={zinc:ne("#fafafa","#f4f4f5","#e4e4e7","#d4d4d8","#a1a1aa","#71717a","#52525b","#3f3f46","#27272a","#18181b","#09090b"),gray:ne("#f9fafb","#f3f4f6","#e5e7eb","#d1d5db","#9ca3af","#6b7280","#4b5563","#374151","#1f2937","#111827","#030712"),slate:ne("#f8fafc","#f1f5f9","#e2e8f0","#cbd5e1","#94a3b8","#64748b","#475569","#334155","#1e293b","#0f172a","#020617"),blue:ne("#eff6ff","#dbeafe","#bfdbfe","#93c5fd","#60a5fa","#3b82f6","#2563eb","#1d4ed8","#1e40af","#1e3a8a","#172554"),green:ne("#f0fdf4","#dcfce7","#bbf7d0","#86efac","#4ade80","#22c55e","#16a34a","#15803d","#166534","#14532d","#052e16"),red:ne("#fef2f2","#fee2e2","#fecaca","#fca5a5","#f87171","#ef4444","#dc2626","#b91c1c","#991b1b","#7f1d1d","#450a0a"),teal:ne("#f0fdfa","#ccfbf1","#99f6e4","#5eead4","#2dd4bf","#14b8a6","#0d9488","#0f766e","#115e59","#134e4a","#042f2e"),amber:ne("#fffbeb","#fef3c7","#fde68a","#fcd34d","#fbbf24","#f59e0b","#d97706","#b45309","#92400e","#78350f","#451a03"),yellow:ne("#fefce8","#fef9c3","#fef08a","#fde047","#facc15","#eab308","#ca8a04","#a16207","#854d0e","#713f12","#422006"),purple:ne("#faf5ff","#f3e8ff","#e9d5ff","#d8b4fe","#c084fc","#a855f7","#9333ea","#7e22ce","#6b21a8","#581c87","#3b0764"),orange:ne("#fff7ed","#ffedd5","#fed7aa","#fdba74","#fb923c","#f97316","#ea580c","#c2410c","#9a3412","#7c2d12","#431407"),white:"#ffffff",black:"#000000"},Gs={statusSuccess:"#16a34a",statusDanger:"#dc2626",statusWarning:"#f59e0b",statusMerged:"#9333ea"},Xs={statusSuccess:"#15803d",statusDanger:"#b91c1c",statusWarning:"#d97706",statusMerged:"#7c3aed"};function Ys(){return{keyword:S.purple[300],string:S.green[300],number:S.orange[300],boolean:S.orange[300],comment:S.zinc[500],function:S.blue[300],variable:S.zinc[200],type:S.teal[300],class:S.amber[300],constant:S.orange[300],operator:S.zinc[400],punctuation:S.zinc[400],tag:S.red[300],attribute:S.amber[300],property:S.blue[200],regexp:S.teal[300],escape:S.orange[200],heading:S.blue[300],link:S.blue[400],deleted:S.red[400],inserted:S.green[400]}}function Js(){return{keyword:S.purple[700],string:S.green[700],number:S.orange[700],boolean:S.orange[700],comment:S.zinc[500],function:S.blue[700],variable:S.zinc[800],type:S.teal[700],class:S.amber[700],constant:S.orange[700],operator:S.zinc[600],punctuation:S.zinc[600],tag:S.red[700],attribute:S.amber[700],property:S.blue[700],regexp:S.teal[700],escape:S.orange[700],heading:S.blue[700],link:S.blue[600],deleted:S.red[700],inserted:S.green[700]}}function Sn(e,t,n){return{background:e,foreground:t,cursor:n,cursorAccent:e,selectionBackground:"rgba(255,255,255,0.18)",black:S.zinc[900],red:S.red[500],green:S.green[500],yellow:S.amber[500],blue:S.blue[500],magenta:S.purple[500],cyan:S.teal[500],white:S.zinc[300],brightBlack:S.zinc[600],brightRed:S.red[400],brightGreen:S.green[400],brightYellow:S.amber[400],brightBlue:S.blue[400],brightMagenta:S.purple[400],brightCyan:S.teal[400],brightWhite:S.zinc[50]}}function Ae(e){const t=S.zinc[50],n=qt(e.accent);return{surface0:e.surface0,surface1:e.surface1,surface2:e.surface2,surface3:e.surface3,surface4:e.surface4,surfaceDiffEmpty:e.surfaceDiffEmpty,surfaceSidebar:e.surfaceSidebar,surfaceSidebarHover:e.surfaceSidebarHover,surfaceWorkspace:e.surface1,foreground:t,foregroundMuted:e.mutedForeground,accent:e.accent,accentBright:e.accentBright,accentForeground:n,destructive:e.destructive,destructiveForeground:S.white,success:e.accent,successForeground:S.white,border:e.border,borderAccent:e.borderAccent,...Gs,diffAddition:S.green[400],diffDeletion:S.red[500],scrollbarHandle:e.scrollbarHandle,background:e.surface0,popover:e.surface2,popoverForeground:t,primary:e.accent,secondary:e.surface2,muted:e.surface2,mutedForeground:e.mutedForeground,input:e.surface2,ring:e.accent,palette:S,syntax:Ys(),terminal:Sn(e.surface0,t,e.accent)}}function Qs(){const e="#1a1a1e",t="#253e6f";return{surface0:"#ffffff",surface1:"#fafafa",surface2:"#f4f4f5",surface3:"#e4e4e7",surface4:"#d4d4d8",surfaceDiffEmpty:"#f6f6f6",surfaceSidebar:"#f4f4f5",surfaceSidebarHover:"#e9e9ec",surfaceWorkspace:"#ffffff",foreground:e,foregroundMuted:"#71717a",accent:t,accentBright:"#2f4f8e",accentForeground:qt(t),destructive:"#b04138",destructiveForeground:"#ffffff",success:t,successForeground:"#ffffff",border:"#e4e4e7",borderAccent:"#ececf1",...Xs,diffAddition:"#15803d",diffDeletion:"#b91c1c",scrollbarHandle:"#3f3f46",background:"#ffffff",popover:"#ffffff",popoverForeground:e,primary:t,secondary:"#f4f4f5",muted:"#f4f4f5",mutedForeground:"#71717a",input:"#f4f4f5",ring:t,palette:S,syntax:Js(),terminal:{...Sn("#ffffff",e,t),selectionBackground:"rgba(0,0,0,0.15)",white:"#ffffff",brightWhite:"#fafafa"}}}const Zs={light:"#ffffff",dark:"#3b62b0",zinc:"#808080",midnight:"#4A6BA8",claude:"#D97757",ghostty:"#8caaee"},vn=["light","dark","zinc","midnight","claude","ghostty"];function eo(e){if(e==="light")return Qs();switch(e){case"dark":return Ae({surface0:"#181B1A",surface1:"#1E2120",surface2:"#272A29",surface3:"#434645",surface4:"#595B5B",surfaceDiffEmpty:"#252827",surfaceSidebar:"#141716",surfaceSidebarHover:"#1c1f1e",mutedForeground:"#A1A5A4",scrollbarHandle:"#717574",border:"#252B2A",borderAccent:"#2f3135",accent:"#2e5cb8",accentBright:"#a2b4d7",destructive:"#c64f43"});case"zinc":return Ae({surface0:"#18181b",surface1:"#1f1f22",surface2:"#27272a",surface3:"#3f3f46",surface4:"#52525b",surfaceDiffEmpty:"#242427",surfaceSidebar:"#131316",surfaceSidebarHover:"#1b1b1e",mutedForeground:"#a1a1aa",scrollbarHandle:"#71717a",border:"#27272a",borderAccent:"#303036",accent:"#e4e4e7",accentBright:"#fafafa",destructive:"#c44a4a"});case"midnight":return Ae({surface0:"#161820",surface1:"#1c1e27",surface2:"#252731",surface3:"#3c3e4c",surface4:"#535564",surfaceDiffEmpty:"#222430",surfaceSidebar:"#121420",surfaceSidebarHover:"#1a1c28",mutedForeground:"#9a9db0",scrollbarHandle:"#6b6e82",border:"#242636",borderAccent:"#2e3040",accent:"#3b6fcf",accentBright:"#7eaaeb",destructive:"#c44a52"});case"claude":return Ae({surface0:"#1f1f1e",surface1:"#262523",surface2:"#2f2d2b",surface3:"#4a4745",surface4:"#605d5b",surfaceDiffEmpty:"#2a2826",surfaceSidebar:"#1a1918",surfaceSidebarHover:"#222120",mutedForeground:"#ada9a5",scrollbarHandle:"#78746f",border:"#2c2a27",borderAccent:"#36332f",accent:"#d97757",accentBright:"#e89a7f",destructive:"#cf513e"});case"ghostty":return Ae({surface0:"#282c34",surface1:"#2f333d",surface2:"#383c48",surface3:"#4a4f5e",surface4:"#5b6175",surfaceDiffEmpty:"#323643",surfaceSidebar:"#21252d",surfaceSidebarHover:"#292d36",mutedForeground:"#c8ccd8",scrollbarHandle:"#a0a4b2",border:"#353a47",borderAccent:"#3f4454",accent:"#89b4fa",accentBright:"#b4d0fc",destructive:"#c44a55"})}}const kn={};for(const e of vn){const t=e==="light"?"light":"dark";kn[e]={name:e,colorScheme:t,colors:eo(e),swatch:Zs[e]}}const to=kn,no={0:0,1:4,"1.5":6,2:8,3:12,4:16,6:24,8:32,12:48,16:64,20:80,24:96,32:128},it={"4xs":10,"3xs":11,"2xs":12,xs:13,code:13,sm:14,md:15,base:17,lg:19,xl:21,"2xl":23,"3xl":28,"4xl":36},so={normal:"400",medium:"500",semibold:"600",bold:"700"},oo={none:0,sm:2,base:4,md:6,lg:8,xl:12,"2xl":16,full:9999},ro={0:0,1:1,2:2},ao={0:0,50:.5,100:1},io={xs:12,sm:14,md:16,lg:20},co={diff:22},In='system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',jn='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';function lo(e){const t=e==="dark"?"rgba(0,0,0,0.55)":"rgba(24,24,27,0.12)";return{sm:{color:t,offsetX:0,offsetY:1,radius:2,elevation:1},md:{color:t,offsetX:0,offsetY:3,radius:8,elevation:4},lg:{color:t,offsetX:0,offsetY:10,radius:24,elevation:12}}}function Cn(e){const t=to[e];return{name:e,colorScheme:t.colorScheme,colors:t.colors,spacing:no,fontSize:{...it},fontFamily:{ui:In,mono:jn},lineHeight:{...co},iconSize:io,fontWeight:so,borderRadius:oo,borderWidth:ro,opacity:ao,shadow:lo(t.colorScheme),swatch:t.swatch}}const uo=it.base,fo=10,po=24;function ho(e,t){const n=t.themeName??e.name,s=Cn(n),o=t.uiFont&&t.uiFont.trim()!==""?t.uiFont:In,r=t.monoFont&&t.monoFont.trim()!==""?t.monoFont:jn,i={...s.fontSize};if(t.fontSize!=null){const d=Math.max(fo,Math.min(po,t.fontSize))/uo;for(const h of Object.keys(it))i[h]=Math.round(it[h]*d)}return{...s,fontSize:i,fontFamily:{ui:o,mono:r}}}function mo(e){return Cn(e)}const go="dark",_o=16;function yo(e){const t=e/_o;return`${Number(t.toFixed(4))}rem`}function wo(e){const t={};bo(e.colors,t);for(const[n,s]of Object.entries(e.spacing))t[`--pi-spacing-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.fontSize))t[`--pi-font-size-${n}`]=yo(s);t["--pi-font-ui"]=e.fontFamily.ui,t["--pi-font-mono"]=e.fontFamily.mono,t["--pi-line-height-diff"]=`${e.lineHeight.diff}px`;for(const[n,s]of Object.entries(e.iconSize))t[`--pi-icon-size-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.fontWeight))t[`--pi-font-weight-${n}`]=String(s);for(const[n,s]of Object.entries(e.borderRadius))t[`--pi-radius-${n}`]=s===9999?"9999px":`${s}px`;for(const[n,s]of Object.entries(e.borderWidth))t[`--pi-border-width-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.opacity))t[`--pi-opacity-${n}`]=String(s);for(const[n,s]of Object.entries(e.shadow))if(typeof s=="string")t[`--pi-shadow-${n}`]=s;else if(s&&typeof s=="object"){const o=s;t[`--pi-shadow-${n}`]=`${o.offsetX}px ${o.offsetY}px ${o.radius}px ${o.color}`}return t["--pi-color-scheme"]=e.colorScheme,t}function bo(e,t){const{palette:n,syntax:s,terminal:o,...r}=e;for(const[i,c]of Object.entries(r))typeof c=="string"&&(t[`--pi-color-${i}`]=c);s&&xo(s,t),o&&(t["--pi-terminal-bg"]=o.background,t["--pi-terminal-fg"]=o.foreground)}function xo(e,t){for(const[n,s]of Object.entries(e))typeof s=="string"&&(t[`--syntax-${So(n)}`]=s)}function So(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function vo(e){if(typeof document>"u")return;const t=document.documentElement.style;for(const[s,o]of Object.entries(e))t.setProperty(s,o);const n=e["--pi-color-scheme"];n&&document.documentElement.style.setProperty("color-scheme",n)}function ko(e){const t=wo(e);vo(t)}const Pe=l().min(1,"Asset path must not be empty"),Io=u({accent:l().refine(Qe,{message:"accent must be a valid #rrggbb hex color"}),accentBright:l().refine(Qe,{message:"accentBright must be a valid #rrggbb hex color"}).optional(),accentForeground:l().refine(Qe,{message:"accentForeground must be a valid #rrggbb hex color"}).optional(),swatch:l().refine(Qe,{message:"swatch must be a valid #rrggbb hex color"}).optional()}),jo=u({logoLight:Pe,logoDark:Pe,logoMark:Pe.optional(),icon:Pe,splash:Pe.optional()}),Co=u({docs:l().url().optional(),support:l().url().optional(),issues:l().url().optional(),website:l().url().optional()}).optional(),To=u({copyright:l().optional(),companyName:l().optional()}).optional();u({productName:l().min(1,"productName is required"),shortName:l().optional(),tagline:l().optional(),colors:Io,assets:jo,links:Co,legal:To});function Eo(e){const t=e.accent,n=e.accentBright??Vs(t,.35),s=e.accentForeground??qt(t),o=e.swatch??t;return{accent:t,accentBright:n,accentForeground:s,swatch:o}}function No(e,t){return{...e,colors:{...e.colors,accent:t.accent,accentBright:t.accentBright,accentForeground:t.accentForeground,primary:t.accent,ring:t.accent},swatch:t.swatch}}const Wt="pi-studio-appearance";function Ro(e,t){let n=c(e),s=null;function o(m){return m==="system"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":m}function r(m,x){const f=o(m),p=mo(f);let v=ho(p,{...x,themeName:f});if(t!=null&&t.colors){const y=Eo(t.colors);v=No(v,y)}return v}function i(){const m=JSON.stringify({mode:n.mode,settings:n.settings});e.set(Wt,m)}function c(m){const x=m.get(Wt);let f=go,p={};if(x)try{const y=JSON.parse(x);y.mode&&(vn.includes(y.mode)||y.mode==="system")&&(f=y.mode),y.settings&&typeof y.settings=="object"&&(p=y.settings)}catch{}const v=r(f,p);return{mode:f,settings:p,resolvedTheme:v}}function d(){n={...n,resolvedTheme:r(n.mode,n.settings)},i()}const h={getState(){return n},setMode(m){n={...n,mode:m},d(),h.apply()},updateSettings(m){n={...n,settings:{...n.settings,...m}},d(),h.apply()},apply(){ko(n.resolvedTheme)},listen(){if(typeof window>"u")return()=>{};const m=window.matchMedia("(prefers-color-scheme: dark)"),x=()=>{n.mode==="system"&&(d(),h.apply())};return m.addEventListener("change",x),s=()=>m.removeEventListener("change",x),s}};return h}function Mo({store:e,brandConfig:t,children:n}){const s=w.useRef(null);return s.current||(s.current=Ro(e,t),s.current.apply()),w.useEffect(()=>s.current.listen(),[]),a.jsx(a.Fragment,{children:n})}const qo={get(e){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem(e))??null}catch{return null}},set(e,t){var n;try{(n=globalThis.localStorage)==null||n.setItem(e,t)}catch{}}};function Bo({children:e}){return a.jsx(Mo,{store:qo,children:a.jsx(is,{client:Ls,children:e})})}const $o="_btn_1chbg_4",Do="_secondary_1chbg_44",Ao="_outline_1chbg_53",Po="_ghost_1chbg_62",Oo="_destructive_1chbg_72",Fo="_iconOnly_1chbg_82",zo="_loadingSpinner_1chbg_89",Wo="_piSpin_1chbg_1",Ze={btn:$o,default:"_default_1chbg_35",secondary:Do,outline:Ao,ghost:Po,destructive:Oo,iconOnly:Fo,loadingSpinner:zo,piSpin:Wo},Lt={xs:28,sm:32,md:36,lg:40},Lo={xs:12,sm:14,md:16,lg:20},Ht={xs:8,sm:10,md:12,lg:16},Ho={xs:"var(--pi-font-size-xs)",sm:"var(--pi-font-size-sm)",md:"var(--pi-font-size-md)",lg:"var(--pi-font-size-base)"};function Uo(e){const{disabled:t,loading:n}=e;return t||n?{opacity:.5,isGhostHover:!1}:{opacity:1,isGhostHover:!1}}function Y({variant:e="default",size:t="md",loading:n=!1,disabled:s=!1,leftIcon:o,trailing:r,iconOnly:i=!1,children:c,style:d,className:h,...m}){const{opacity:x}=Uo({disabled:s??!1,loading:n}),f=s||n,p=Lo[t];return a.jsxs("button",{className:W(Ze.btn,Ze[e],i&&Ze.iconOnly,h),disabled:f,"aria-busy":n||void 0,style:{minHeight:Lt[t],paddingLeft:i?void 0:Ht[t],paddingRight:i?void 0:Ht[t],fontSize:Ho[t],opacity:x,...i?{width:Lt[t]}:{},...d},...m,children:[n?a.jsx(ds,{className:Ze.loadingSpinner,size:p,"aria-hidden":!0}):o?a.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:o}):null,c,r&&!n&&a.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:r})]})}const Ko="_input_ew09y_3",Vo="_textarea_ew09y_32",vt={input:Ko,textarea:Vo},ct=w.forwardRef(function({className:t,...n},s){return a.jsx("input",{ref:s,className:W(vt.input,t),...n})}),df=w.forwardRef(function({className:t,...n},s){return a.jsx("textarea",{ref:s,className:W(vt.input,vt.textarea,t),...n})}),Tn=l().datetime({offset:!0});l().uuid();l().regex(/^[A-Za-z0-9_-]+$/,"expected base64url");const Ue=fn([D(),Tn]),Go=ve(["mobile","browser","cli","mcp"]),Xo=u({type:b("hello"),clientId:l(),clientType:Go,protocolVersion:D(),appVersion:l().optional(),capabilities:fe(l(),A()).optional()}),Yo=u({status:b("server_info"),serverId:l(),hostname:l().optional(),version:l().optional(),capabilities:fe(l(),U()),features:fe(l(),U())}),Jo=u({type:b("status"),payload:Yo}),Qo=u({type:b("ping"),requestId:l(),clientSentAt:Ue.optional()}),Zo=u({type:b("pong"),requestId:l(),clientSentAt:Ue.optional(),serverReceivedAt:Ue,serverSentAt:Ue}),En=ve(["initializing","idle","running","error","closed"]),dt=u({mimeType:l().optional(),data:l().optional()}).passthrough(),er=u({prs:G(U()).optional(),issues:G(U()).optional()}).passthrough(),tr=u({provider:l(),cwd:l(),modeId:l().optional(),model:l().optional(),modelProvider:l().optional(),thinkingOptionId:l().optional(),featureValues:fe(l(),U()).optional(),title:l().nullable().optional(),approvalPolicy:l().optional(),sandboxMode:l().optional(),networkAccess:A().optional(),webSearch:A().optional(),extra:u({pi:U().optional()}).passthrough().optional(),systemPrompt:l().optional(),mcpServers:fe(l(),U()).optional()}),nr=u({type:b("create_agent_request"),requestId:l(),config:tr,env:fe(l(),l()).optional(),workspaceId:l().optional(),worktreeName:l().optional(),initialPrompt:l().optional(),clientMessageId:l().optional(),outputSchema:fe(l(),U()).optional(),images:G(dt).optional(),attachments:er.optional(),git:U().optional(),worktree:U().optional(),autoArchive:A().optional(),labels:fe(l(),l()).default({})}),sr=u({type:b("create_agent_response"),requestId:l(),payload:u({agentId:l()}).passthrough()}),or=u({type:b("agent_update"),agentId:l(),status:En.optional(),title:l().nullable().optional(),labels:fe(l(),l()).optional()}),rr=u({type:b("agent_status"),agentId:l(),status:En}),ar=u({type:b("agent_list"),agents:G(u({id:l()}).passthrough())}),ir=u({type:b("agent_deleted"),agentId:l()}),cr=u({type:b("agent_archived"),agentId:l(),archivedAt:Tn.optional()}),Nn=lt("kind",[u({kind:b("shell"),command:l().optional(),output:l().optional()}),u({kind:b("read"),path:l().optional(),output:l().optional()}),u({kind:b("edit"),path:l().optional(),diff:l().optional(),output:l().optional()}),u({kind:b("write"),path:l().optional(),output:l().optional()}),u({kind:b("search"),query:l().optional(),output:l().optional()}),u({kind:b("fetch"),url:l().optional(),output:l().optional()}),u({kind:b("task"),description:l().optional(),output:l().optional()})]),lr=lt("kind",[u({kind:b("user_message"),messageId:l().optional(),text:l().optional(),images:G(dt).optional()}),u({kind:b("assistant_message"),messageId:l().optional(),text:l().optional()}),u({kind:b("reasoning"),text:l().optional()}),u({kind:b("tool_call"),callId:l().optional(),tool:Nn,status:l().optional()}),u({kind:b("turn_started"),turnId:l().optional()}),u({kind:b("turn_completed"),turnId:l().optional()}),u({kind:b("turn_failed"),turnId:l().optional(),error:l().optional()}),u({kind:b("turn_canceled"),turnId:l().optional()}),u({kind:b("error"),message:l().optional()}),u({kind:b("queue_update"),steering:G(l()).optional(),followUp:G(l()).optional()})]),dr=u({type:b("agent_stream"),agentId:l(),seq:D().optional(),timestamp:Ue.optional(),event:lr}),ur=ve(["before","after"]),fr=u({start:D(),end:D()}),pr=u({type:b("fetch_agent_timeline_request"),requestId:l(),agentId:l(),cursor:l().nullable().optional(),direction:ur,limit:D().optional()}),hr=u({type:b("fetch_agent_timeline_response"),requestId:l(),agentId:l().optional(),items:G(U()),seqStart:D(),seqEnd:D(),sourceSeqRanges:G(fr),collapsed:A(),hasNewer:A(),startCursor:l().nullable().optional(),endCursor:l().nullable().optional()}),mr=u({type:b("agent_permission_request"),requestId:l(),agentId:l(),toolName:l().optional(),tool:Nn.optional(),action:U().optional(),responses:G(l()).optional()}),gr=u({type:b("agent_permission_resolved"),requestId:l(),agentId:l(),decision:l().optional()}),_r=u({type:b("agent.permission.respond.request"),requestId:l(),permissionRequestId:l(),response:U()}),yr=u({type:b("agent.permission.respond.response"),requestId:l(),payload:u({resolved:A()}).passthrough()}),wr=u({type:b("respond_to_permission"),requestId:l(),permissionRequestId:l(),response:U()}),Rn=ve(["conversation","files","both"]),br=u({type:b("agent.rewind.request"),requestId:l(),agentId:l(),messageId:l(),mode:Rn}).passthrough(),xr=u({type:b("agent.rewind.response"),requestId:l(),payload:u({agentId:l(),messageId:l(),mode:Rn,truncatedAt:l().optional()}).passthrough()}).passthrough(),Sr=u({input:D().optional(),output:D().optional(),cacheRead:D().optional(),cacheWrite:D().optional(),total:D().optional()}).passthrough(),vr=u({tokens:D().nullable().optional(),contextWindow:D().optional(),percent:D().nullable().optional()}).passthrough(),kr=u({type:b("agent_session_stats_request"),requestId:l(),agentId:l()}).passthrough(),Ir=u({type:b("agent_session_stats_response"),requestId:l(),payload:u({sessionId:l().optional(),sessionFile:l().optional(),userMessages:D().optional(),assistantMessages:D().optional(),toolCalls:D().optional(),toolResults:D().optional(),totalMessages:D().optional(),tokens:Sr.optional(),cost:D().optional(),contextUsage:vr.optional(),model:l().optional()}).passthrough()}).passthrough(),jr=u({type:b("agent_compact_request"),requestId:l(),agentId:l(),customInstructions:l().optional()}).passthrough(),Cr=u({type:b("agent_compact_response"),requestId:l(),payload:u({summary:l().optional(),firstKeptEntryId:l().optional(),tokensBefore:D().optional(),details:U().optional()}).passthrough()}).passthrough(),Tr=u({type:b("agent_new_session_request"),requestId:l(),agentId:l()}).passthrough(),Er=u({type:b("agent_new_session_response"),requestId:l(),payload:u({cancelled:A()}).passthrough()}).passthrough(),Nr=u({type:b("agent_switch_session_request"),requestId:l(),agentId:l(),sessionPath:l()}).passthrough(),Rr=u({type:b("agent_switch_session_response"),requestId:l(),payload:u({cancelled:A()}).passthrough()}).passthrough(),Mr=u({type:b("agent_fork_request"),requestId:l(),agentId:l(),entryId:l()}).passthrough(),qr=u({type:b("agent_fork_response"),requestId:l(),payload:u({text:l(),cancelled:A()}).passthrough()}).passthrough(),Br=u({type:b("agent_fork_messages_request"),requestId:l(),agentId:l()}).passthrough(),$r=u({type:b("agent_fork_messages_response"),requestId:l(),payload:u({messages:G(u({entryId:l(),text:l()}).passthrough())}).passthrough()}).passthrough(),Dr=u({type:b("agent_clone_request"),requestId:l(),agentId:l()}).passthrough(),Ar=u({type:b("agent_clone_response"),requestId:l(),payload:u({cancelled:A()}).passthrough()}).passthrough(),Pr=u({type:b("agent_set_session_name_request"),requestId:l(),agentId:l(),name:l()}).passthrough(),Or=u({type:b("agent_set_session_name_response"),requestId:l(),payload:u({}).passthrough().optional()}).passthrough(),Fr=u({type:b("agent_export_html_request"),requestId:l(),agentId:l(),outputPath:l().optional()}).passthrough(),zr=u({type:b("agent_export_html_response"),requestId:l(),payload:u({path:l()}).passthrough()}).passthrough(),Wr=u({type:b("agent_set_model_request"),requestId:l(),agentId:l(),provider:l(),modelId:l()}).passthrough(),Lr=u({type:b("agent_set_model_response"),requestId:l(),payload:u({}).passthrough()}).passthrough(),Hr=u({type:b("agent_cycle_model_request"),requestId:l(),agentId:l()}).passthrough(),Ur=u({type:b("agent_cycle_model_response"),requestId:l(),payload:u({model:U().nullable().optional(),thinkingLevel:l().optional(),isScoped:A().optional()}).passthrough()}).passthrough(),Kr=u({type:b("agent_last_assistant_text_request"),requestId:l(),agentId:l()}).passthrough(),Vr=u({type:b("agent_last_assistant_text_response"),requestId:l(),payload:u({text:l().nullable()}).passthrough()}).passthrough(),Gr=u({type:b("steer_agent_request"),requestId:l(),agentId:l(),message:l(),images:G(dt).optional(),clientMessageId:l().optional()}).passthrough(),Xr=u({type:b("steer_agent_response"),requestId:l(),agentId:l(),ok:A()}).passthrough(),Yr=u({type:b("follow_up_agent_request"),requestId:l(),agentId:l(),message:l(),images:G(dt).optional(),clientMessageId:l().optional()}).passthrough(),Jr=u({type:b("follow_up_agent_response"),requestId:l(),agentId:l(),ok:A()}).passthrough(),Qr=u({name:l(),id:l().optional(),description:l().optional(),source:ve(["extension","prompt","skill"]).optional(),scope:ve(["user","project","temporary"]).optional(),path:l().optional()}).passthrough(),Zr=u({type:b("agent_list_commands_request"),requestId:l(),agentId:l()}).passthrough(),ea=u({type:b("agent_list_commands_response"),requestId:l(),payload:u({commands:G(Qr)}).passthrough()}).passthrough(),ta=u({type:b("rpc_error"),requestId:l(),code:l().optional(),message:l().optional(),error:l().optional()}),na=lt("type",[nr,sr,or,rr,ar,ir,cr,dr,pr,hr,mr,gr,_r,yr,wr,br,xr,kr,Ir,jr,Cr,Tr,Er,Nr,Rr,Mr,qr,Br,$r,Dr,Ar,Pr,Or,Fr,zr,Wr,Lr,Hr,Ur,Kr,Vr,Gr,Xr,Yr,Jr,Zr,ea,ta]),sa=u({type:l()}).passthrough(),oa=u({type:b("session"),message:fn([na,sa])});lt("type",[Xo,Jo,Qo,Zo,oa]);const ra={inline_image_markdown:"inline_image_markdown"},Ie={Output:1,Input:2,Resize:3,Snapshot:4,Restore:5},aa=Object.fromEntries(Object.entries(Ie).map(([e,t])=>[t,e])),Mn=u({rows:D().int().nonnegative(),cols:D().int().nonnegative()});class We extends Error{constructor(t){super(t),this.name="TerminalFrameError"}}const ia=new TextEncoder,ca=new TextDecoder;function la(e){if(!Number.isInteger(e)||e<0||e>255)throw new We(`slot must be an integer 0–255, got ${e}`)}function Oe(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function uf(e){switch(la(e.slot),e.opcode){case"Output":return Oe(Ie.Output,e.slot,e.data);case"Input":return Oe(Ie.Input,e.slot,e.data);case"Snapshot":return Oe(Ie.Snapshot,e.slot,e.data);case"Restore":return Oe(Ie.Restore,e.slot,e.data);case"Resize":{const t=JSON.stringify(Mn.parse({rows:e.rows,cols:e.cols}));return Oe(Ie.Resize,e.slot,ia.encode(t))}}}function da(e){if(e.length<2)throw new We(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=aa[t];if(!s)throw new We(`unknown terminal opcode 0x${t.toString(16)}`);const o=e.subarray(2);if(s==="Resize"){let r;try{r=JSON.parse(ca.decode(o))}catch{throw new We("resize payload is not valid JSON")}const i=Mn.safeParse(r);if(!i.success)throw new We("resize payload is not { rows, cols }");return{opcode:"Resize",slot:n,rows:i.data.rows,cols:i.data.cols}}return{opcode:s,slot:n,data:o.slice()}}const Te={Begin:16,Chunk:17,End:18,Error:19},ua=Object.fromEntries(Object.entries(Te).map(([e,t])=>[t,e])),qn=u({transferId:l(),fileName:l().optional(),mimeType:l().optional(),totalBytes:D().int().nonnegative().optional()});class Le extends Error{constructor(t){super(t),this.name="FileTransferFrameError"}}const Ut=new TextEncoder,Kt=new TextDecoder;function fa(e){if(!Number.isInteger(e)||e<0||e>255)throw new Le(`stream must be an integer 0–255, got ${e}`)}function et(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function ht(e){switch(fa(e.stream),e.opcode){case"Begin":return et(Te.Begin,e.stream,Ut.encode(JSON.stringify(qn.parse(e.meta))));case"Chunk":return et(Te.Chunk,e.stream,e.data);case"End":return et(Te.End,e.stream,new Uint8Array([e.ok?1:0]));case"Error":return et(Te.Error,e.stream,Ut.encode(e.message))}}function pa(e){if(e.length<2)throw new Le(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=ua[t];if(!s)throw new Le(`unknown file-transfer opcode 0x${t.toString(16)}`);const o=e.subarray(2);switch(s){case"Begin":{let r;try{r=JSON.parse(Kt.decode(o))}catch{throw new Le("begin payload is not valid JSON")}const i=qn.safeParse(r);if(!i.success)throw new Le("begin payload is not a valid transfer header");return{opcode:"Begin",stream:n,meta:i.data}}case"Chunk":return{opcode:"Chunk",stream:n,data:o.slice()};case"End":return{opcode:"End",stream:n,ok:(o[0]??1)!==0};case"Error":return{opcode:"Error",stream:n,message:Kt.decode(o)}}}function ha(e){try{return pa(e)}catch{return null}}const je=256;function ma(e,t=0){const n=(t%je+je)%je;for(let s=0;s<je;s++){const o=(n+s)%je;if(!e.has(o))return o}return null}const ga=l().regex(/^[a-z][a-z0-9-]*$/,"invalid provider id"),_a=ve(["safe","moderate","dangerous","planning"]),ya=u({supportsStreaming:A(),supportsSessionPersistence:A(),supportsDynamicModes:A(),supportsMcpServers:A(),supportsReasoningStream:A(),supportsToolInvocations:A(),supportsRewindConversation:A().optional(),supportsRewindFiles:A().optional(),supportsRewindBoth:A().optional(),supportsSteering:A().optional()}).passthrough(),wa=u({id:l(),label:l().optional(),description:l().optional(),icon:l().optional(),colorTier:_a});u({id:ga,label:l(),description:l().optional(),extends:l().optional(),modes:G(wa),capabilities:ya});function kt(e){return typeof e=="string"?e:e instanceof Uint8Array||Buffer.isBuffer(e)?e.toString("utf8"):String(e??"")}function Bn(e){let t=null;const n={onMessage:null,onClose:null,onError:null,get isOpen(){return t!==null&&t.readyState===1},connect(s){return new Promise((o,r)=>{const i=e??(()=>new WebSocket(s));try{t=e?i(s):new WebSocket(s),t.binaryType="arraybuffer"}catch(c){r(c);return}t.onopen=()=>o(),t.onerror=c=>{var d;(t==null?void 0:t.readyState)!==1&&r(c),(d=n.onError)==null||d.call(n,c)},t.onclose=c=>{var d;(d=n.onClose)==null||d.call(n,c.code,kt(c.reason))},t.onmessage=c=>{var h,m,x,f;const{data:d}=c;d instanceof ArrayBuffer||d instanceof Uint8Array?(h=n.onMessage)==null||h.call(n,d):typeof d=="string"?(m=n.onMessage)==null||m.call(n,d):typeof Blob<"u"&&d instanceof Blob?(x=n.onMessage)==null||x.call(n,d):Buffer.isBuffer(d)&&((f=n.onMessage)==null||f.call(n,d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength)))}})},sendText(s){t==null||t.send(s)},sendBinary(s){t==null||t.send(s)},close(s=1e3,o=""){t==null||t.close(s,o),t=null}};return n}const He="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function $n(e){let t="";for(let n=0;n<e.length;n+=3){const s=e[n],o=n+1<e.length,r=n+2<e.length,i=o?e[n+1]:0,c=r?e[n+2]:0;t+=He[s>>2],t+=He[(s&3)<<4|i>>4],t+=o?He[(i&15)<<2|c>>6]:"=",t+=r?He[c&63]:"="}return t}function Dn(e){const t=e.replace(/=+$/,""),n=[];let s=0,o=0;for(const r of t){const i=He.indexOf(r);if(i===-1)throw new Error(`invalid base64 character: ${JSON.stringify(r)}`);s=s<<6|i,o+=6,o>=8&&(o-=8,n.push(s>>o&255))}return new Uint8Array(n)}function ba(e){try{const t=JSON.parse(e);return!t||typeof t.type!="string"?null:t}catch{return null}}const ot=24;function An(e,t){const n=Ee.randomBytes(ot),s=Ee.box.after(e,n,t),o=new Uint8Array(n.length+s.length);return o.set(n,0),o.set(s,n.length),$n(o)}function Pn(e,t){let n;try{n=Dn(e)}catch{return null}if(n.length<ot)return null;const s=n.slice(0,ot),o=n.slice(ot);return Ee.box.open.after(o,s,t)}function xa(e,t){return An(new TextEncoder().encode(e),t)}function Sa(e,t){const n=Pn(e,t);return n?new TextDecoder().decode(n):null}function va(e,t,n,s,o,r){let i=!1;return n.onClose(c=>{var d;i=!0,(d=s.onClose)==null||d.call(s,c)}),{handleAppFrame(c){var m,x;if(i)return;const d=o();if(!r()||!d)return;const h=Sa(c.frame,d);if(h===null){(m=s.onAuthError)==null||m.call(s,new Error(`relay ${e} channel: message failed authentication`));return}(x=s.onMessage)==null||x.call(s,h)},handleBinaryFrame(c){var m,x;if(i)return;const d=o();if(!r()||!d)return;const h=Pn(c.frame,d);if(h===null){(m=s.onAuthError)==null||m.call(s,new Error(`relay ${e} channel: binary message failed authentication`));return}(x=s.onBinaryMessage)==null||x.call(s,h)},send(c){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_app",frame:xa(c,d)}))},sendBinary(c){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_bin",frame:An(c,d)}))},close(){i||(i=!0,n.close())}}}function ka(e){const{transport:t,attachment:n,daemonPublicKey:s}=e,o=e.events??{},r=Ee.box.keyPair(),i=Ee.box.before(s,r.secretKey);let c=!1;const d=va("client",n,t,o,()=>i,()=>c);return t.onMessage(h=>{var x;const m=ba(h);if(m){if(m.type==="e2ee_ready"){if(c)return;c=!0,(x=o.onReady)==null||x.call(o);return}if(m.type==="e2ee_app"){d.handleAppFrame(m);return}m.type==="e2ee_bin"&&d.handleBinaryFrame(m)}}),t.send(JSON.stringify({type:"e2ee_hello",ephemeralPublicKey:$n(r.publicKey)})),{role:"client",attachment:n,get ready(){return c},send:d.send,sendBinary:d.sendBinary,close:d.close}}const Ia=16;function ja(e){const t=Ee.hash(e);let n="";for(let s=0;s<Ia;s++)n+=t[s].toString(16).padStart(2,"0");return n}function Ca(e){const t=e.useTls?"wss":"ws",n=e.endpoint.replace(/^(?:https?|wss?):\/\//,"").replace(/\/+$/,"");return`${t}://${n}`}function Ta(e){let t=null,n=null;const s=e.sessionId??ja(e.daemonPublicKey),o={onMessage:null,onClose:null,onError:null,get isOpen(){return t!==null&&t.readyState===1&&n!==null&&n.ready},connect(r){return new Promise((i,c)=>{const d=e.factory??(()=>new WebSocket(r));try{t=e.factory?d(r):new WebSocket(r)}catch(f){c(f);return}const h=t,m=[],x=[];h.onopen=()=>{h.send(JSON.stringify({type:"relay_register",sessionId:s})),n=ka({transport:{send:f=>h.send(f),onMessage:f=>m.push(f),onClose:f=>x.push(f),close:()=>h.close()},attachment:{sessionId:s},daemonPublicKey:e.daemonPublicKey,events:{onReady:()=>i(),onMessage:f=>{var p;return(p=o.onMessage)==null?void 0:p.call(o,f)},onBinaryMessage:f=>{var p;return(p=o.onMessage)==null?void 0:p.call(o,f.slice().buffer)},onAuthError:f=>{var p;return(p=o.onError)==null?void 0:p.call(o,f)}}})},h.onerror=f=>{var p;h.readyState!==1&&c(f),(p=o.onError)==null||p.call(o,f)},h.onclose=f=>{var p;for(const v of x)v(kt(f.reason));(p=o.onClose)==null||p.call(o,f.code,kt(f.reason))},h.onmessage=f=>{const{data:p}=f;if(typeof p=="string")for(const v of m)v(p)}})},sendText(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.send(r)},sendBinary(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.sendBinary(r)},close(r=1e3,i=""){n==null||n.close(),n=null,t==null||t.close(r,i),t=null}};return o}function Ea(e){const t=e.indexOf("#"),n=t===-1?e:e.slice(t+1),s=new URLSearchParams(n),o=s.get("offer");if(!o)return null;let r;try{r=Dn(o)}catch{return null}const i=s.get("relay");if(i){const d={endpoint:i,useTls:s.get("relayTls")==="1"};return{publicKeyB64:o,publicKey:r,relay:d}}const c=s.get("host")??void 0;return{publicKeyB64:o,publicKey:r,...c?{host:c}:{}}}const Na=1;function It(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}class Ra extends Error{constructor(t,n,s){super(t),this.requestId=n,this.code=s,this.name="RpcError"}}class Vt extends Error{constructor(t){super(`RPC ${t} timed out`),this.requestId=t,this.name="RpcTimeoutError"}}class Ma{constructor(t){N(this,"transport");N(this,"rpcTimeoutMs");N(this,"now");N(this,"_state","idle");N(this,"_serverId",null);N(this,"_features",{});N(this,"_serverCapabilities",{});N(this,"pending",new Map);N(this,"sessionHandlers",new Set);N(this,"terminalHandlers",new Set);N(this,"fileTransferHandlers",new Set);N(this,"stateHandlers",new Set);N(this,"helloResolve",null);N(this,"helloReject",null);this.options=t,this.transport=t.transport??Bn(),this.rpcTimeoutMs=t.rpcTimeoutMs??3e4,this.now=t.now??(()=>Date.now()),this.transport.onMessage=n=>this.handleIncoming(n),this.transport.onClose=(n,s)=>this.handleClose(n,s),this.transport.onError=()=>{}}get state(){return this._state}get serverId(){return this._serverId}get features(){return this._features}get serverCapabilities(){return this._serverCapabilities}hasFeature(t){return!!this._features[t]}async connect(){this.setState("connecting"),await this.transport.connect(this.options.url);const t=new Promise((s,o)=>{this.helloResolve=s,this.helloReject=o});this.transport.sendText(JSON.stringify({type:"hello",clientId:this.options.clientId,clientType:this.options.clientType,protocolVersion:this.options.protocolVersion??Na,appVersion:this.options.appVersion,capabilities:this.options.capabilities}));const n=await t;return this._serverId=n.serverId,this._features=n.features,this._serverCapabilities=n.capabilities,this.setState("open"),n}close(t=1e3,n=""){this.setState("closing"),this.transport.close(t,n)}request(t,n={},s){const o=n.requestId??It();return new Promise((r,i)=>{const c=s??this.rpcTimeoutMs,d=c>0?setTimeout(()=>{this.pending.delete(o),i(new Vt(o))},c):null;this.pending.set(o,{resolve:h=>r(h),reject:i,timer:d}),this.sendSession({type:t,...n,requestId:o})})}sendSession(t){this.transport.sendText(JSON.stringify({type:"session",message:t}))}sendBinary(t){this.transport.sendBinary(t)}ping(t=1e4){const n=It();return new Promise((s,o)=>{const r=t>0?setTimeout(()=>{this.pending.delete(n),o(new Vt(n))},t):null;this.pending.set(n,{resolve:()=>s(),reject:o,timer:r}),this.transport.sendText(JSON.stringify({type:"ping",requestId:n,clientSentAt:this.now()}))})}onSessionMessage(t){return this.sessionHandlers.add(t),()=>this.sessionHandlers.delete(t)}onTerminalFrame(t){return this.terminalHandlers.add(t),()=>this.terminalHandlers.delete(t)}onFileTransferFrame(t){return this.fileTransferHandlers.add(t),()=>this.fileTransferHandlers.delete(t)}onStateChange(t){return this.stateHandlers.add(t),()=>this.stateHandlers.delete(t)}setState(t){if(this._state!==t){this._state=t;for(const n of this.stateHandlers)n(t)}}handleClose(t,n){this.helloReject&&(this.helloReject(new Error(`socket closed during handshake: ${n}`)),this.helloResolve=null,this.helloReject=null);for(const[,s]of this.pending)s.timer&&clearTimeout(s.timer),s.reject(new Error(`socket closed: ${n}`));this.pending.clear(),this.setState("closed")}handleIncoming(t){if(typeof t=="string"){this.handleTextFrame(t);return}if(t instanceof ArrayBuffer){this.handleBinaryFrame(new Uint8Array(t));return}typeof t.arrayBuffer=="function"&&t.arrayBuffer().then(n=>this.handleBinaryFrame(new Uint8Array(n)))}handleBinaryFrame(t){const n=t[0];if(n!==void 0&&Object.values(Te).includes(n)){const r=ha(t);if(!r)return;for(const i of this.fileTransferHandlers)i(r);return}const o=da(t);for(const r of this.terminalHandlers)r(o)}handleTextFrame(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;switch(s.type){case"status":this.handleStatus(s);return;case"pong":this.resolvePending(s.requestId,void 0);return;case"ping":this.transport.sendText(JSON.stringify({type:"pong",requestId:s.requestId,serverReceivedAt:this.now(),serverSentAt:this.now()}));return;case"session":this.handleSession(s.message);return;default:return}}handleStatus(t){const n=t.payload;(n==null?void 0:n.status)==="server_info"&&this.helloResolve&&(this.helloResolve(n),this.helloResolve=null,this.helloReject=null)}handleSession(t){if(!t||typeof t!="object")return;const n=t;if(n.type==="rpc_error"&&typeof n.requestId=="string"){const s=this.pending.get(n.requestId);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(n.requestId),s.reject(new Ra(n.message??n.error??"RPC failed",n.requestId,n.code)));return}if(typeof n.requestId=="string"&&this.pending.has(n.requestId)){const s="payload"in n?n.payload:n;this.resolvePending(n.requestId,s)}for(const s of this.sessionHandlers)s(t)}resolvePending(t,n){const s=this.pending.get(t);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(t),s.resolve(n))}}class qa{constructor(t){this.daemon=t}get connection(){return this.daemon}async createAgent(t){return await this.daemon.request("create_agent_request",{...t})}agent(t){return new $a(this.daemon,t)}workspace(t){return new Da(this.daemon,t)}get providers(){return new Aa(this.daemon)}onAgentUpdate(t){return this.daemon.onSessionMessage(n=>{n.type==="agent_update"&&t(n)})}onWorkspaceUpdate(t){return this.daemon.onSessionMessage(n=>{n.type==="workspace_update"&&t(n)})}}class Ba{constructor(t,n){this.daemon=t,this.agentId=n}fetch(t={}){return this.daemon.request("fetch_agent_timeline_request",{agentId:this.agentId,cursor:t.cursor,direction:t.direction,limit:t.limit})}subscribe(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_stream"&&s.agentId===this.agentId&&s.event&&t(s.event)})}}class $a{constructor(t,n){N(this,"timeline");this.daemon=t,this.agentId=n,this.timeline=new Ba(t,n)}send(t,n={}){return this.daemon.request("send_agent_prompt",{agentId:this.agentId,prompt:t,clientMessageId:n.clientMessageId,images:n.images})}run(t,n){return this.send(t,n)}interrupt(){return this.daemon.request("interrupt_agent",{agentId:this.agentId})}steer(t,n={}){return this.daemon.request("steer_agent_request",{agentId:this.agentId,message:t,clientMessageId:n.clientMessageId,images:n.images})}followUp(t,n={}){return this.daemon.request("follow_up_agent_request",{agentId:this.agentId,message:t,clientMessageId:n.clientMessageId,images:n.images})}update(t){return this.daemon.request("update_agent",{agentId:this.agentId,...t})}resume(){return this.daemon.request("resume_agent",{agentId:this.agentId})}archive(){return this.daemon.request("archive_agent",{agentId:this.agentId})}delete(){return this.daemon.request("delete_agent",{agentId:this.agentId})}onUpdate(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_update"&&s.agentId===this.agentId&&t(s)})}sessionStats(){return this.daemon.request("agent_session_stats_request",{agentId:this.agentId})}compact(t){return this.daemon.request("agent_compact_request",{agentId:this.agentId,customInstructions:t})}newSession(){return this.daemon.request("agent_new_session_request",{agentId:this.agentId})}switchSession(t){return this.daemon.request("agent_switch_session_request",{agentId:this.agentId,sessionPath:t})}fork(t){return this.daemon.request("agent_fork_request",{agentId:this.agentId,entryId:t})}forkMessages(){return this.daemon.request("agent_fork_messages_request",{agentId:this.agentId})}clone(){return this.daemon.request("agent_clone_request",{agentId:this.agentId})}setSessionName(t){return this.daemon.request("agent_set_session_name_request",{agentId:this.agentId,name:t})}exportHtml(t){return this.daemon.request("agent_export_html_request",{agentId:this.agentId,outputPath:t})}setModel(t,n){return this.daemon.request("agent_set_model_request",{agentId:this.agentId,provider:t,modelId:n})}cycleModel(){return this.daemon.request("agent_cycle_model_request",{agentId:this.agentId})}lastAssistantText(){return this.daemon.request("agent_last_assistant_text_request",{agentId:this.agentId})}listCommands(){return this.daemon.request("agent_list_commands_request",{agentId:this.agentId})}}class Da{constructor(t,n){this.daemon=t,this.workspaceId=n}onUpdate(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="workspace_update"&&s.workspaceId===this.workspaceId&&t(s)})}}class Aa{constructor(t){this.daemon=t}listProviders(){return this.daemon.request("list_providers",{})}listModels(t){return this.daemon.request("list_provider_models",{provider:t})}listModes(t){return this.daemon.request("list_provider_modes",{provider:t})}resolveDefaultModel(t,n){return this.daemon.request("resolve_default_model",{provider:t,...n?{cwd:n}:{}})}refreshSnapshot(){return this.daemon.request("providers.snapshot.refresh.request",{})}}const Gt=32*1024,Pa="invalid_or_expired_token";function Oa(e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}class Fa{constructor(t){N(this,"pending",new Map);N(this,"streamCursor",1);N(this,"detach",null);this.daemon=t}start(){this.detach||(this.detach=this.daemon.onFileTransferFrame(t=>this.dispatch(t)))}stop(){var t;(t=this.detach)==null||t.call(this),this.detach=null;for(const[n,s]of this.pending)s.reject(new Error("file transfer router stopped")),this.pending.delete(n)}async download(t){try{return await this.attemptDownload(t)}catch(n){if(!(n instanceof Error)||n.message!==Pa)throw n;return await this.attemptDownload(t)}}async attemptDownload(t){const n=await this.daemon.request("file_download_token_request",{path:t});if(!n.ok||!n.token)throw new Error(n.error??"failed to issue download token");const s=ma(this.pending,this.streamCursor);if(s===null)throw new Error("no free download stream");this.streamCursor=(s+1)%je;const o=new Promise((i,c)=>{this.pending.set(s,{chunks:[],meta:{},resolve:i,reject:c})});let r;try{r=await this.daemon.request("file_download_request",{token:n.token,stream:s})}catch(i){throw this.pending.delete(s),i}if(!r.ok)throw this.pending.delete(s),new Error(r.error??"download request failed");return o}async upload(t,n){const s=It(),o=await this.daemon.request("file_upload_request",{path:t,transferId:s});if(!o.ok||o.stream===void 0)throw new Error(o.error??"upload request failed");const r=o.stream;this.daemon.sendBinary(ht({opcode:"Begin",stream:r,meta:{transferId:s}}));for(let i=0;i<n.length;i+=Gt){const c=n.subarray(i,i+Gt);this.daemon.sendBinary(ht({opcode:"Chunk",stream:r,data:c}))}this.daemon.sendBinary(ht({opcode:"End",stream:r,ok:!0}))}dispatch(t){const n=this.pending.get(t.stream);if(n)switch(t.opcode){case"Begin":n.meta.fileName=t.meta.fileName,n.meta.mimeType=t.meta.mimeType;return;case"Chunk":n.chunks.push(t.data);return;case"End":this.pending.delete(t.stream),t.ok?n.resolve({bytes:Oa(n.chunks),...n.meta}):n.reject(new Error("download failed"));return;case"Error":this.pending.delete(t.stream),n.reject(new Error(t.message));return}}}class za{constructor(t,n={}){N(this,"initialDelayMs");N(this,"maxDelayMs");N(this,"factor");N(this,"jitter");N(this,"maxAttempts");N(this,"setTimer");N(this,"clearTimer");N(this,"random");N(this,"attempt",0);N(this,"timer",null);N(this,"active",!1);N(this,"detachState",null);N(this,"reconnectedHandlers",new Set);N(this,"failedHandlers",new Set);this.daemon=t,this.initialDelayMs=n.initialDelayMs??500,this.maxDelayMs=n.maxDelayMs??3e4,this.factor=n.factor??2,this.jitter=n.jitter??.2,this.maxAttempts=n.maxAttempts??Number.POSITIVE_INFINITY,this.setTimer=n.setTimer??((s,o)=>setTimeout(s,o)),this.clearTimer=n.clearTimer??(s=>clearTimeout(s)),this.random=n.random??Math.random}delayForAttempt(t){const n=Math.min(this.maxDelayMs,this.initialDelayMs*this.factor**(t-1)),s=n*this.jitter*(this.random()*2-1);return Math.max(0,Math.round(n+s))}onReconnected(t){return this.reconnectedHandlers.add(t),()=>this.reconnectedHandlers.delete(t)}onReconnectFailed(t){return this.failedHandlers.add(t),()=>this.failedHandlers.delete(t)}start(){this.active||(this.active=!0,this.detachState=this.daemon.onStateChange(t=>{t==="closed"&&this.active&&this.scheduleReconnect(),t==="open"&&(this.attempt=0)}))}stop(){var t;this.active=!1,this.timer&&this.clearTimer(this.timer),this.timer=null,(t=this.detachState)==null||t.call(this),this.detachState=null}get attemptCount(){return this.attempt}scheduleReconnect(){if(!this.active||this.attempt>=this.maxAttempts)return;this.attempt+=1;const t=this.delayForAttempt(this.attempt);this.timer=this.setTimer(()=>{this.timer=null,this.tryReconnect()},t)}async tryReconnect(){if(!this.active)return;const t=this.attempt;try{await this.daemon.connect();for(const n of this.reconnectedHandlers)n({attempt:t,serverId:this.daemon.serverId})}catch(n){for(const s of this.failedHandlers)s(n,t);this.scheduleReconnect()}}}function Xt(e){const t=e.trim();if(t==="")return t;const n=t.match(/^([a-z][a-z0-9+.-]*):\/\//i);if(!n)return`ws://${t.replace(/\/+$/,"")}`;const s=n[1].toLowerCase(),o=t.slice(n[0].length).replace(/\/+$/,"");switch(s){case"http":return`ws://${o}`;case"https":return`wss://${o}`;case"ws":case"wss":return`${s}://${o}`;default:return t}}function Wa(e){const t=Ea(e);return t!=null&&t.relay?{mode:"relay",url:Ca(t.relay),daemonPublicKey:t.publicKey}:t!=null&&t.host?{mode:"direct",url:Xt(t.host)}:{mode:"direct",url:Xt(e)}}const La=32,J=new Map;function Ha(){for(;J.size>La;){let e=null;for(const[t,n]of J)if(n.refs===0&&n.entry){URL.revokeObjectURL(n.entry.objectUrl),e=t;break}if(e===null)return;J.delete(e)}}function ff(e,t){const n=J.get(e);if(n)return n.refs+=1,J.delete(e),J.set(e,n),n.entry?Promise.resolve(n.entry):n.pending;const s={refs:1,entry:null,pending:null};return J.set(e,s),Ha(),s.pending=t(e).then(o=>{const r=new Blob([Uint8Array.from(o.bytes)],{type:o.mimeType||"application/octet-stream"}),i={objectUrl:URL.createObjectURL(r),mimeType:o.mimeType};return J.get(e)===s?(s.entry=i,s.pending=null):URL.revokeObjectURL(i.objectUrl),i}).catch(o=>{throw J.get(e)===s&&J.delete(e),o}),s.pending}function pf(e){const t=J.get(e);t&&(t.refs=Math.max(0,t.refs-1))}function Ua(){for(const e of J.values())e.entry&&URL.revokeObjectURL(e.entry.objectUrl);J.clear()}function Ka(){return"web-"+Math.random().toString(36).slice(2,10)}const M=ke()((e,t)=>({status:"idle",serverInfo:null,error:null,daemon:null,client:null,reconnection:null,async connect(n){t().disconnect();const s=Wa(n.url);let o;s.mode==="relay"?o=Ta({daemonPublicKey:s.daemonPublicKey}):n.password&&(o=Bn(d=>new WebSocket(d,[`pi-studio.bearer.${n.password}`])));const r=new Ma({url:s.url,clientId:n.clientId??Ka(),clientType:"browser",capabilities:{[ra.inline_image_markdown]:!0},transport:o,rpcTimeoutMs:1800*1e3}),i=new qa(r),c=new za(r);r.onStateChange(d=>e({status:d})),c.onReconnected(()=>e({error:null})),c.onReconnectFailed(d=>{e({error:d instanceof Error?d.message:String(d)})}),e({daemon:r,client:i,reconnection:c,error:null,status:"connecting"});try{const d=await r.connect();e({serverInfo:d}),c.start()}catch(d){throw e({error:d instanceof Error?d.message:String(d)}),d}},disconnect(){const{daemon:n,reconnection:s}=t();s==null||s.stop(),n==null||n.close(),Ua(),e({status:"idle",serverInfo:null,daemon:null,client:null,reconnection:null})}})),Va=100,Ga=480,Xa=220,Ya=280;function tt(e){return Math.min(Ga,Math.max(Va,e))}const j=ke()(e=>({host:"ws://127.0.0.1:6767",password:"",cwd:"~",cwdPickerOpen:!1,sessionMenu:null,workspaceMenu:null,fileMenu:null,rightSidebarTab:"files",collapsedWorkspaces:new Set,leftSidebarCollapsed:!1,rightSidebarCollapsed:!1,leftSidebarWidth:Xa,rightSidebarWidth:Ya,setHost:t=>e({host:t}),setPassword:t=>e({password:t}),setCwd:t=>e({cwd:t}),openCwdPicker:()=>e({cwdPickerOpen:!0}),closeCwdPicker:()=>e({cwdPickerOpen:!1}),openSessionMenu:(t,n,s)=>e({sessionMenu:{sessionId:t,x:n,y:s}}),closeSessionMenu:()=>e({sessionMenu:null}),openWorkspaceMenu:(t,n,s)=>e({workspaceMenu:{cwd:t,x:n,y:s}}),closeWorkspaceMenu:()=>e({workspaceMenu:null}),openFileMenu:(t,n,s,o,r)=>e({fileMenu:{path:t,isDirectory:n,x:s,y:o,background:r}}),closeFileMenu:()=>e({fileMenu:null}),setRightSidebarTab:t=>e({rightSidebarTab:t}),toggleWorkspaceCollapsed:t=>e(n=>{const s=new Set(n.collapsedWorkspaces);return s.has(t)?s.delete(t):s.add(t),{collapsedWorkspaces:s}}),setCollapsedWorkspaces:t=>e({collapsedWorkspaces:t}),toggleLeftSidebar:()=>e(t=>({leftSidebarCollapsed:!t.leftSidebarCollapsed})),toggleRightSidebar:()=>e(t=>({rightSidebarCollapsed:!t.rightSidebarCollapsed})),setLeftSidebarWidth:t=>e({leftSidebarWidth:tt(t)}),setRightSidebarWidth:t=>e({rightSidebarWidth:tt(t)}),resizeLeftSidebar:t=>e(n=>({leftSidebarWidth:tt(n.leftSidebarWidth+t)})),resizeRightSidebar:t=>e(n=>({rightSidebarWidth:tt(n.rightSidebarWidth+t)}))})),Ja="_wrap_1jr5f_1",Qa="_dot_1jr5f_8",Za="_open_1jr5f_15",ei="_connecting_1jr5f_18",ti="_closed_1jr5f_21",ni="_idle_1jr5f_22",si="_closing_1jr5f_23",mt={wrap:Ja,dot:Qa,open:Za,connecting:ei,closed:ti,idle:ni,closing:si},oi={idle:"disconnected",connecting:"connecting…",open:"connected",closing:"disconnecting…",closed:"disconnected"};function ri(){const e=M(n=>n.status),t=M(n=>n.error);return a.jsxs("span",{className:mt.wrap,title:t??void 0,children:[a.jsx("span",{className:W(mt.dot,mt[e])}),oi[e]??e]})}const ai="_toolbar_1oxtj_1",ii="_brand_1oxtj_10",ci="_version_1oxtj_16",li="_sep_1oxtj_22",di="_host_1oxtj_28",ui="_password_1oxtj_31",fi="_sidebarToggles_1oxtj_34",we={toolbar:ai,brand:ii,version:ci,sep:li,host:di,password:ui,sidebarToggles:fi};function pi(){const e=M(f=>f.status),t=M(f=>f.connect),n=M(f=>f.disconnect),s=j(f=>f.host),o=j(f=>f.setHost),r=j(f=>f.password),i=j(f=>f.setPassword),c=j(f=>f.leftSidebarCollapsed),d=j(f=>f.toggleLeftSidebar),h=j(f=>f.rightSidebarCollapsed),m=j(f=>f.toggleRightSidebar),x=e==="open"||e==="connecting";return a.jsxs("div",{className:we.toolbar,children:[a.jsx("span",{className:we.brand,children:"Pi-Studio"}),a.jsxs("span",{className:we.version,children:["v","0.0.59"]}),a.jsx(ri,{}),a.jsx("div",{className:we.sep}),a.jsx(ct,{className:we.host,value:s,onChange:f=>o(f.target.value),placeholder:"host:port, ws://…/http://…, or a pasted pairing link",disabled:x}),a.jsx(ct,{className:we.password,type:"password",value:r,onChange:f=>i(f.target.value),placeholder:"password",disabled:x}),e==="open"||e==="connecting"||e==="closing"?a.jsx(Y,{size:"sm",onClick:()=>n(),children:"Disconnect"}):a.jsx(Y,{size:"sm",variant:"default",onClick:()=>void t({url:s,password:r||void 0}),children:"Connect"}),a.jsxs("div",{className:we.sidebarToggles,children:[a.jsx(Y,{size:"sm",variant:"ghost",iconOnly:!0,title:c?"Show sessions sidebar":"Hide sessions sidebar",onClick:()=>d(),children:c?a.jsx(us,{size:16}):a.jsx(fs,{size:16})}),a.jsx(Y,{size:"sm",variant:"ghost",iconOnly:!0,title:h?"Show files/changes sidebar":"Hide files/changes sidebar",onClick:()=>m(),children:h?a.jsx(ps,{size:16}):a.jsx(hs,{size:16})})]})]})}const jt={rows:[],streamingAssistantIndex:null,streamingReasoningIndex:null,toolIndexByCallId:{}};let Yt=0;function ge(){return Yt+=1,`row-${Yt}`}function hi(e){switch(e.kind){case"shell":return e.command??"";case"read":case"write":return e.path??"";case"edit":return e.path??"";case"search":return e.query??"";case"fetch":return e.url??"";case"task":return e.description??"";default:return""}}function mi(e,t){return e??`${t.kind}:${hi(t)}`}function gi(e){return{...e,streamingAssistantIndex:null,streamingReasoningIndex:null}}function _i(e,t){var r;const n=e.rows.slice();let s=e.streamingAssistantIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="assistant"){const i={kind:"assistant",id:ge(),text:"",streaming:!0};n.push(i),s=n.length-1}const o=n[s];return!o||o.kind!=="assistant"?e:(n[s]={...o,text:o.text+t},{...e,rows:n,streamingAssistantIndex:s,streamingReasoningIndex:null})}function yi(e,t){var r;const n=e.rows.slice();let s=e.streamingReasoningIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="reasoning"){const i={kind:"reasoning",id:ge(),text:"",streaming:!0};n.push(i),s=n.length-1}const o=n[s];return!o||o.kind!=="reasoning"?e:(n[s]={...o,text:o.text+t},{...e,rows:n,streamingReasoningIndex:s,streamingAssistantIndex:null})}function wi(e,t){if(e.kind!==t.kind)return t;const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&o!==""&&(n[s]=o);return n}function bi(e,t){var c;const n=mi(t.callId,t.tool),s=t.status==="completed"||t.status==="error"?t.status:"running",o=e.toolIndexByCallId[n],r=e.rows.slice();if(o!==void 0&&((c=r[o])==null?void 0:c.kind)==="tool"){const d=r[o];return d.kind!=="tool"?e:(r[o]={...d,tool:wi(d.tool,t.tool),status:s},{...e,rows:r,streamingAssistantIndex:null,streamingReasoningIndex:null})}const i={kind:"tool",id:ge(),callId:n,tool:t.tool,status:s};return r.push(i),{...e,rows:r,toolIndexByCallId:{...e.toolIndexByCallId,[n]:r.length-1},streamingAssistantIndex:null,streamingReasoningIndex:null}}function Bt(e){const t=e.rows.slice();if(e.streamingAssistantIndex!==null){const n=t[e.streamingAssistantIndex];(n==null?void 0:n.kind)==="assistant"&&(t[e.streamingAssistantIndex]={...n,streaming:!1})}if(e.streamingReasoningIndex!==null){const n=t[e.streamingReasoningIndex];(n==null?void 0:n.kind)==="reasoning"&&(t[e.streamingReasoningIndex]={...n,streaming:!1})}return{...e,rows:t,streamingAssistantIndex:null,streamingReasoningIndex:null}}function xi(e,t){const n=Bt(e),s={kind:"error",id:ge(),text:t||"turn failed"};return{...n,rows:[...n.rows,s]}}function Si(e){const t=Bt(e),n={kind:"system",id:ge(),text:"(canceled)"};return{...t,rows:[...t.rows,n]}}function vi(e,t){const n={kind:"error",id:ge(),text:t||"error"};return{...e,rows:[...e.rows,n]}}function ki(e,t,n,s){if(s!==void 0){const r=e.rows.findIndex(i=>i.kind==="user"&&i.pending&&i.clientMessageId===s);if(r!==-1){const i=e.rows.slice(),c=i[r];if((c==null?void 0:c.kind)==="user")return i[r]={...c,text:t,images:n,pending:!1},{...e,rows:i}}}const o={kind:"user",id:ge(),text:t,images:n,clientMessageId:s};return{...e,rows:[...e.rows,o]}}function Ii(e,t){let n=!1;const s=e.rows.map(o=>o.kind!=="user"||!o.queued||t.includes(o.text)?o:(n=!0,{...o,queued:!1}));return n?{...e,rows:s}:e}function On(e,t){switch(t.kind){case"turn_started":return gi(e);case"user_message":return ki(e,t.text??"",t.images,t.messageId);case"assistant_message":return _i(e,t.text??"");case"reasoning":return yi(e,t.text??"");case"tool_call":return bi(e,t);case"turn_completed":return Bt(e);case"turn_failed":return xi(e,t.error);case"turn_canceled":return Si(e);case"error":return vi(e,t.message);case"queue_update":return Ii(e,t.steering??[]);default:return e}}function ji(e,t,n,s,o){const r={kind:"user",id:ge(),text:n,images:s,clientMessageId:t,pending:!0,queued:o};return{...e,rows:[...e.rows,r]}}function Ci(e,t){const n=e.rows.findIndex(r=>r.kind==="user"&&r.pending&&r.clientMessageId===t);if(n===-1)return e;const s=e.rows.slice(),o=s[n];return(o==null?void 0:o.kind)!=="user"?e:(s[n]={...o,pending:!1,failed:!0},{...e,rows:s})}let Jt=0;function Ti(){return Jt+=1,`s-${Date.now().toString(36)}-${Jt}`}const R=ke()((e,t)=>({sessions:{},order:[],activeSessionId:null,createSession(n){const s=Ti(),o={id:s,agentId:null,title:"New chat",status:"idle",cwd:n,timeline:jt,userMessageCount:0};return e(r=>({sessions:{...r.sessions,[s]:o},order:[s,...r.order],activeSessionId:s})),s},hydrate(n){e(s=>s.sessions[n.id]?s:{sessions:{...s.sessions,[n.id]:n},order:[...s.order,n.id]})},bindAgent(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,agentId:s}}}:o})},setStatus(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,status:s}}}:o})},setStatusByAgentId(n,s){const o=t().findByAgentId(n);o&&t().setStatus(o.id,s)},setModel(n,s,o){e(r=>{const i=r.sessions[n];return i?{sessions:{...r.sessions,[n]:{...i,model:s,modelProvider:o}}}:r})},setModelByAgentId(n,s,o){const r=t().findByAgentId(n);r&&t().setModel(r.id,s,o)},setTitle(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,title:s}}}:o})},setCwd(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,cwd:s}}}:o})},applyStreamEvent(n,s){e(o=>{const r=o.sessions[n];if(!r)return o;const i=On(r.timeline,s);let c=r.title;if(s.kind==="turn_completed"&&c==="New chat"){const d=i.rows.slice().reverse().find(h=>h.kind==="assistant");d&&d.kind==="assistant"&&d.text&&(c=d.text.slice(0,40)+(d.text.length>40?"…":""))}return{sessions:{...o.sessions,[n]:{...r,timeline:i,title:c}}}})},addOptimisticUserMessage(n,s,o,r,i){e(c=>{const d=c.sessions[n];if(!d)return c;const h=ji(d.timeline,s,o,r,i);return{sessions:{...c.sessions,[n]:{...d,timeline:h,userMessageCount:d.userMessageCount+1}}}})},markUserMessageFailed(n,s){e(o=>{const r=o.sessions[n];if(!r)return o;const i=Ci(r.timeline,s);return{sessions:{...o.sessions,[n]:{...r,timeline:i}}}})},activate(n){e({activeSessionId:n})},remove(n){e(s=>{const{[n]:o,...r}=s.sessions,i=s.order.filter(d=>d!==n),c=s.activeSessionId===n?i[0]??null:s.activeSessionId;return{sessions:r,order:i,activeSessionId:c}})},findByAgentId(n){return Object.values(t().sessions).find(s=>s.agentId===n)}})),Qt=new WeakMap;function Ei(e,t="pi"){const n=Qt.get(e);if(n)return n;const s=e.providers.resolveDefaultModel(t).then(o=>({model:o.model,modelProvider:o.modelProvider})).catch(()=>({}));return Qt.set(e,s),s}const rt=new Map;function Fn(e,t){const n=R.getState().sessions[t];if(!n)return Promise.reject(new Error(`unknown session: ${t}`));if(n.agentId)return Promise.resolve(n.agentId);const s=rt.get(t);if(s)return s;const o=(async()=>{if(!n.model){const d=await Ei(e),h=R.getState().sessions[t];d.model&&h&&!h.model&&R.getState().setModel(t,d.model,d.modelProvider)}const r=R.getState().sessions[t];if(!r)throw new Error(`unknown session: ${t}`);const i={provider:"pi",cwd:r.cwd||"~"};r.model&&(i.model=r.model),r.modelProvider&&(i.modelProvider=r.modelProvider);const c=await e.createAgent({config:i,labels:{}});return R.getState().bindAgent(t,c.agentId),c.agentId})();return rt.set(t,o),o.finally(()=>rt.delete(t)),o}async function Ni(e,t){var o;const n=R.getState().sessions[t];if(!n||n.userMessageCount>0||n.timeline.rows.length>0)return!1;await((o=rt.get(t))==null?void 0:o.catch(()=>{}));const s=R.getState().sessions[t];return s?(s.agentId&&e&&await e.agent(s.agentId).delete().catch(()=>{}),R.getState().remove(t),!0):!1}function gt(e,t){return e.filter(n=>n.workspaceCwd===t)}function nt(e){(e==null?void 0:e.kind)==="chat"&&R.getState().activate(e.data.sessionId)}const E=ke()((e,t)=>({tabs:[],activeTabId:null,activeWorkspaceCwd:null,lastActiveTabByWorkspace:{},open(n){const s=t().tabs.find(o=>o.id===n.id);if(s){t().activate(s.id);return}e(o=>({tabs:[...o.tabs,n],activeTabId:n.id,activeWorkspaceCwd:n.workspaceCwd,lastActiveTabByWorkspace:{...o.lastActiveTabByWorkspace,[n.workspaceCwd]:n.id}})),nt(n)},close(n){let s;e(o=>{const r=o.tabs.find(m=>m.id===n);if(!r)return o;const i=o.tabs.findIndex(m=>m.id===n),c=o.tabs.filter(m=>m.id!==n);let d=o.activeTabId;const h={...o.lastActiveTabByWorkspace};if(d===n){const m=gt(c,r.workspaceCwd),x=Math.min(i,m.length-1),f=m[x];d=(f==null?void 0:f.id)??null,s=f}if(h[r.workspaceCwd]===n){const m=gt(c,r.workspaceCwd)[0];m?h[r.workspaceCwd]=m.id:delete h[r.workspaceCwd]}return{tabs:c,activeTabId:d,lastActiveTabByWorkspace:h}}),nt(s)},activate(n){let s;e(o=>{const r=o.tabs.find(i=>i.id===n);return r?(s=r,{activeTabId:n,activeWorkspaceCwd:r.workspaceCwd,lastActiveTabByWorkspace:{...o.lastActiveTabByWorkspace,[r.workspaceCwd]:n}}):o}),nt(s)},switchWorkspace(n){let s;e(o=>{var h;const r=gt(o.tabs,n),i=o.lastActiveTabByWorkspace[n],d=i&&r.some(m=>m.id===i)?i:((h=r[0])==null?void 0:h.id)??null;return s=r.find(m=>m.id===d),{activeWorkspaceCwd:n,activeTabId:d,lastActiveTabByWorkspace:d?{...o.lastActiveTabByWorkspace,[n]:d}:o.lastActiveTabByWorkspace}}),nt(s)},reorder(n,s){e(o=>{const r=o.tabs.findIndex(h=>h.id===n),i=o.tabs.findIndex(h=>h.id===s);if(r===-1||i===-1||r===i)return o;const c=o.tabs.slice(),[d]=c.splice(r,1);return d?(c.splice(i,0,d),{tabs:c}):o})},updateLabel(n,s){e(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,label:s}:r)}))},updateData(n,s){e(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,data:{...r.data,...s}}:r)}))},closeByPathPrefix(n){const s=t().tabs.filter(o=>{if(o.kind!=="file"&&o.kind!=="diff"&&o.kind!=="molecule")return!1;const r=o.data.path;return r===n||((r==null?void 0:r.startsWith(`${n}/`))??!1)});for(const o of s)t().close(o.id)}})),Q={chat:e=>`chat-${e}`,file:e=>`file-${e}`,diff:(e,t)=>`diff-${e}${t?"-staged":""}`,terminal:e=>`term-${e}`,molecule:e=>`mol-${e}`};let _t=0;function zn(e){_t+=1,E.getState().open({id:Q.terminal(`new-${_t}`),kind:"terminal",label:`Terminal ${_t}`,closable:!0,data:{slot:null,cwd:e},workspaceCwd:e})}let yt=0;function Ri(e){yt+=1,E.getState().open({id:Q.molecule(`new-${yt}`),kind:"molecule",label:`Molecule ${yt}`,closable:!0,data:{path:null},workspaceCwd:e})}function $t(e){const t=R.getState().createSession(e);E.getState().open({id:Q.chat(t),kind:"chat",label:"New chat",closable:!0,data:{sessionId:t},workspaceCwd:e});const n=M.getState().client;n&&Fn(n,t).catch(()=>{})}function Ct(e){const t=E.getState().tabs.find(s=>s.id===e);if(E.getState().close(e),(t==null?void 0:t.kind)!=="chat")return;const{sessionId:n}=t.data;Ni(M.getState().client,n)}const ee=ke()(e=>({rootPath:"",expanded:new Set,expandedByRoot:new Map,draft:null,selected:null,setRoot:t=>e(n=>{const s=new Map(n.expandedByRoot);n.rootPath&&s.set(n.rootPath,n.expanded);const o=s.get(t),r=new Set(o);return r.add(t),{rootPath:t,expanded:r,expandedByRoot:s,draft:null,selected:null}}),toggle:t=>e(n=>{if(t===n.rootPath)return n;const s=new Set(n.expanded);s.has(t)?s.delete(t):s.add(t);const o=new Map(n.expandedByRoot);return o.set(n.rootPath,s),{expanded:s,expandedByRoot:o}}),startDraft:(t,n)=>e(s=>{const o=new Set(s.expanded);o.add(t);const r=new Map(s.expandedByRoot);return s.rootPath&&r.set(s.rootPath,o),{draft:{parentPath:t,kind:n},expanded:o,expandedByRoot:r}}),cancelDraft:()=>e({draft:null}),setSelected:t=>e({selected:t}),repathAfterMove:(t,n,s)=>e(o=>{const r=h=>h===t?n:h.startsWith(`${t}/`)?n+h.slice(t.length):h,i=new Set([...o.expanded].map(r));i.add(s);const c=new Map(o.expandedByRoot);o.rootPath&&c.set(o.rootPath,i);const d=o.selected?{path:r(o.selected.path),isDirectory:o.selected.isDirectory}:null;return{expanded:i,expandedByRoot:c,selected:d}})}));let Ce=null;const Tt=new Set;function Mi(e){return Tt.add(e),()=>Tt.delete(e)}async function ut(e){var t;if(Ce)return Ce;try{const n=await e.connection.request("file_explorer_request",{path:"/home"}),o=(((t=n.result)==null?void 0:t.entries)??n.entries??[]).find(r=>r.kind==="directory"||r.type==="directory");Ce="/home/"+((o==null?void 0:o.name)||"user")}catch{return"/tmp"}for(const n of Tt)n(Ce);return Ce}function qi(){return Ce}async function Bi(e,t){return t==="~"||t.startsWith("~/")?await ut(e)+t.slice(1):t}function ft(){const e=M(o=>o.client),t=M(o=>o.status),[n,s]=w.useState(qi());return w.useEffect(()=>Mi(s),[]),w.useEffect(()=>{!e||t!=="open"||n||ut(e)},[e,t,n]),n}const $i="_dot_gfh8u_3",Di="_spinner_gfh8u_16",Zt={dot:$i,spinner:Di};function Ai(e){const{status:t,requiresAttention:n,attentionReason:s,showInactive:o}=e;if(!t)return null;if(n)switch(s){case"permission":return"statusWarning";case"error":return"statusDanger";case"finished":default:return"statusSuccess"}switch(t){case"running":case"queued":return"accent";case"waiting":return"statusWarning";case"finished":return"statusSuccess";case"error":return"statusDanger";case"idle":case"archived":return o?"foregroundMuted":null}}const en=8,Pi={accent:"var(--pi-color-accent)",statusSuccess:"var(--pi-color-statusSuccess)",statusDanger:"var(--pi-color-statusDanger)",statusWarning:"var(--pi-color-statusWarning)",foregroundMuted:"var(--pi-color-foregroundMuted)"};function Oi({className:e,...t}){const n=Ai(t);if(!n)return null;const s=t.status==="running"&&!t.requiresAttention,o=s?"var(--pi-color-accentBright, #a2b4d7)":Pi[n]??"currentColor";return a.jsx("span",{className:`${s?Zt.spinner:Zt.dot}${e?` ${e}`:""}`,style:s?{borderTopColor:o,borderRightColor:o}:{width:en,height:en,backgroundColor:o},role:"presentation"})}const Fi={initializing:"queued",idle:"idle",running:"running",error:"error",closed:"finished"};function zi(e){return Fi[e]??"idle"}const Wi="_wrap_3dtlo_1",Li="_header_3dtlo_7",Hi="_openBtn_3dtlo_15",Ui="_list_3dtlo_27",Ki="_item_3dtlo_32",Vi="_active_3dtlo_41",Gi="_title_3dtlo_45",Xi="_meta_3dtlo_54",Yi="_menuBtn_3dtlo_62",Ji="_workspaceGroup_3dtlo_80",Qi="_workspaceHeader_3dtlo_83",Zi="_workspaceChevron_3dtlo_108",ec="_workspaceIcon_3dtlo_119",tc="_workspaceLabel_3dtlo_123",nc="_workspaceCount_3dtlo_129",sc="_workspaceMenuBtn_3dtlo_134",oc="_workspaceSessions_3dtlo_154",rc="_emptyState_3dtlo_157",z={wrap:Wi,header:Li,openBtn:Hi,list:Ui,item:Ki,active:Vi,title:Gi,meta:Xi,menuBtn:Yi,workspaceGroup:Ji,workspaceHeader:Qi,workspaceChevron:Zi,workspaceIcon:ec,workspaceLabel:tc,workspaceCount:nc,workspaceMenuBtn:sc,workspaceSessions:oc,emptyState:rc};function ac({session:e,active:t,onSelect:n,onOpenMenu:s}){return a.jsxs("div",{className:W(z.item,t&&z.active),onClick:n,onContextMenu:o=>{o.preventDefault(),s(o.clientX,o.clientY)},children:[a.jsxs("div",{className:z.title,children:[a.jsx(Oi,{status:zi(e.status),showInactive:!0}),a.jsx("span",{children:e.title})]}),a.jsxs("div",{className:z.meta,children:[e.cwd||"~"," · ",e.agentId?e.agentId.slice(0,8):"new"," ·"," ",e.userMessageCount," msgs"]}),a.jsx("button",{type:"button",className:z.menuBtn,title:"Actions",onClick:o=>{o.stopPropagation();const r=o.currentTarget.getBoundingClientRect();s(r.left,r.bottom)},children:a.jsx(Et,{size:14})})]})}const ic="_trigger_yc3my_1",cc="_content_yc3my_12",lc="_item_yc3my_21",dc="_danger_yc3my_39",uc="_sep_yc3my_42",V={trigger:ic,content:cc,item:lc,danger:dc,sep:uc};function fc(){const e=j(v=>v.sessionMenu),t=j(v=>v.closeSessionMenu),n=M(v=>v.client),s=w.useRef(null),[o,r]=w.useState(!1);w.useEffect(()=>{r(e!==null)},[e]);const i=R(v=>e?v.sessions[e.sessionId]:void 0);if(!e)return null;const c=!!(i!=null&&i.agentId)&&(i==null?void 0:i.status)==="running";function d(v){r(v),v||t()}function h(){if(!i)return;const v=window.prompt("Rename:",i.title);if(v!=null&&v.trim()){const y=v.trim();R.getState().setTitle(i.id,y),E.getState().updateLabel(Q.chat(i.id),y),i.agentId&&(n==null||n.agent(i.agentId).update({title:y}).catch(()=>{}))}t()}function m(){i!=null&&i.agentId&&(n==null||n.agent(i.agentId).interrupt().catch(()=>{})),t()}function x(v){R.getState().remove(v),E.getState().close(Q.chat(v))}async function f(){if(i){if(!window.confirm("Archive this agent? It can be resumed later."))return t();if(t(),!i.agentId){x(i.id);return}if(!n){window.alert("Not connected — cannot archive remotely.");return}try{await n.agent(i.agentId).archive(),x(i.id)}catch(v){window.alert(`Failed to archive: ${v instanceof Error?v.message:String(v)}`)}}}async function p(){if(i){if(!window.confirm("Permanently delete this agent? This cannot be undone."))return t();if(t(),!i.agentId){x(i.id);return}if(!n){window.alert("Not connected — cannot delete remotely.");return}try{await n.agent(i.agentId).delete(),x(i.id)}catch(v){window.alert(`Failed to delete: ${v instanceof Error?v.message:String(v)}`)}}}return a.jsxs(Ke,{open:o,onOpenChange:d,modal:!1,children:[a.jsx(Ve,{asChild:!0,children:a.jsx("button",{ref:s,type:"button",className:V.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Ge,{children:a.jsxs(Xe,{className:V.content,align:"start",sideOffset:2,children:[a.jsxs(P,{className:V.item,onSelect:h,children:[a.jsx(ms,{size:13}),"Rename"]}),a.jsxs(P,{className:V.item,disabled:!c,onSelect:m,children:[a.jsx(gs,{size:13}),"Stop agent"]}),a.jsx(Se,{className:V.sep}),a.jsxs(P,{className:`${V.item} ${V.danger}`,onSelect:f,children:[a.jsx(_s,{size:13}),"Archive"]}),a.jsxs(P,{className:`${V.item} ${V.danger}`,onSelect:p,children:[a.jsx(Nt,{size:13}),"Delete permanently"]})]})})]})}function pc({label:e,cwd:t,sessionCount:n,collapsed:s,onToggleCollapsed:o,onOpenMenu:r}){return a.jsxs("div",{className:z.workspaceHeader,onClick:o,title:t,children:[a.jsx("button",{type:"button",className:z.workspaceChevron,"aria-label":s?"Expand workspace":"Collapse workspace",onClick:i=>{i.stopPropagation(),o()},children:s?a.jsx(Rt,{size:13}):a.jsx(pn,{size:13})}),a.jsx(ys,{size:13,className:W(z.workspaceIcon)}),a.jsx("span",{className:z.workspaceLabel,children:e}),a.jsx("span",{className:z.workspaceCount,children:n}),a.jsx("button",{type:"button",className:z.workspaceMenuBtn,title:"Workspace actions",onClick:i=>{i.stopPropagation();const c=i.currentTarget.getBoundingClientRect();r(c.left,c.bottom)},children:a.jsx(Et,{size:13})})]})}function qe(e,t){return t&&(e==="~"||e.startsWith("~/"))?t+e.slice(1):e}function Dt(e,t,n){const s=new Map;for(const o of e){const r=t[o];if(!r)continue;const i=qe(r.cwd||"~",n),c=s.get(i);c?c.push(r):s.set(i,[r])}return Array.from(s,([o,r])=>({cwd:o,sessions:r}))}function Wn(e){return!e||e==="~"?"~":e.split("/").filter(Boolean).pop()||e}function hc(e,t){return new Set(e.filter(n=>n.cwd!==t).map(n=>n.cwd))}function mc(){const e=j(p=>p.workspaceMenu),t=j(p=>p.closeWorkspaceMenu),n=M(p=>p.client),s=R(p=>p.order),o=R(p=>p.sessions),r=ft(),i=w.useRef(null),[c,d]=w.useState(!1);if(w.useEffect(()=>{d(e!==null)},[e]),!e)return null;const h=s.map(p=>o[p]).filter(p=>!!p).filter(p=>qe(p.cwd||"~",r)===e.cwd);function m(p){d(p),p||t()}function x(){e&&(t(),$t(e.cwd))}async function f(){if(!e)return;const p=h.length;if(!window.confirm(`Delete all ${p} conversation${p===1?"":"s"} in "${Wn(e.cwd)}"? This deletes the conversations only — files on disk are untouched. This cannot be undone.`))return t();t();for(const y of h){if(y.agentId&&n)try{await n.agent(y.agentId).delete()}catch(_){window.alert(`Failed to delete "${y.title}": ${_ instanceof Error?_.message:String(_)}`);continue}R.getState().remove(y.id),E.getState().close(Q.chat(y.id))}}return a.jsxs(Ke,{open:c,onOpenChange:m,modal:!1,children:[a.jsx(Ve,{asChild:!0,children:a.jsx("button",{ref:i,type:"button",className:V.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Ge,{children:a.jsxs(Xe,{className:V.content,align:"start",sideOffset:2,children:[a.jsxs(P,{className:V.item,onSelect:x,children:[a.jsx(hn,{size:13}),"New conversation"]}),a.jsx(Se,{className:V.sep}),a.jsxs(P,{className:`${V.item} ${V.danger}`,onSelect:f,children:[a.jsx(Nt,{size:13}),"Delete workspace (all conversations)"]})]})})]})}function gc(){const e=R(y=>y.order),t=R(y=>y.sessions),n=R(y=>y.activeSessionId),s=R(y=>y.activate),o=E(y=>y.open),r=M(y=>y.status),i=j(y=>y.openSessionMenu),c=j(y=>y.openWorkspaceMenu),d=j(y=>y.setCwd),h=j(y=>y.openCwdPicker),m=j(y=>y.collapsedWorkspaces),x=j(y=>y.toggleWorkspaceCollapsed),f=ft();function p(y){s(y);const _=t[y],q=qe((_==null?void 0:_.cwd)||"~",f);_!=null&&_.cwd&&d(_.cwd),o({id:Q.chat(y),kind:"chat",label:(_==null?void 0:_.title)??"Chat",closable:!0,data:{sessionId:y},workspaceCwd:q})}const v=Dt(e,t,f);return a.jsxs("div",{className:z.wrap,children:[a.jsxs("div",{className:z.header,children:[a.jsx("h3",{children:"Workspaces"}),a.jsx(Y,{size:"xs",variant:"ghost",iconOnly:!0,className:z.openBtn,title:r!=="open"?"Connect to open a workspace":"Open a workspace folder",disabled:r!=="open",onClick:()=>h(),children:a.jsx(mn,{size:13})})]}),a.jsxs("div",{className:z.list,children:[v.length===0&&a.jsx("div",{className:z.emptyState,children:r!=="open"?"Not connected":"No workspaces — open a folder to start"}),v.map(y=>{const _=m.has(y.cwd);return a.jsxs("div",{className:z.workspaceGroup,children:[a.jsx(pc,{label:Wn(y.cwd),cwd:y.cwd,sessionCount:y.sessions.length,collapsed:_,onToggleCollapsed:()=>x(y.cwd),onOpenMenu:(q,K)=>c(y.cwd,q,K)}),!_&&a.jsx("div",{className:z.workspaceSessions,children:y.sessions.map(q=>a.jsx(ac,{session:q,active:q.id===n,onSelect:()=>p(q.id),onOpenMenu:(K,C)=>i(q.id,K,C)},q.id))})]},y.cwd)})]}),a.jsx(fc,{}),a.jsx(mc,{})]})}const _c="_strip_tg9sf_1",yc="_tab_tg9sf_11",wc="_active_tg9sf_27",bc="_icon_tg9sf_31",xc="_label_tg9sf_36",Sc="_close_tg9sf_41",vc="_newTab_tg9sf_51",kc="_content_tg9sf_74",Ic="_item_tg9sf_83",jc="_itemIcon_tg9sf_97",X={strip:_c,tab:yc,active:wc,icon:bc,label:xc,close:Sc,newTab:vc,content:kc,item:Ic,itemIcon:jc},Cc={chat:yn,file:ws,diff:_n,terminal:gn,molecule:Mt};function Tc({tab:e}){const t=E(m=>m.activeTabId),n=E(m=>m.activate),s=Cc[e.kind],{attributes:o,listeners:r,setNodeRef:i,transform:c,transition:d,isDragging:h}=zs({id:e.id});return a.jsxs("div",{ref:i,className:W(X.tab,e.id===t&&X.active),style:{transform:Ws.Transform.toString(c),transition:d,opacity:h?.5:1},onClick:()=>n(e.id),onAuxClick:m=>{m.button===1&&e.closable&&Ct(e.id)},title:e.label,...o,...r,children:[a.jsx("span",{className:X.icon,children:a.jsx(s,{size:13})}),a.jsx("span",{className:X.label,children:e.label}),e.closable&&a.jsx("span",{className:X.close,onClick:m=>{m.stopPropagation(),Ct(e.id)},children:a.jsx(bt,{size:12})})]})}function Ec({workspaceCwd:e}){const t=e??"~";return a.jsxs(Ke,{children:[a.jsx(Ve,{asChild:!0,children:a.jsx("button",{type:"button",className:X.newTab,title:"New tab",disabled:!e,children:a.jsx(hn,{size:14})})}),a.jsx(Ge,{children:a.jsxs(Xe,{className:X.content,align:"start",sideOffset:4,children:[a.jsxs(P,{className:X.item,onSelect:()=>$t(t),children:[a.jsx(yn,{size:13,className:X.itemIcon}),"New chat"]}),a.jsxs(P,{className:X.item,onSelect:()=>zn(t),children:[a.jsx(gn,{size:13,className:X.itemIcon}),"New terminal"]}),a.jsxs(P,{className:X.item,onSelect:()=>Ri(t),children:[a.jsx(Mt,{size:13,className:X.itemIcon}),"New molecule view"]})]})})]})}function Nc(){const e=E(i=>i.tabs),t=E(i=>i.activeWorkspaceCwd),n=E(i=>i.reorder),s=e.filter(i=>i.workspaceCwd===t),o=Bs($s(Fs,{activationConstraint:{distance:4}}));function r(i){const{active:c,over:d}=i;!d||c.id===d.id||n(String(c.id),String(d.id))}return a.jsxs("div",{className:X.strip,children:[a.jsx(Ds,{sensors:o,collisionDetection:As,onDragEnd:r,children:a.jsx(Ps,{items:s.map(i=>i.id),strategy:Os,children:s.map(i=>a.jsx(Tc,{tab:i},i.id))})}),a.jsx(Ec,{workspaceCwd:t})]})}const Rc="_spinner_1tgzp_3",Mc={spinner:Rc},qc={xs:12,sm:16,md:20,lg:24},Bc={xs:1,sm:2,md:2,lg:3};function Ln({size:e="md",color:t="currentColor",className:n,"aria-label":s="Loading"}){const o=typeof e=="number"?e:qc[e],r=typeof e=="number"?2:Bc[e];return a.jsx("span",{className:`${Mc.spinner}${n?` ${n}`:""}`,role:"status","aria-label":s,style:{width:o,height:o,borderWidth:r,color:t}})}const $c=w.lazy(()=>pe(()=>import("./ChatPanel-8Tj813-O.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])).then(e=>({default:e.ChatPanel}))),tn=w.lazy(()=>pe(()=>import("./FilePanel-1jMXusYi.js"),__vite__mapDeps([16,1,7,6,5,2,17,11,12,18,19,3,13,14])).then(e=>({default:e.FilePanel}))),Dc=w.lazy(()=>pe(()=>import("./TerminalPanel-BQZ0KqJv.js"),__vite__mapDeps([20,1,21,22,7,6,5,2,3,13,14,23])).then(e=>({default:e.TerminalPanel}))),Ac=w.lazy(()=>pe(()=>import("./MoleculeViewerPanel-CtODGGih.js"),__vite__mapDeps([24,1,25,26,9,10,27,2,17,7,6,5,3,13,14,28])).then(e=>({default:e.MoleculeViewerPanel}))),Pc={chat:$c,file:tn,diff:tn,terminal:Dc,molecule:Ac},Oc="_area_abmp3_1",Fc="_panel_abmp3_7",zc="_active_abmp3_14",Wc="_empty_abmp3_17",Lc="_emptyStack_abmp3_25",Hc="_emptyTitle_abmp3_35",Uc="_emptyHint_abmp3_39",ue={area:Oc,panel:Fc,active:zc,empty:Wc,emptyStack:Lc,emptyTitle:Hc,emptyHint:Uc};function Kc(){const e=E(i=>i.tabs),t=E(i=>i.activeTabId),n=E(i=>i.activeWorkspaceCwd),s=M(i=>i.status),o=j(i=>i.openCwdPicker),r=e.some(i=>i.workspaceCwd===n);return n===null?a.jsx("div",{className:ue.area,children:a.jsxs("div",{className:ue.emptyStack,children:[a.jsx("div",{className:ue.emptyTitle,children:"No workspace open"}),a.jsx("div",{className:ue.emptyHint,children:"Open a project folder to start a chat."}),a.jsx(Y,{size:"sm",variant:"secondary",leftIcon:a.jsx(mn,{size:14}),disabled:s!=="open",title:s!=="open"?"Connect to open a workspace":"Open a workspace folder",onClick:()=>o(),children:"Open Workspace"})]})}):r?a.jsx("div",{className:ue.area,children:e.map(i=>{const c=Pc[i.kind];return a.jsx("div",{className:W(ue.panel,i.id===t&&ue.active),children:a.jsx(w.Suspense,{fallback:a.jsx(Ln,{size:"md"}),children:a.jsx(c,{tab:i})})},i.id)})}):a.jsx("div",{className:ue.area,children:a.jsx("div",{className:ue.empty,children:"No open tabs in this workspace"})})}const me={fileRead:e=>["file","read",e],fileDownload:e=>["file","download",e],fileText:(e,t)=>["file","text",e,t],fileDiff:(e,t,n)=>["file","diff",e,t,n],fileDiffByPath:e=>["file","diff",e],explorer:e=>["explorer",e],agentList:()=>["agents","list"],providerModels:e=>["providers","models",e],agentTimeline:e=>["agents","timeline",e],agentCommands:e=>["agents","commands",e]};function Vc(e){const t=e.kind==="directory"||e.type==="directory"?"directory":"file";return{name:e.name??"",kind:t,size:e.size,mtimeMs:e.mtimeMs}}function Gc(e){return e.slice().sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}async function Hn(e,t){const s=(await e.connection.request("file_explorer_request",{path:t})).result;if(!s||s.ok===!1)throw new Error(s&&"error"in s?s.error:"explorer request failed");const o="entries"in s?s.entries??[]:[];return{path:s.resolvedPath??t,entries:Gc(o.map(Vc))}}function Xc(e,t=!0){const n=M(s=>s.client);return un({queryKey:me.explorer(e),queryFn:()=>{if(!n)throw new Error("not connected");return Hn(n,e)},enabled:!!n&&!!e&&t})}function Yc(e){const t=M(o=>o.client),n=w.useMemo(()=>Array.from(e),[e]),s=cs({queries:n.map(o=>({queryKey:me.explorer(o),queryFn:()=>{if(!t)throw new Error("not connected");return Hn(t,o)},enabled:!!t&&!!o}))});return w.useMemo(()=>{const o=new Map;return n.forEach((r,i)=>{const c=s[i];o.set(r,{listing:c==null?void 0:c.data,isLoading:!!(c!=null&&c.isLoading),isError:!!(c!=null&&c.isError),error:c==null?void 0:c.error})}),o},[n,s])}function Jc(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="file_changed"&&"path"in e&&typeof e.path=="string"}function Qc(e,t){const n=new Set,s=e.connection.onSessionMessage(o=>{const r=o;Jc(r)&&n.has(r.path)&&t(r.path)});return{sync(o){for(const r of n)o.has(r)||(n.delete(r),e.connection.request("file_watch_unsubscribe",{path:r}).catch(()=>{}));for(const r of o)n.has(r)||(n.add(r),e.connection.request("file_watch_subscribe",{path:r}).then(i=>{const c=i;(c==null?void 0:c.ok)===!1&&console.warn(`useExplorerWatch: ${c.error??"subscribe failed"} for "${r}"`)}).catch(()=>{}))},dispose(){s();for(const o of n)e.connection.request("file_watch_unsubscribe",{path:o}).catch(()=>{});n.clear()}}}function Zc(e){const t=M(i=>i.client),n=Me(),s=w.useRef(null),o=w.useRef(null),r=Array.from(e).toSorted().join("\0");w.useEffect(()=>{var i,c;t&&(o.current!==t&&((i=s.current)==null||i.dispose(),s.current=Qc(t,d=>{n.invalidateQueries({queryKey:me.explorer(d)})}),o.current=t),(c=s.current)==null||c.sync(new Set(r?r.split("\0"):[])))},[t,r,n]),w.useEffect(()=>()=>{var i;(i=s.current)==null||i.dispose(),s.current=null,o.current=null},[])}const nn=new WeakMap;function sn(e){let t=nn.get(e);return t||(t=new Fa(e),t.start(),nn.set(e,t)),t}function el(e,t,n){const s=new Blob([Uint8Array.from(e)],{type:n||"application/octet-stream"}),o=URL.createObjectURL(s),r=document.createElement("a");r.href=o,r.download=t,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(o),0)}function Un(){const e=M(o=>o.daemon),t=Me(),n=w.useCallback(async(o,r)=>{if(!e)throw new Error("not connected");const i=o?`${o}/${r.name}`:r.name,c=new Uint8Array(await r.arrayBuffer());await sn(e).upload(i,c),await t.invalidateQueries({queryKey:["explorer"]})},[e,t]),s=w.useCallback(async o=>{if(!e)throw new Error("not connected");const r=await sn(e).download(o);el(r.bytes,r.fileName||o.split("/").pop()||"download",r.mimeType)},[e]);return{upload:n,saveToDisk:s}}function hf(e,t){return e?e.startsWith("/")||e.startsWith("~")?e:t?`${t.replace(/\/+$/,"")}/${e}`:null:null}function Re(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):"/"}function tl(e,t){return!t||!e.startsWith(t)?e:e.slice(t.length).replace(/^\/+/,"")}function on(e,t,n){if(t.kind!=="file"&&t.kind!=="directory")return null;const s=t.kind==="directory"?t.path:Re(t.path);if(s===Re(e)||s===e||s.startsWith(`${e}/`)||s!==n&&!s.startsWith(`${n}/`))return null;const o=e.split("/").pop();return{destinationDir:s,destination:`${s}/${o}`}}function rn(e,t){if(e.kind!=="file"&&e.kind!=="directory")return null;const n=e.kind==="directory"?e.path:Re(e.path);return n!==t&&!n.startsWith(`${t}/`)?null:n}const nl={empty_path:"Nothing to move.",invalid_name:"Invalid name for the destination.",exists:"An item with that name already exists in the destination folder.",not_found:"That item or destination folder no longer exists.",not_a_directory:"The destination is not a folder.",same_path:"That item is already in this folder.",into_descendant:"A folder cannot be moved into itself.",cross_device:"Cannot move across filesystems."};async function sl(e,t,n){const s=await e.connection.request("file_move_request",{path:t,destination:n});if(!s.ok){const o=s.error??"";throw new Error(nl[o]??o??"Failed to move")}return s.destination??n}function ol(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}function Kn(e,t,n,s,o,r){var c;(r==null?void 0:r.parentPath)===t&&e.push({kind:"draft",path:`${t}::draft`,depth:n,draftKind:r.kind,parentPath:t});const i=o.get(t);if(!i||i.isLoading){e.push({kind:"loading",path:t,depth:n});return}if(i.isError){const d=i.error instanceof Error?i.error.message:"failed to load";e.push({kind:"error",path:t,depth:n,message:d});return}for(const d of((c=i.listing)==null?void 0:c.entries)??[])rl(e,t,d,n,s,o,r)}function rl(e,t,n,s,o,r,i){const c=ol(t,n.name);if(n.kind!=="directory"){e.push({kind:"file",path:c,name:n.name,depth:s});return}const d=o.has(c);e.push({kind:"directory",path:c,name:n.name,depth:s,expanded:d}),d&&Kn(e,c,s+1,o,r,i)}function al(e,t,n,s){if(!e)return[];const o=[];return Kn(o,e,0,t,n,s),o}const il="_container_1d3wg_1",cl="_header_1d3wg_7",ll="_uploadButton_1d3wg_14",dl="_hiddenInput_1d3wg_33",ul="_status_1d3wg_36",fl="_statusError_1d3wg_37",pl="_rowAction_1d3wg_50",hl="_item_1d3wg_65",ml="_list_1d3wg_69",gl="_active_1d3wg_92",_l="_selected_1d3wg_97",yl="_dropTarget_1d3wg_101",wl="_chevronSlot_1d3wg_106",bl="_chevron_1d3wg_106",xl="_chevronOpen_1d3wg_117",Sl="_icon_1d3wg_120",vl="_name_1d3wg_127",kl="_dirName_1d3wg_132",Il="_statusRow_1d3wg_138",jl="_statusRowError_1d3wg_149",Cl="_emptyState_1d3wg_152",Tl="_draftInput_1d3wg_158",B={container:il,header:cl,uploadButton:ll,hiddenInput:dl,status:ul,statusError:fl,rowAction:pl,item:hl,list:ml,active:gl,selected:_l,dropTarget:yl,chevronSlot:wl,chevron:bl,chevronOpen:xl,icon:Sl,name:vl,dirName:kl,statusRow:Il,statusRowError:jl,emptyState:Cl,draftInput:Tl};function El({draftKind:e,indentStyle:t,onSubmit:n,onCancel:s}){const[o,r]=w.useState("");return a.jsxs("div",{className:B.item,style:t,onClick:i=>i.stopPropagation(),children:[a.jsx("span",{className:B.chevronSlot}),a.jsx("span",{className:B.icon,children:e==="directory"?a.jsx(Ne,{size:16}):a.jsx(wn,{size:16})}),a.jsx("input",{className:B.draftInput,autoFocus:!0,spellCheck:!1,placeholder:e==="directory"?"New folder":"New file",value:o,onChange:i=>r(i.target.value),onKeyDown:i=>{if(i.key==="Enter"){i.preventDefault();const c=o.trim();c?n(c):s()}else i.key==="Escape"&&(i.preventDefault(),s())},onBlur:s})]})}const Nl=14;function Rl({row:e,active:t,selected:n,dropTarget:s,onToggle:o,onOpenFile:r,onContextMenu:i,onSubmitDraft:c,onCancelDraft:d,onDragStartRow:h,onDragEndRow:m}){const x={paddingLeft:8+e.depth*Nl};if(e.kind==="loading")return a.jsx("div",{className:B.statusRow,style:x,children:"Loading…"});if(e.kind==="error")return a.jsx("div",{className:W(B.statusRow,B.statusRowError),style:x,children:e.message??"failed to load"});if(e.kind==="draft")return a.jsx(El,{draftKind:e.draftKind,indentStyle:x,onSubmit:p=>c(e.parentPath,p),onCancel:d});const f=e.kind==="directory";return a.jsxs("div",{className:W(B.item,t&&B.active,n&&B.selected,s&&B.dropTarget),style:x,title:e.path,draggable:!0,onDragStart:p=>h(e.path,p),onDragEnd:m,onClick:()=>f?o(e.path):r(e.path),onContextMenu:p=>{p.preventDefault(),p.stopPropagation(),i(e.path,f,p.clientX,p.clientY)},children:[a.jsx("span",{className:B.chevronSlot,children:f&&a.jsx(Rt,{size:14,className:W(B.chevron,e.expanded&&B.chevronOpen)})}),a.jsx("span",{className:B.icon,children:f?a.jsx(Ne,{size:16}):a.jsx(wn,{size:16})}),a.jsx("span",{className:f?B.dirName:B.name,children:e.name}),a.jsx("button",{type:"button",className:B.rowAction,title:"Actions",onClick:p=>{p.stopPropagation();const v=p.currentTarget.getBoundingClientRect();i(e.path,f,v.left,v.bottom)},children:a.jsx(Et,{size:14})})]})}async function an(e){var n;if((n=navigator.clipboard)!=null&&n.writeText)try{await navigator.clipboard.writeText(e);return}catch{}const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();try{if(!document.execCommand("copy"))throw new Error('execCommand("copy") failed')}finally{t.remove()}}const Ml=w.lazy(()=>pe(()=>import("./TextViewer-3yEorz3A.js"),__vite__mapDeps([29,1,30,2,7,6,5,31,27,18,19,3,13,14,32])).then(e=>({default:e.TextViewer}))),ql=w.lazy(()=>pe(()=>import("./MarkdownFileViewer-BChv2tKK.js"),__vite__mapDeps([33,1,30,2,7,6,5,31,4,8,18,19,3,13,14,34])).then(e=>({default:e.MarkdownFileViewer}))),Bl=w.lazy(()=>pe(()=>import("./ImageViewer-Cimj0SFJ.js"),__vite__mapDeps([35,1,27,2,18,19,7,6,5,3,13,14,36])).then(e=>({default:e.ImageViewer}))),$l=w.lazy(()=>pe(()=>import("./VideoViewer-CbBaI4CK.js"),__vite__mapDeps([37,1,27,2,18,19,7,6,5,3,13,14,38])).then(e=>({default:e.VideoViewer}))),Dl=w.lazy(()=>pe(()=>import("./BinaryFallbackViewer-BPcn4yCY.js"),__vite__mapDeps([39,1,27,2,3,7,6,5,13,14,40])).then(e=>({default:e.BinaryFallbackViewer}))),mf={text:Ml,markdown:ql,image:Bl,video:$l,binary:Dl},Al={md:"markdown",markdown:"markdown",mdx:"markdown",png:"image",jpg:"image",jpeg:"image",gif:"image",webp:"image",svg:"image",bmp:"image",ico:"image",avif:"image",mp4:"video",webm:"video",mov:"video",m4v:"video",ogv:"video",pdf:"binary",zip:"binary",gz:"binary",tar:"binary",exe:"binary",wasm:"binary",woff:"binary",woff2:"binary",ttf:"binary",otf:"binary"},Pl=[["image/","image"],["video/","video"]];function Vn(e){const t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}const Ol={pdb:!0,cif:!0,mmcif:!0,mol:!0,mol2:!0,xyz:!0,extxyz:!0,gro:!0,lammpstrj:!0,xsf:!0},Fl={poscar:!0,contcar:!0};function zl(e){if(Ol[Vn(e)])return!0;const t=e.split("/").pop()??e;return!!Fl[t.toLowerCase()]}function gf(e,t={}){const n=Al[Vn(e)];if(n)return n;const s=t.mimeHint??"";for(const[o,r]of Pl)if(s.startsWith(o))return r;return t.isBinary?"binary":"text"}function Gn(e,t){if(zl(e)){Xn(e,t);return}const n=e.split("/").pop()||e;E.getState().open({id:Q.file(e),kind:"file",label:n,closable:!0,data:{path:e},workspaceCwd:t})}function Xn(e,t){const n=e.split("/").pop()||e;E.getState().open({id:Q.molecule(e),kind:"molecule",label:n,closable:!0,data:{path:e},workspaceCwd:t})}const Wl="_trigger_13ghf_1",Ll="_content_13ghf_12",Hl="_item_13ghf_21",Ul="_danger_13ghf_35",Kl="_sep_13ghf_38",O={trigger:Wl,content:Ll,item:Hl,danger:Ul,sep:Kl};function Vl(){const e=j($=>$.fileMenu),t=j($=>$.closeFileMenu),n=M($=>$.client),s=ee($=>$.startDraft),o=ee($=>$.rootPath),r=E($=>$.activeWorkspaceCwd),{saveToDisk:i}=Un(),c=Me(),d=w.useRef(null),[h,m]=w.useState(!1);if(w.useEffect(()=>{m(e!==null)},[e]),!e)return null;const x=e.path.split("/").pop()||e.path;function f($){m($),$||t()}function p(){e&&(t(),Gn(e.path,r||"~"))}function v(){e&&(t(),Xn(e.path,r||"~"))}async function y(){if(e){t();try{await an(e.path)}catch{window.alert("Failed to copy to clipboard.")}}}async function _(){if(e){t();try{await an(tl(e.path,o)||"/")}catch{window.alert("Failed to copy to clipboard.")}}}async function q(){if(e){t();try{await i(e.path)}catch($){window.alert(`Failed to download: ${$ instanceof Error?$.message:String($)}`)}}}async function K(){if(!e)return;const $=e.isDirectory?"folder (and everything inside it)":"file";if(!window.confirm(`Permanently delete this ${$}? "${x}" — this cannot be undone.`))return t();if(t(),!n){window.alert("Not connected — cannot delete remotely.");return}try{const L=await n.connection.request("file_delete_request",{path:e.path});if(!L.ok)throw new Error(L.error??"delete failed");await c.invalidateQueries({queryKey:["explorer"]}),E.getState().closeByPathPrefix(e.path)}catch(L){window.alert(`Failed to delete: ${L instanceof Error?L.message:String(L)}`)}}function C($){if(!e)return;const L=e.isDirectory?e.path:Re(e.path);t(),s(L,$)}return a.jsxs(Ke,{open:h,onOpenChange:f,modal:!1,children:[a.jsx(Ve,{asChild:!0,children:a.jsx("button",{ref:d,type:"button",className:O.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Ge,{children:a.jsx(Xe,{className:O.content,align:"start",sideOffset:2,children:e.background?a.jsxs(a.Fragment,{children:[a.jsxs(P,{className:O.item,onSelect:()=>C("file"),children:[a.jsx(xt,{size:13}),"New File"]}),a.jsxs(P,{className:O.item,onSelect:()=>C("directory"),children:[a.jsx(at,{size:13}),"New Folder"]}),a.jsx(Se,{className:O.sep}),a.jsxs(P,{className:O.item,onSelect:y,children:[a.jsx(Je,{size:13}),"Copy Current Directory Path"]}),a.jsxs(P,{className:O.item,onSelect:_,children:[a.jsx(Je,{size:13}),"Copy Current Directory Relative Path"]})]}):a.jsxs(a.Fragment,{children:[!e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(P,{className:O.item,onSelect:p,children:[a.jsx(bs,{size:13}),"Open"]}),a.jsxs(P,{className:O.item,onSelect:v,children:[a.jsx(Mt,{size:13}),"Open in MolViewer"]}),a.jsx(Se,{className:O.sep})]}),e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(P,{className:O.item,onSelect:()=>C("file"),children:[a.jsx(xt,{size:13}),"New File"]}),a.jsxs(P,{className:O.item,onSelect:()=>C("directory"),children:[a.jsx(at,{size:13}),"New Folder"]}),a.jsx(Se,{className:O.sep})]}),a.jsxs(P,{className:O.item,onSelect:y,children:[a.jsx(Je,{size:13}),"Copy Absolute Path"]}),a.jsxs(P,{className:O.item,onSelect:_,children:[a.jsx(Je,{size:13}),"Copy Relative Path"]}),a.jsx(Se,{className:O.sep}),!e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(P,{className:O.item,onSelect:q,children:[a.jsx(xs,{size:13}),"Download"]}),a.jsx(Se,{className:O.sep})]}),a.jsxs(P,{className:`${O.item} ${O.danger}`,onSelect:K,children:[a.jsx(Nt,{size:13}),"Delete"]})]})})})]})}const Gl={empty_path:"Choose a folder first.",invalid_name:'Invalid name — cannot be empty or contain "/".',exists:"An item with that name already exists here.",not_found:"That folder no longer exists.",not_a_directory:"That path is not a folder.",unreadable:"That folder is not readable."};async function Yn(e,t,n,s){const o=await e.connection.request("file_create_request",{path:t,name:n,kind:s});if(!o.ok){const r=o.error??"";throw new Error(Gl[r]??r??"Failed to create")}return o.path??(t.endsWith("/")?`${t}${n}`:`${t}/${n}`)}const Xl=28,Fe="application/x-pi-studio-path",wt="Files";function Yl(){const e=M(g=>g.client),t=ee(g=>g.rootPath),n=ee(g=>g.expanded),s=ee(g=>g.setRoot),o=ee(g=>g.toggle),r=ee(g=>g.draft),i=ee(g=>g.startDraft),c=ee(g=>g.cancelDraft),d=ee(g=>g.selected),h=ee(g=>g.setSelected),m=E(g=>g.activeWorkspaceCwd),x=E(g=>g.tabs.find(k=>k.id===g.activeTabId)),{upload:f}=Un(),p=j(g=>g.openFileMenu),v=Me(),[y,_]=w.useState(null),[q,K]=w.useState(null),C=w.useRef(null),$=w.useRef(null),L=w.useRef(null),te=w.useRef(null),Ye=(x==null?void 0:x.kind)==="file"||(x==null?void 0:x.kind)==="molecule"?x.data.path:null,le=d?d.isDirectory?d.path:Re(d.path):t,_e=w.useRef(null);w.useEffect(()=>{if(!e)return;const g=m||"~";_e.current!==g&&(_e.current=g,Bi(e,g).then(k=>s(k)))},[e,m,s]);const Be=Yc(n);Zc(n);const ye=w.useMemo(()=>al(t,n,Be,r),[t,n,Be,r]),$e=ls({count:ye.length,getScrollElement:()=>$.current,estimateSize:()=>Xl,overscan:12,getItemKey:g=>{var k;return((k=ye[g])==null?void 0:k.path)??g}});function De(g){Gn(g,m||"~")}function I(g,k){k.dataTransfer.setData(Fe,g),k.dataTransfer.effectAllowed="move",L.current=g}function de(){L.current=null}function pt(){K(null),te.current&&(clearTimeout(te.current.timer),te.current=null)}function Pt(g){var T;if(((T=te.current)==null?void 0:T.path)===g.path||(te.current&&clearTimeout(te.current.timer),te.current=null,g.kind!=="directory"||g.expanded))return;const k=window.setTimeout(()=>o(g.path),700);te.current={path:g.path,timer:k}}async function Zn(g,k){const T=on(g,k,t);if(!T||!e)return;const F=g.split("/").pop()??g;_({text:`Moving ${F}…`,error:!1});try{await sl(e,g,T.destination),await v.invalidateQueries({queryKey:me.explorer(Re(g))}),await v.invalidateQueries({queryKey:me.explorer(T.destinationDir)}),ee.getState().repathAfterMove(g,T.destination,T.destinationDir);const H=E.getState().tabs.some(re=>(re.kind==="file"||re.kind==="molecule")&&re.data.path===g);E.getState().closeByPathPrefix(g),H&&De(T.destination),_({text:`Moved to ${T.destinationDir.split("/").pop()||"/"}`,error:!1})}catch(H){_({text:H instanceof Error?H.message:"Failed to move",error:!0})}}async function es(g,k){const T=(r==null?void 0:r.kind)??"file";if(c(),!!e)try{const F=await Yn(e,g,k,T);await v.invalidateQueries({queryKey:me.explorer(g)}),_({text:`Created ${F}`,error:!1}),T==="file"&&De(F)}catch(F){_({text:F instanceof Error?F.message:"Failed to create",error:!0})}}async function Ot(g,k){var re;if(!k.length||!g)return;const T=(re=Be.get(g))==null?void 0:re.listing,F=new Set((T==null?void 0:T.entries.map(ae=>ae.name))??[]),H=k.filter(ae=>F.has(ae.name));if(H.length>0){const ae=H.map(ns=>ns.name).join(", ");if(!window.confirm(`Overwrite ${H.length>1?"these files":"this file"}? ${ae}`))return}_({text:`Uploading ${k.length} file${k.length>1?"s":""}…`,error:!1});try{for(const ae of k)await f(g,ae);_({text:`Uploaded ${k.length} file${k.length>1?"s":""}`,error:!1})}catch(ae){_({text:`Upload failed: ${ae instanceof Error?ae.message:"unknown"}`,error:!0})}}function Ft(g,k){if(g.preventDefault(),g.dataTransfer.types.includes(Fe)){const H=g.dataTransfer.getData(Fe)||L.current;pt(),H&&Zn(H,k??{kind:"directory",path:t});return}if(pt(),!g.dataTransfer.types.includes(wt))return;const T=k?rn(k,t):t;if(!T)return;const F=Array.from(g.dataTransfer.files);F.length&&Ot(T,F)}function ts(g){const k=g.dataTransfer.types.includes(Fe);!k&&!g.dataTransfer.types.includes(wt)||(g.preventDefault(),g.dataTransfer.dropEffect=k?"move":"copy")}return e?a.jsxs("div",{className:B.container,onDragOver:ts,onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||pt()},onDrop:g=>Ft(g),children:[a.jsxs("div",{className:B.header,children:[a.jsx("button",{type:"button",className:B.uploadButton,onClick:()=>i(le,"file"),disabled:!t,title:d?`New file in ${le.split("/").pop()||"/"}`:"New file in workspace root",children:a.jsx(xt,{size:14})}),a.jsx("button",{type:"button",className:B.uploadButton,onClick:()=>i(le,"directory"),disabled:!t,title:d?`New folder in ${le.split("/").pop()||"/"}`:"New folder in workspace root",children:a.jsx(at,{size:14})}),a.jsxs("button",{type:"button",className:B.uploadButton,onClick:()=>{var g;return(g=C.current)==null?void 0:g.click()},disabled:!t,title:"Upload files to the workspace root",children:[a.jsx(Ss,{size:14}),a.jsx("span",{children:"Upload"})]}),a.jsx("input",{ref:C,type:"file",multiple:!0,className:B.hiddenInput,onChange:g=>{Ot(t,Array.from(g.target.files??[])),g.target.value=""}})]}),y&&a.jsx("div",{className:y.error?B.statusError:B.status,children:y.text}),a.jsxs("div",{className:B.list,ref:$,onContextMenu:g=>{g.preventDefault(),p(t,!0,g.clientX,g.clientY,!0)},children:[ye.length===0&&a.jsx("div",{className:B.emptyState,children:"No files loaded"}),a.jsx("div",{style:{position:"relative",height:$e.getTotalSize()},children:$e.getVirtualItems().map(g=>{const k=ye[g.index];return k?a.jsx("div",{"data-index":g.index,style:{position:"absolute",top:0,left:0,width:"100%",height:g.size,transform:`translateY(${g.start}px)`},onDragEnter:T=>{if(T.dataTransfer.types.includes(Fe)){const H=L.current;if(!H)return;const re=on(H,k,t);K(re?k.path:null),Pt(k);return}if(!T.dataTransfer.types.includes(wt))return;const F=rn(k,t);K(F?k.path:null),Pt(k)},onDrop:T=>{T.stopPropagation(),Ft(T,k)},children:a.jsx(Rl,{row:k,active:(k.kind==="file"||k.kind==="directory")&&k.path===Ye,selected:(k.kind==="file"||k.kind==="directory")&&k.path===(d==null?void 0:d.path),onToggle:T=>{h({path:T,isDirectory:!0}),o(T)},onOpenFile:T=>{h({path:T,isDirectory:!1}),De(T)},onContextMenu:(T,F,H,re)=>p(T,F,H,re),onSubmitDraft:(T,F)=>void es(T,F),onCancelDraft:c,onDragStartRow:I,onDragEndRow:de,dropTarget:(k.kind==="file"||k.kind==="directory")&&k.path===q})},g.key):null})})]}),a.jsx(Vl,{})]}):a.jsx("div",{className:B.emptyState,children:"Connect to browse files"})}const cn={available:!1,branch:null,upstream:null,ahead:0,behind:0,detached:!1,conflictCount:0},ce=ke()(e=>({subscribedCwd:null,changes:[],...cn,setSubscribedCwd:t=>e({subscribedCwd:t}),applyProjection:t=>{if(!t||!t.available){e({changes:[],...cn});return}const n=[];for(const s of t.staged)n.push({path:s.path,status:s.indexStatus==="A"?"added":s.indexStatus==="D"?"deleted":"modified",staged:!0});for(const s of t.unstaged)n.push({path:s.path,status:s.worktreeStatus==="D"?"deleted":"modified",staged:!1});for(const s of t.untracked)n.push({path:s,status:"added",staged:!1});e({changes:n,available:!0,branch:t.branch,upstream:t.upstream,ahead:t.ahead,behind:t.behind,detached:t.detached,conflictCount:t.conflicted.length})}})),Jl="_list_10160_1",Ql="_summary_10160_4",Zl="_item_10160_11",ed="_badge_10160_23",td="_added_10160_30",nd="_modified_10160_34",sd="_deleted_10160_38",od="_name_10160_42",rd="_emptyState_10160_47",be={list:Jl,summary:Ql,item:Zl,badge:ed,added:td,modified:nd,deleted:sd,name:od,emptyState:rd},ad={added:"A",modified:"M",deleted:"D"};function id(){const t=E(r=>r.activeWorkspaceCwd)||"~",n=ce(r=>r.changes),s=E(r=>r.open);function o(r,i){s({id:Q.diff(r,i),kind:"diff",label:r.split("/").pop()||r,closable:!0,data:{path:r,staged:i},workspaceCwd:t})}return n.length===0?a.jsx("div",{className:be.emptyState,children:"No changes detected"}):a.jsxs("div",{className:be.list,children:[a.jsxs("div",{className:be.summary,children:[n.length," changed file",n.length===1?"":"s"]}),n.map((r,i)=>a.jsxs("div",{className:be.item,onClick:()=>o(r.path,r.staged),children:[a.jsx("span",{className:W(be.badge,be[r.status]),children:ad[r.status]}),a.jsx("span",{className:be.name,children:r.path})]},`${r.path}-${r.staged}-${i}`))]})}const cd="_wrap_3jeq6_1",ld="_tabBar_3jeq6_7",dd="_tabBtn_3jeq6_13",ud="_active_3jeq6_29",fd="_refreshBtn_3jeq6_33",pd="_content_3jeq6_37",he={wrap:cd,tabBar:ld,tabBtn:dd,active:ud,refreshBtn:fd,content:pd};function hd(){const e=j(c=>c.rightSidebarTab),t=j(c=>c.setRightSidebarTab),s=E(c=>c.activeWorkspaceCwd)||"~",o=M(c=>c.client),r=Me();function i(){r.invalidateQueries({queryKey:["explorer"]}),o&&s&&o.connection.request("checkout_refresh_request",{cwd:s}).catch(()=>{})}return a.jsxs("div",{className:he.wrap,children:[a.jsxs("div",{className:he.tabBar,children:[a.jsxs("button",{type:"button",className:W(he.tabBtn,e==="files"&&he.active),onClick:()=>t("files"),children:[a.jsx(Ne,{size:13}),"Files"]}),a.jsxs("button",{type:"button",className:W(he.tabBtn,e==="changes"&&he.active),onClick:()=>t("changes"),children:[a.jsx(_n,{size:13}),"Changes"]}),a.jsx(Y,{size:"xs",variant:"ghost",iconOnly:!0,title:"Refresh",className:he.refreshBtn,onClick:i,children:a.jsx(vs,{size:13})})]}),a.jsx("div",{className:he.content,children:e==="files"?a.jsx(Yl,{}):a.jsx(id,{})})]})}const Jn=ke()(e=>({bySession:{},setStats(t,n){e(s=>({bySession:{...s.bySession,[t]:{...s.bySession[t],...n}}}))},clear(t){e(n=>{const{[t]:s,...o}=n.bySession;return{bySession:o}})}})),md=12e3;function gd(e,t){return e==="running"&&t!=="running"}function ln(e,t){var s,o,r,i,c,d;const n={};((s=t.contextUsage)==null?void 0:s.tokens)!=null&&(n.contextTokens=t.contextUsage.tokens),((o=t.contextUsage)==null?void 0:o.contextWindow)!==void 0&&(n.contextWindow=t.contextUsage.contextWindow),((r=t.contextUsage)==null?void 0:r.percent)!=null&&(n.contextPercent=t.contextUsage.percent),((i=t.tokens)==null?void 0:i.total)!==void 0&&(n.totalTokens=t.tokens.total),((c=t.tokens)==null?void 0:c.input)!==void 0&&(n.inputTokens=t.tokens.input),((d=t.tokens)==null?void 0:d.output)!==void 0&&(n.outputTokens=t.tokens.output),t.cost!==void 0&&(n.cost=t.cost),t.model!==void 0&&(n.model=t.model,R.getState().setModel(e,t.model)),Jn.getState().setStats(e,n)}function _d(e){const t=M(c=>c.client),n=M(c=>c.status),s=R(c=>{var d;return e?((d=c.sessions[e])==null?void 0:d.agentId)??null:null}),o=R(c=>{var d;return e?(d=c.sessions[e])==null?void 0:d.status:void 0}),r=w.useRef(!1),i=w.useRef(void 0);w.useEffect(()=>{if(n!=="open"||!t||!e||!s)return;let c=!1;const d=async()=>{if(!r.current){r.current=!0;try{const m=await t.agent(s).sessionStats();c||ln(e,m)}catch{}finally{r.current=!1}}};d();const h=setInterval(()=>void d(),md);return()=>{c=!0,clearInterval(h)}},[n,t,e,s]),w.useEffect(()=>{const c=i.current;i.current=o,gd(c,o)&&(n!=="open"||!t||!e||!s||(r.current=!1,t.agent(s).sessionStats().then(d=>ln(e,d)).catch(()=>{})))},[o,n,t,e,s])}function yd(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="checkout_status_update"&&"cwd"in e&&typeof e.cwd=="string"&&"projection"in e&&typeof e.projection=="object"&&e.projection!==null}function wd(e){const t=M(r=>r.client),n=ce(r=>r.applyProjection),s=ce(r=>r.setSubscribedCwd),o=w.useRef(t);return o.current=t,w.useEffect(()=>{if(!t||!e)return;let r=!1;t.connection.request("checkout_status_subscribe",{cwd:e}).catch(()=>{}),s(e);const i=t.connection.onSessionMessage(c=>{if(r)return;const d=c;yd(d)&&d.cwd===e&&n(d.projection)});return t.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{}),()=>{r=!0,i(),t.connection.request("checkout_status_unsubscribe",{cwd:e}).catch(()=>{}),s(null)}},[t,e,n,s]),{refresh(){const r=o.current;!r||!e||r.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{})}}}const At="--";function ze(e){return e===void 0?At:e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function bd(e){if(e==null)return At;const t=e<=1?e*100:e;return`${Math.round(t)}%`}function xd(e){if(e===void 0)return At;const t=e<1?4:2;return`$${e.toFixed(t)}`}function Sd(e,t){return t?e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e:e}function vd(e,t){const n=[];return e>0&&n.push(`↑${e}`),t>0&&n.push(`↓${t}`),n.join(" ")}function kd(e,t=!0){const n=M(s=>s.client);return un({queryKey:me.providerModels(e),queryFn:async()=>{if(!n)throw new Error("not connected");return(await n.providers.listModels(e)).models},enabled:!!n&&!!e&&t})}function Id(e,t){if(t.trim()==="")return e;const n=t.toLowerCase();return e.filter(s=>s.label.toLowerCase().includes(n)||s.description!==void 0&&s.description.toLowerCase().includes(n))}function jd(e,t){if(!t)return e;const n=e.find(s=>s.id===t);return n?[n,...e.filter(s=>s.id!==t)]:e}function Cd(e){const t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const Td="_content_14c2k_4",Ed="_search_14c2k_17",Nd="_list_14c2k_35",Rd="_item_14c2k_40",Md="_itemActive_14c2k_54",qd="_checkSlot_14c2k_58",Bd="_label_14c2k_67",$d="_modelId_14c2k_73",Dd="_state_14c2k_80",Ad="_stateError_14c2k_89",Pd="_commandContent_14c2k_99",Od="_commandList_14c2k_102",Fd="_commandItem_14c2k_107",zd="_commandItemHeader_14c2k_140",Wd="_commandKindBadge_14c2k_154",Ld="_commandKindExtension_14c2k_173",Hd="_commandKindPrompt_14c2k_178",Ud="_commandKindSkill_14c2k_183",Kd="_commandDescription_14c2k_188",ie={content:Td,search:Ed,list:Nd,item:Rd,itemActive:Md,checkSlot:qd,label:Bd,modelId:$d,state:Dd,stateError:Ad,commandContent:Pd,commandList:Od,commandItem:Fd,commandItemHeader:zd,commandKindBadge:Wd,commandKindExtension:Ld,commandKindPrompt:Hd,commandKindSkill:Ud,commandDescription:Kd};function Vd({currentModel:e,provider:t,onSelect:n,renderTrigger:s}){const[o,r]=w.useState(!1),[i,c]=w.useState(""),d=w.useRef(null),{data:h=[],isLoading:m,isError:x,error:f}=kd(t,o),p=Cd(jd(h,e));w.useEffect(()=>{var C;o&&(c(""),(C=d.current)==null||C.focus())},[o]);const v=new Map(p.map(C=>[C.id,C.provider])),y=p.map(C=>({value:C.id,label:C.label??C.id,description:C.id})),_=Id(y,i),q=f instanceof Error?f.message:"Failed to load models";function K(C){C.stopPropagation(),C.key==="Escape"&&r(!1)}return a.jsxs(Ke,{open:o,onOpenChange:r,modal:!1,children:[a.jsx(Ve,{asChild:!0,children:s(e)}),a.jsx(Ge,{children:a.jsxs(Xe,{className:ie.content,align:"start",sideOffset:4,children:[a.jsx("input",{ref:d,className:ie.search,placeholder:"Search models…",value:i,onChange:C=>c(C.target.value),onKeyDown:K}),m&&a.jsx("div",{className:ie.state,children:a.jsx(Ln,{size:"sm"})}),!m&&x&&a.jsx("div",{className:ie.stateError,children:q}),!m&&!x&&_.length===0&&a.jsx("div",{className:ie.state,children:"No models found"}),!m&&!x&&_.length>0&&a.jsx("div",{className:ie.list,children:_.map(C=>a.jsxs(P,{className:ie.item,onSelect:()=>n(C.value,v.get(C.value)),children:[a.jsx("span",{className:ie.checkSlot,"aria-hidden":!0,children:C.value===e&&a.jsx(bn,{size:14})}),a.jsx("span",{className:ie.label,children:C.label}),a.jsxs("span",{className:ie.modelId,children:["(",C.value,")"]})]},C.value))})]})})]})}const Gd="_statusBar_1tlwk_1",Xd="_segmentGroup_1tlwk_16",Yd="_chevron_1tlwk_20",Jd="_segment_1tlwk_16",Qd="_icon_1tlwk_33",Zd="_modelSegment_1tlwk_39",eu="_modelChevron_1tlwk_63",tu="_text_1tlwk_74",se={statusBar:Gd,segmentGroup:Xd,chevron:Yd,segment:Jd,icon:Qd,modelSegment:Zd,modelChevron:eu,text:tu};function nu(){const e=R(_=>_.activeSessionId),t=R(_=>e?_.sessions[e]:void 0),n=M(_=>_.client),s=R(_=>_.setModel),o=ft(),r=E(_=>_.activeWorkspaceCwd);wd(r||"");const i=ce(_=>_.available),c=ce(_=>_.branch),d=ce(_=>_.ahead),h=ce(_=>_.behind),m=ce(_=>_.detached),x=ce(_=>_.conflictCount),f=ce(_=>_.changes.length),p=Jn(_=>e?_.bySession[e]:void 0);_d(e);const v=[];if(t){const _=Sd(t.cwd,o);v.push({key:"cwd",icon:a.jsx(Ne,{size:13}),text:_,title:t.cwd})}if(i){const _=vd(d,h),q=[m?"(detached)":c??"?"];_&&q.push(_),f>0&&q.push(`●${f}`),x>0&&q.push(`⚠${x}`),v.push({key:"branch",icon:a.jsx(ks,{size:13}),text:q.join(" ")})}if(t){const _=`${bd(p==null?void 0:p.contextPercent)} (${ze(p==null?void 0:p.contextTokens)}/${ze(p==null?void 0:p.contextWindow)})`;v.push({key:"context",icon:a.jsx(Is,{size:13}),text:_}),v.push({key:"tokens",icon:a.jsx(js,{size:13}),text:ze(p==null?void 0:p.totalTokens),title:`in ${ze(p==null?void 0:p.inputTokens)} / out ${ze(p==null?void 0:p.outputTokens)}`}),v.push({key:"cost",icon:a.jsx(Cs,{size:13}),text:xd(p==null?void 0:p.cost)})}function y(_,q){e&&(s(e,_,q),!(!n||!q)&&(async()=>{const K=await Fn(n,e);await n.agent(K).setModel(q,_)})().catch(()=>{}))}return a.jsxs("div",{className:se.statusBar,children:[t&&a.jsx("span",{className:se.segmentGroup,children:a.jsx(Vd,{currentModel:t.model,provider:"pi",onSelect:y,renderTrigger:_=>a.jsxs("button",{type:"button",className:se.modelSegment,disabled:!n,title:_?`Model: ${_}`:"Select model",children:[a.jsx("span",{className:se.icon,children:a.jsx(Ts,{size:13})}),a.jsx("span",{className:se.text,children:_??"Model"}),a.jsx(pn,{size:12,className:se.modelChevron,"aria-hidden":"true"})]})})}),v.map((_,q)=>a.jsxs("span",{className:se.segmentGroup,children:[(!!t||q>0)&&a.jsx(Rt,{size:12,className:se.chevron,"aria-hidden":"true"}),a.jsxs("span",{className:se.segment,title:_.title,children:[a.jsx("span",{className:se.icon,children:_.icon}),a.jsx("span",{className:se.text,children:_.text})]})]},_.key))]})}const su="_wrapper_oygyv_3",ou="_box_oygyv_18",ru="_checkmark_oygyv_38",au="_nativeInput_oygyv_43",st={wrapper:su,box:ou,checkmark:ru,nativeInput:au};w.forwardRef(function({label:t,checked:n=!1,disabled:s,className:o,onChange:r,...i},c){return a.jsxs("label",{className:st.wrapper,"data-disabled":s||void 0,children:[a.jsx("input",{ref:c,type:"checkbox",className:st.nativeInput,checked:n,disabled:s,onChange:r,...i}),a.jsx("span",{className:st.box,"data-checked":n,"aria-hidden":!0,children:n&&a.jsx(bn,{size:12,className:st.checkmark})}),t&&a.jsx("span",{children:t})]})});const iu="_select_1vd81_3",cu={select:iu};w.forwardRef(function({options:t,placeholder:n,className:s,...o},r){return a.jsxs("select",{ref:r,className:W(cu.select,s),...o,children:[n&&a.jsx("option",{value:"",disabled:!0,children:n}),t.map(i=>a.jsx("option",{value:i.value,children:i.label},i.value))]})});const lu="_overlay_1aujk_1",du="_contentWrapper_1aujk_7",uu="_dialog_1aujk_16",fu="_header_1aujk_28",pu="_title_1aujk_36",hu="_closeBtn_1aujk_43",mu="_body_1aujk_57",gu="_footer_1aujk_63",_u="_bare_1aujk_72",yu="_bareBody_1aujk_78",wu="_bareCloseBtn_1aujk_82",bu="_visuallyHidden_1aujk_101",Z={overlay:lu,contentWrapper:du,dialog:uu,header:fu,title:pu,closeBtn:hu,body:mu,footer:gu,bare:_u,bareBody:yu,bareCloseBtn:wu,visuallyHidden:bu},xu=St;function Su({open:e,onOpenChange:t,title:n,children:s,footer:o,width:r,className:i,bare:c=!1}){return a.jsx(Ns,{open:e,onOpenChange:t,children:a.jsxs(Rs,{children:[a.jsx(Ms,{className:Z.overlay}),a.jsx("div",{className:Z.contentWrapper,children:a.jsxs(qs,{className:W(Z.dialog,c&&Z.bare,i),style:r!==void 0?{width:r}:void 0,children:[c?a.jsx(zt,{className:Z.visuallyHidden,children:n}):a.jsxs("div",{className:Z.header,children:[a.jsx(zt,{className:Z.title,children:n}),a.jsx(St,{asChild:!0,children:a.jsx("button",{type:"button",className:Z.closeBtn,"aria-label":"Close",children:a.jsx(bt,{size:16})})})]}),a.jsx("div",{className:W(Z.body,c&&Z.bareBody),children:s}),c&&a.jsx(St,{asChild:!0,children:a.jsx("button",{type:"button",className:Z.bareCloseBtn,"aria-label":"Close",children:a.jsx(bt,{size:16})})}),o&&a.jsx("div",{className:Z.footer,children:o})]})})]})})}const vu="_handle_1ocv1_1",ku={handle:vu};function dn({side:e,onResize:t,className:n}){const s=w.useRef(0),o=w.useCallback(c=>{const d=c.clientX-s.current;s.current=c.clientX,t(e==="left"?d:-d)},[t,e]),r=w.useCallback(c=>{var d,h;window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),document.body.style.cursor="",document.body.style.userSelect="",(h=(d=c.target)==null?void 0:d.releasePointerCapture)==null||h.call(d,c.pointerId)},[o]);function i(c){c.preventDefault(),s.current=c.clientX,document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",o),window.addEventListener("pointerup",r)}return a.jsx("div",{className:W(ku.handle,n),onPointerDown:i,role:"separator","aria-orientation":"vertical"})}function Iu(e,t){const{order:n,sessions:s}=R.getState(),r=Dt(n,s,t).find(i=>i.cwd===e);if(r!=null&&r.sessions[0]){const i=r.sessions[0].id;R.getState().activate(i);const c=R.getState().sessions[i];E.getState().open({id:Q.chat(i),kind:"chat",label:(c==null?void 0:c.title)??"New chat",closable:!0,data:{sessionId:i},workspaceCwd:e})}else $t(e);j.getState().setCwd(e)}const ju="_pathRow_kzfmp_1",Cu="_pathInput_kzfmp_9",Tu="_createRow_kzfmp_13",Eu="_createInput_kzfmp_21",Nu="_createError_kzfmp_25",Ru="_list_kzfmp_30",Mu="_item_kzfmp_37",qu="_name_kzfmp_49",Bu="_emptyState_kzfmp_54",oe={pathRow:ju,pathInput:Cu,createRow:Tu,createInput:Eu,createError:Nu,list:Ru,item:Mu,name:qu,emptyState:Bu};function $u(){const e=j(I=>I.cwdPickerOpen),t=j(I=>I.closeCwdPicker),n=E(I=>I.activeWorkspaceCwd),s=j(I=>I.cwd),o=M(I=>I.client),r=ft(),[i,c]=w.useState("/"),[d,h]=w.useState("/"),[m,x]=w.useState(!1),[f,p]=w.useState(""),[v,y]=w.useState(null),[_,q]=w.useState(!1),K=Me();w.useEffect(()=>{if(!e)return;const I=qe(n||s||"~",r);c(I),h(I),le()},[e,o,n,s]);const{data:C,isLoading:$,isError:L,error:te}=Xc(i,e&&!!o),Ye=((C==null?void 0:C.entries)??[]).filter(I=>I.kind==="directory");function le(){x(!1),p(""),y(null)}function _e(I){const de=I.length>1?I.replace(/\/+$/,"")||"/":I;c(de),h(de),le()}function Be(){_e(i.split("/").slice(0,-1).join("/")||"/")}function ye(){_e(d.trim())}async function $e(){const I=f.trim();if(!(!I||!o||_)){q(!0),y(null);try{const de=await Yn(o,i,I,"directory");await K.invalidateQueries({queryKey:me.explorer(i)}),_e(de)}catch(de){y(de instanceof Error?de.message:"Failed to create folder")}finally{q(!1)}}}function De(){Iu(i,r),t()}return a.jsxs(Su,{open:e,onOpenChange:I=>!I&&t(),title:"Open Workspace",footer:a.jsxs(a.Fragment,{children:[a.jsx(xu,{asChild:!0,children:a.jsx(Y,{size:"sm",variant:"secondary",children:"Cancel"})}),a.jsx(Y,{size:"sm",onClick:De,children:"Open this folder"})]}),children:[a.jsxs("div",{className:oe.pathRow,children:[a.jsx(Y,{size:"xs",variant:"ghost",iconOnly:!0,title:"Up",onClick:Be,children:a.jsx(Es,{size:13})}),a.jsx(ct,{className:oe.pathInput,value:d,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),ye())}}),a.jsx(Y,{size:"xs",onClick:ye,children:"Go"}),a.jsx(Y,{size:"xs",variant:"ghost",iconOnly:!0,title:"New folder",disabled:!o||L||m,onClick:()=>{x(!0),p(""),y(null)},children:a.jsx(at,{size:13})})]}),m&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:oe.createRow,children:[a.jsx(Ne,{size:14}),a.jsx(ct,{className:oe.createInput,autoFocus:!0,placeholder:"New folder name",value:f,onChange:I=>p(I.target.value),onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),$e()):I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),le())}}),a.jsx(Y,{size:"xs",loading:_,disabled:!f.trim()||_,onClick:()=>void $e(),children:"Create"}),a.jsx(Y,{size:"xs",variant:"secondary",onClick:le,children:"Cancel"})]}),v&&a.jsx("div",{className:oe.createError,children:v})]}),a.jsx("div",{className:oe.list,children:$?a.jsx("div",{className:oe.emptyState,children:"Loading..."}):L?a.jsxs("div",{className:oe.emptyState,children:["Error: ",te instanceof Error?te.message:"unknown error"]}):Ye.length===0?a.jsx("div",{className:oe.emptyState,children:"No subdirectories"}):Ye.map(I=>a.jsxs("div",{className:oe.item,onClick:()=>_e(i==="/"?`/${I.name}`:`${i}/${I.name}`),children:[a.jsx(Ne,{size:14}),a.jsx("span",{className:oe.name,children:I.name})]},I.name))})]})}const Du="_shell_1ilqr_1",Au="_main_1ilqr_7",Pu="_sidebarLeft_1ilqr_13",Ou="_leftHandle_1ilqr_25",Fu="_center_1ilqr_28",zu="_sidebarRight_1ilqr_35",Wu="_rightHandle_1ilqr_43",xe={shell:Du,main:Au,sidebarLeft:Pu,leftHandle:Ou,center:Fu,sidebarRight:zu,rightHandle:Wu};function Lu(){const e=j(i=>i.leftSidebarCollapsed),t=j(i=>i.rightSidebarCollapsed),n=j(i=>i.leftSidebarWidth),s=j(i=>i.rightSidebarWidth),o=j(i=>i.resizeLeftSidebar),r=j(i=>i.resizeRightSidebar);return a.jsxs("div",{className:xe.shell,children:[a.jsx(pi,{}),a.jsxs("div",{className:xe.main,children:[!e&&a.jsxs("aside",{className:xe.sidebarLeft,style:{width:n},children:[a.jsx(gc,{}),a.jsx(dn,{side:"left",className:xe.leftHandle,onResize:o})]}),a.jsxs("div",{className:xe.center,children:[a.jsx(Nc,{}),a.jsx(Kc,{})]}),!t&&a.jsxs("aside",{className:xe.sidebarRight,style:{width:s},children:[a.jsx(dn,{side:"right",className:xe.rightHandle,onResize:r}),a.jsx(hd,{})]})]}),a.jsx(nu,{}),a.jsx($u,{})]})}function Hu(){const e=w.useRef(!1);w.useEffect(()=>{if(e.current)return;if(e.current=!0,window.location.hash.includes("offer=")){const d=window.location.href;j.getState().setHost(d),M.getState().connect({url:d});return}const t=new URLSearchParams(window.location.search),n=t.get("host"),s=t.get("pair"),o=t.get("password"),r=t.get("cwd"),i=t.get("connect")==="1",c=j.getState();if(s?c.setHost(s):n&&c.setHost(n),o&&c.setPassword(o),r&&c.setCwd(r),s)M.getState().connect({url:s});else if(i){const{host:d,password:h}=j.getState();M.getState().connect({url:d,password:h||void 0})}},[])}function Uu(e){return typeof e=="object"&&e!==null&&"kind"in e}function Ku(e){const t=[];for(const n of e)if(Uu(n))if(n.kind==="other")n.event&&t.push(n.event);else for(const s of n.events??[])t.push(s);return t}async function Vu(e){const t=[];let n=null;for(;;){const s=await e(n);if(s.items.length===0||(t.push(...Ku(s.items)),!s.hasNewer))return t;const o=s.endCursor;if(typeof o!="string"||o===n)return t;n=o}}function Gu(e){return typeof e.model=="string"}function Xu(){const e=M(s=>s.client),t=M(s=>s.status),n=w.useRef(!1);w.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,(async()=>{var x;let s=[];try{s=(await e.connection.request("list_agents_request",{all:!1})).agents??[]}catch{s=[]}s.sort((f,p)=>(p.lastActivity??0)-(f.lastActivity??0));const o=R.getState();for(const f of s){if(o.findByAgentId(f.agentId))continue;let p=jt;try{p=(await Vu(_=>e.agent(f.agentId).timeline.fetch({direction:"after",cursor:_??void 0,limit:200}))).reduce(On,jt)}catch{}const v=p.rows.length===0;o.hydrate({id:`s-${f.agentId.slice(0,12)}`,agentId:f.agentId,title:f.title||(v?"New chat":(x=f.cwd)==null?void 0:x.split("/").pop())||"Restored",status:f.status??"idle",cwd:f.cwd||"~",timeline:p,userMessageCount:p.rows.filter(y=>y.kind==="user").length,model:f.model,modelProvider:f.modelProvider})}const{order:r,sessions:i}=R.getState(),c=r.length>0?i[r[0]??""]:void 0;if(!c)return;const d=await ut(e).catch(()=>null),h=qe(c.cwd||"~",d),m=Dt(r,i,d);j.getState().setCollapsedWorkspaces(hc(m,h)),R.getState().activate(c.id),j.getState().setCwd(c.cwd),E.getState().open({id:Q.chat(c.id),kind:"chat",label:c.title,closable:!0,data:{sessionId:c.id},workspaceCwd:h})})())},[t,e]),w.useEffect(()=>{if(!(t!=="open"||!e))return e.onAgentUpdate(s=>{if(Gu(s)){const o=typeof s.modelProvider=="string"?s.modelProvider:void 0;R.getState().setModelByAgentId(s.agentId,s.model,o)}})},[t,e])}function Yu(){const e=M(s=>s.client),t=M(s=>s.status),n=w.useRef(!1);w.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,(async()=>{let s=[];try{s=(await e.connection.request("list_terminals_request",{})).terminals??[]}catch{s=[]}if(s.length===0)return;const o=await ut(e).catch(()=>null),r=E.getState().open;for(const i of s){if(i.closed)continue;const c=qe(i.cwd||"~",o);r({id:Q.terminal(i.slot),kind:"terminal",label:i.name,closable:!0,data:{slot:i.slot,cwd:c},workspaceCwd:c})}})())},[t,e])}function Ju(){w.useEffect(()=>{function e(t){const n=j.getState();if(t.key==="Escape"){n.closeCwdPicker(),n.closeSessionMenu();return}const s=t.ctrlKey||t.metaKey;if(s&&t.key.toLowerCase()==="t"){t.preventDefault(),zn(E.getState().activeWorkspaceCwd||"~");return}if(s&&t.key.toLowerCase()==="w"){const{activeTabId:o,tabs:r}=E.getState();if(!o)return;const i=r.find(c=>c.id===o);(i==null?void 0:i.closable)!==!1&&(t.preventDefault(),Ct(o))}}return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}function Qu(){return Hu(),Xu(),Yu(),Ju(),null}function Zu(){return a.jsxs(Bo,{children:[a.jsx(Qu,{}),a.jsx(Lu,{})]})}const Qn=document.getElementById("root");if(!Qn)throw new Error("Missing #root element");rs.createRoot(Qn).render(a.jsx(w.StrictMode,{children:a.jsx(Zu,{})}));export{Y as B,Su as D,Ln as S,df as T,mf as V,M as a,ft as b,hf as c,gf as d,Fn as e,Id as f,uf as g,E as h,it as i,ff as j,pf as k,sn as l,Q as m,qe as n,me as r,ie as s,hi as t,R as u};
3
- //# sourceMappingURL=index-CEP1cIKf.js.map