@av-pi-studio/web-client 0.0.74 → 0.0.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web/assets/{BinaryFallbackViewer-B1PBcT3N.js → BinaryFallbackViewer-BcXz7eRe.js} +2 -2
- package/dist/web/assets/{BinaryFallbackViewer-B1PBcT3N.js.map → BinaryFallbackViewer-BcXz7eRe.js.map} +1 -1
- package/dist/web/assets/ChatPanel-BGaHXRkd.js +3 -0
- package/dist/web/assets/ChatPanel-BGaHXRkd.js.map +1 -0
- package/dist/web/assets/ChatPanel-BSD-8ded.css +1 -0
- package/dist/web/assets/{CodeView-_wBYU-zK.js → CodeView-BwpO1rFh.js} +2 -2
- package/dist/web/assets/{CodeView-_wBYU-zK.js.map → CodeView-BwpO1rFh.js.map} +1 -1
- package/dist/web/assets/{FilePanel-CqiLosrb.js → FilePanel-Cg9NsETY.js} +2 -2
- package/dist/web/assets/{FilePanel-CqiLosrb.js.map → FilePanel-Cg9NsETY.js.map} +1 -1
- package/dist/web/assets/{ImageViewer-WToUsK2Y.js → ImageViewer-BJp-etHM.js} +2 -2
- package/dist/web/assets/{ImageViewer-WToUsK2Y.js.map → ImageViewer-BJp-etHM.js.map} +1 -1
- package/dist/web/assets/{MarkdownFileViewer-Do69vE6s.js → MarkdownFileViewer-BzB1d4TY.js} +2 -2
- package/dist/web/assets/{MarkdownFileViewer-Do69vE6s.js.map → MarkdownFileViewer-BzB1d4TY.js.map} +1 -1
- package/dist/web/assets/{MoleculeViewerPanel-CKaIka-k.js → MoleculeViewerPanel-DrXqIoI5.js} +2 -2
- package/dist/web/assets/{MoleculeViewerPanel-CKaIka-k.js.map → MoleculeViewerPanel-DrXqIoI5.js.map} +1 -1
- package/dist/web/assets/{TerminalPanel-B7ujFxCG.js → TerminalPanel-CqbvRBBr.js} +2 -2
- package/dist/web/assets/{TerminalPanel-B7ujFxCG.js.map → TerminalPanel-CqbvRBBr.js.map} +1 -1
- package/dist/web/assets/{TextViewer-CJGwYjCh.js → TextViewer-Bd-xuyEa.js} +2 -2
- package/dist/web/assets/{TextViewer-CJGwYjCh.js.map → TextViewer-Bd-xuyEa.js.map} +1 -1
- package/dist/web/assets/{VideoViewer-CYXPkYLV.js → VideoViewer-q6x3q8Rf.js} +2 -2
- package/dist/web/assets/{VideoViewer-CYXPkYLV.js.map → VideoViewer-q6x3q8Rf.js.map} +1 -1
- package/dist/web/assets/index-CO_ZzVSZ.js +18 -0
- package/dist/web/assets/index-CO_ZzVSZ.js.map +1 -0
- package/dist/web/assets/index-D5SH-IYM.css +1 -0
- package/dist/web/assets/{markdown-q0cxuHgm.js → markdown-DZVzjFwV.js} +2 -2
- package/dist/web/assets/{markdown-q0cxuHgm.js.map → markdown-DZVzjFwV.js.map} +1 -1
- package/dist/web/assets/{use-file-download-BCG_kqpD.js → use-file-download-f9giWuuK.js} +2 -2
- package/dist/web/assets/{use-file-download-BCG_kqpD.js.map → use-file-download-f9giWuuK.js.map} +1 -1
- package/dist/web/assets/{use-file-watch-CZgwolg7.js → use-file-watch-CR6oYkRD.js} +2 -2
- package/dist/web/assets/{use-file-watch-CZgwolg7.js.map → use-file-watch-CR6oYkRD.js.map} +1 -1
- package/dist/web/assets/{vendor-icons-DDiHMdgo.js → vendor-icons-4MWXLMX2.js} +51 -66
- package/dist/web/assets/vendor-icons-4MWXLMX2.js.map +1 -0
- package/dist/web/index.html +3 -3
- package/package.json +3 -3
- package/dist/web/assets/ChatPanel-DuiC5ipg.js +0 -3
- package/dist/web/assets/ChatPanel-DuiC5ipg.js.map +0 -1
- package/dist/web/assets/ChatPanel-qE6vr3IJ.css +0 -1
- package/dist/web/assets/index-BLK6SFvN.css +0 -1
- package/dist/web/assets/index-Cz7AgOgN.js +0 -18
- package/dist/web/assets/index-Cz7AgOgN.js.map +0 -1
- package/dist/web/assets/vendor-icons-DDiHMdgo.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TextViewer-CJGwYjCh.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 { Panel } from \"@pi-studio-ui/components/primitives/Panel.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.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 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 <EmptyState>\n <Spinner size=\"sm\" /> Loading...\n </EmptyState>\n );\n case \"inline\":\n return <CodeView path={path} content={state.content} />;\n case \"streaming\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Streaming {formatMegabytes(state.size)} file...\n </EmptyState>\n );\n case \"stream-error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n case \"streamed\":\n return (\n <Panel>\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 </Panel>\n );\n case \"too-large\": {\n const name = path.split(\"/\").pop() || path;\n return (\n <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 </EmptyState>\n );\n }\n case \"error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\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","EmptyState","jsx","Spinner","CodeView","Panel","jsxs","textStyles","name","Button"],"mappings":"0eA4BO,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,+FC7CaG,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,cACGI,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,aAAA,EACvB,EAEJ,IAAK,SACH,OAAOD,EAAAA,IAACE,EAAA,CAAS,KAAA7B,EAAY,QAASsB,EAAM,QAAS,EACvD,IAAK,YACH,cACGI,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,cAAYhB,EAAgBU,EAAM,IAAI,EAAE,UAAA,EAC/D,EAEJ,IAAK,eACH,cAAQI,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,EAC3C,IAAK,WACH,cACGQ,EAAA,CACC,SAAA,CAAAC,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,KAAO,SAAA,CAAApB,EAAgBU,EAAM,IAAI,EAAE,gBAAA,EAAc,EAC5EK,EAAAA,IAAC,MAAA,CAAI,UAAWK,EAAW,KACzB,SAAAL,EAAAA,IAACE,EAAA,CAAS,KAAA7B,EAAY,QAASsB,EAAM,OAAA,CAAS,CAAA,CAChD,CAAA,EACF,EAEJ,IAAK,YAAa,CAChB,MAAMW,EAAOjC,EAAK,MAAM,GAAG,EAAE,OAASA,EACtC,aACG0B,EAAA,CACC,SAAAK,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,SACzB,SAAA,CAAAD,OAAC,MAAA,CACE,SAAA,CAAAnB,EAAgBU,EAAM,IAAI,EAAE,8CAA4C,IACxEV,EAAgBU,EAAM,eAAe,EAAE,IAAA,EAC1C,EACCA,EAAM,YACLK,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EACjBN,EAAM,kBACP,IAAA,CAAE,KAAMA,EAAM,YAAa,SAAUA,EAAM,cAAgBW,EAC1D,SAAAN,MAACO,EAAA,CAAO,KAAK,KAAK,SAAA,WAAA,CAAS,EAC7B,EAEAP,EAAAA,IAACO,EAAA,CAAO,KAAK,KAAK,QAAS,IAAMd,EAAqB,EAAI,EAAG,SAAA,UAAA,CAE7D,CAAA,CAAA,CAEJ,CAAA,CACF,CAEJ,CACA,IAAK,QACH,cAAQM,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,CAAA,CAE/C"}
|
|
1
|
+
{"version":3,"file":"TextViewer-Bd-xuyEa.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 { Panel } from \"@pi-studio-ui/components/primitives/Panel.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.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 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 <EmptyState>\n <Spinner size=\"sm\" /> Loading...\n </EmptyState>\n );\n case \"inline\":\n return <CodeView path={path} content={state.content} />;\n case \"streaming\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Streaming {formatMegabytes(state.size)} file...\n </EmptyState>\n );\n case \"stream-error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n case \"streamed\":\n return (\n <Panel>\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 </Panel>\n );\n case \"too-large\": {\n const name = path.split(\"/\").pop() || path;\n return (\n <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 </EmptyState>\n );\n }\n case \"error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\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","EmptyState","jsx","Spinner","CodeView","Panel","jsxs","textStyles","name","Button"],"mappings":"0eA4BO,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,+FC7CaG,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,cACGI,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,aAAA,EACvB,EAEJ,IAAK,SACH,OAAOD,EAAAA,IAACE,EAAA,CAAS,KAAA7B,EAAY,QAASsB,EAAM,QAAS,EACvD,IAAK,YACH,cACGI,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,cAAYhB,EAAgBU,EAAM,IAAI,EAAE,UAAA,EAC/D,EAEJ,IAAK,eACH,cAAQI,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,EAC3C,IAAK,WACH,cACGQ,EAAA,CACC,SAAA,CAAAC,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,KAAO,SAAA,CAAApB,EAAgBU,EAAM,IAAI,EAAE,gBAAA,EAAc,EAC5EK,EAAAA,IAAC,MAAA,CAAI,UAAWK,EAAW,KACzB,SAAAL,EAAAA,IAACE,EAAA,CAAS,KAAA7B,EAAY,QAASsB,EAAM,OAAA,CAAS,CAAA,CAChD,CAAA,EACF,EAEJ,IAAK,YAAa,CAChB,MAAMW,EAAOjC,EAAK,MAAM,GAAG,EAAE,OAASA,EACtC,aACG0B,EAAA,CACC,SAAAK,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,SACzB,SAAA,CAAAD,OAAC,MAAA,CACE,SAAA,CAAAnB,EAAgBU,EAAM,IAAI,EAAE,8CAA4C,IACxEV,EAAgBU,EAAM,eAAe,EAAE,IAAA,EAC1C,EACCA,EAAM,YACLK,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EACjBN,EAAM,kBACP,IAAA,CAAE,KAAMA,EAAM,YAAa,SAAUA,EAAM,cAAgBW,EAC1D,SAAAN,MAACO,EAAA,CAAO,KAAK,KAAK,SAAA,WAAA,CAAS,EAC7B,EAEAP,EAAAA,IAACO,EAAA,CAAO,KAAK,KAAK,QAAS,IAAMd,EAAqB,EAAI,EAAG,SAAA,UAAA,CAE7D,CAAA,CAAA,CAEJ,CAAA,CACF,CAEJ,CACA,IAAK,QACH,cAAQM,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,CAAA,CAE/C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{j as o}from"./vendor-react-Uv3j2inr.js";import{E as e,S as t}from"./index-
|
|
2
|
-
//# sourceMappingURL=VideoViewer-
|
|
1
|
+
import{j as o}from"./vendor-react-Uv3j2inr.js";import{E as e,S as t}from"./index-CO_ZzVSZ.js";import{u as n}from"./use-file-download-f9giWuuK.js";import"./vendor-query-NxjRJKdp.js";import"./vendor-BLc7PaxD.js";import"./vendor-markdown-DtEbK_xy.js";import"./vendor-highlight-CJuJYF7f.js";import"./vendor-icons-4MWXLMX2.js";import"./vendor-overlays-Ki1AFMsh.js";import"./vendor-dnd-Bvh3agTi.js";const a="_wrap_gy3e6_1",m="_video_gy3e6_10",i={wrap:a,video:m};function E({path:s}){const r=n(s);return r.isLoading?o.jsxs(e,{children:[o.jsx(t,{size:"sm"})," Loading video..."]}):r.isError?o.jsxs(e,{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{E as VideoViewer};
|
|
2
|
+
//# sourceMappingURL=VideoViewer-q6x3q8Rf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VideoViewer-
|
|
1
|
+
{"version":3,"file":"VideoViewer-q6x3q8Rf.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 { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\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 <EmptyState>\n <Spinner size=\"sm\" /> Loading video...\n </EmptyState>\n );\n }\n if (query.isError) {\n return (\n <EmptyState>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </EmptyState>\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","EmptyState","jsx","Spinner","styles"],"mappings":"wcAYO,SAASA,EAAY,CAAE,KAAAC,GAAqB,CACjD,MAAMC,EAAQC,EAAgBF,CAAI,EAElC,OAAIC,EAAM,iBAELE,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,mBAAA,EACvB,EAGAJ,EAAM,eAELE,EAAA,CAAW,SAAA,CAAA,UACFF,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,WAGR,MAAA,CAAI,UAAWK,EAAO,KAErB,eAAC,QAAA,CAAM,UAAWA,EAAO,MAAO,IAAKL,EAAM,KAAK,UAAW,SAAQ,GAAC,EACtE,EANsB,IAQ1B"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatPanel-BGaHXRkd.js","assets/vendor-react-Uv3j2inr.js","assets/vendor-query-NxjRJKdp.js","assets/vendor-icons-4MWXLMX2.js","assets/markdown-DZVzjFwV.js","assets/vendor-highlight-CJuJYF7f.js","assets/vendor-markdown-DtEbK_xy.js","assets/vendor-BLc7PaxD.js","assets/markdown-zMTuCbxl.css","assets/StatusBadge-DggMFuW_.js","assets/StatusBadge-DmrnYEhp.css","assets/DiffView-dzXC51QP.js","assets/DiffView-CUctPSBA.css","assets/vendor-overlays-Ki1AFMsh.js","assets/vendor-dnd-Bvh3agTi.js","assets/ChatPanel-BSD-8ded.css","assets/FilePanel-Cg9NsETY.js","assets/use-file-watch-CR6oYkRD.js","assets/FilePanel-bWuYWz8t.css","assets/TerminalPanel-CqbvRBBr.js","assets/vendor-terminal-BhzX2_ts.js","assets/vendor-terminal-DYP7pi_n.css","assets/TerminalPanel-DoDBqfAg.css","assets/MoleculeViewerPanel-DrXqIoI5.js","assets/vendor-molviewer-B2jrWzvr.js","assets/vendor-molviewer-Bychyqid.css","assets/use-file-download-f9giWuuK.js","assets/MoleculeViewerPanel-CHZ8q0jD.css","assets/TextViewer-Bd-xuyEa.js","assets/CodeView-BwpO1rFh.js","assets/CodeView-Bbd7h9aM.css","assets/TextViewer-C7Vnqw_v.css","assets/MarkdownFileViewer-BzB1d4TY.js","assets/MarkdownFileViewer-BOOIyc8-.css","assets/ImageViewer-BJp-etHM.js","assets/ImageViewer-Bh1rkSDM.css","assets/VideoViewer-q6x3q8Rf.js","assets/VideoViewer-CCmuaDLl.css","assets/BinaryFallbackViewer-BcXz7eRe.js","assets/BinaryFallbackViewer-ClYyn4IS.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var vr=Object.defineProperty;var xr=(e,t,n)=>t in e?vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>xr(e,typeof t!="symbol"?t+"":t,n);import{r as b,j as c,c as Sr}from"./vendor-react-Uv3j2inr.js";import{Q as kr,a as Ir,u as jr,b as Tr,c as We,d as Cr}from"./vendor-query-NxjRJKdp.js";import{A as d,B as g,C as W,D as rs,E as F,F as Re,G as ye,H as O,I as x,J,K as U,L as xt,M as ze,N as xe}from"./vendor-BLc7PaxD.js";import{L as Er,P as Rr,a as Mr,b as Nr,c as Pr,E as Qt,d as os,S as Dr,A as Ar,T as Zt,C as en,e as $r,F as qr,f as is,g as as,h as tn,i as cs,G as ls,j as ds,M as us,X as Ot,k as Br,R as Or,l as Me,m as nn,n as zt,o as yt,p as ct,q as zr,D as Fr,U as Wr,r as Lr,s as Hr,t as Ur,u as Vr,v as Kr,w as Gr,x as Yr}from"./vendor-icons-4MWXLMX2.js";import{P as Xr,C as Jr,I as Qr,S as Zr,R as St,T as kt,D as eo,a as to,b as no,c as so,d as bn,e as Ft}from"./vendor-overlays-Ki1AFMsh.js";import{u as ro,a as oo,p as io,P as ao,b as fs,S as co,h as lo,c as uo,C as fo,D as po,d as ho}from"./vendor-dnd-Bvh3agTi.js";import{_ as we}from"./vendor-highlight-CJuJYF7f.js";import"./vendor-markdown-DtEbK_xy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();const mo=new kr;function ps(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 go(e){return Math.max(0,Math.min(255,Math.round(e)))}function yo({r:e,g:t,b:n}){const s=r=>go(r).toString(16).padStart(2,"0");return`#${s(e)}${s(t)}${s(n)}`}function _o(e){const{r:t,g:n,b:s}=ps(e),r=o=>{const i=o/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4};return .2126*r(t)+.7152*r(n)+.0722*r(s)}function sn(e,t="#18181b",n="#ffffff"){return _o(e)>.45?t:n}function wo(e,t){const{r:n,g:s,b:r}=ps(e),o=Math.max(0,Math.min(1,t));return yo({r:n+(255-n)*o,g:s+(255-s)*o,b:r+(255-r)*o})}function lt(e){const t=e.trim().replace(/^#/,"");return(t.length===3||t.length===6)&&!/[^0-9a-fA-F]/.test(t)}const pe=(e,t,n,s,r,o,i,a,l,u,f)=>({50:e,100:t,200:n,300:s,400:r,500:o,600:i,700:a,800:l,900:u,950:f}),S={zinc:pe("#fafafa","#f4f4f5","#e4e4e7","#d4d4d8","#a1a1aa","#71717a","#52525b","#3f3f46","#27272a","#18181b","#09090b"),gray:pe("#f9fafb","#f3f4f6","#e5e7eb","#d1d5db","#9ca3af","#6b7280","#4b5563","#374151","#1f2937","#111827","#030712"),slate:pe("#f8fafc","#f1f5f9","#e2e8f0","#cbd5e1","#94a3b8","#64748b","#475569","#334155","#1e293b","#0f172a","#020617"),blue:pe("#eff6ff","#dbeafe","#bfdbfe","#93c5fd","#60a5fa","#3b82f6","#2563eb","#1d4ed8","#1e40af","#1e3a8a","#172554"),green:pe("#f0fdf4","#dcfce7","#bbf7d0","#86efac","#4ade80","#22c55e","#16a34a","#15803d","#166534","#14532d","#052e16"),red:pe("#fef2f2","#fee2e2","#fecaca","#fca5a5","#f87171","#ef4444","#dc2626","#b91c1c","#991b1b","#7f1d1d","#450a0a"),teal:pe("#f0fdfa","#ccfbf1","#99f6e4","#5eead4","#2dd4bf","#14b8a6","#0d9488","#0f766e","#115e59","#134e4a","#042f2e"),amber:pe("#fffbeb","#fef3c7","#fde68a","#fcd34d","#fbbf24","#f59e0b","#d97706","#b45309","#92400e","#78350f","#451a03"),yellow:pe("#fefce8","#fef9c3","#fef08a","#fde047","#facc15","#eab308","#ca8a04","#a16207","#854d0e","#713f12","#422006"),purple:pe("#faf5ff","#f3e8ff","#e9d5ff","#d8b4fe","#c084fc","#a855f7","#9333ea","#7e22ce","#6b21a8","#581c87","#3b0764"),orange:pe("#fff7ed","#ffedd5","#fed7aa","#fdba74","#fb923c","#f97316","#ea580c","#c2410c","#9a3412","#7c2d12","#431407"),white:"#ffffff",black:"#000000"},bo={statusSuccess:"#16a34a",statusDanger:"#dc2626",statusWarning:"#f59e0b",statusMerged:"#9333ea"},vo={statusSuccess:"#15803d",statusDanger:"#b91c1c",statusWarning:"#d97706",statusMerged:"#7c3aed"};function xo(){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 So(){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 hs(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 Le(e){const t=S.zinc[50],n=sn(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,...bo,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:xo(),terminal:hs(e.surface0,t,e.accent)}}function ko(){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:sn(t),destructive:"#b04138",destructiveForeground:"#ffffff",success:t,successForeground:"#ffffff",border:"#e4e4e7",borderAccent:"#ececf1",...vo,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:So(),terminal:{...hs("#ffffff",e,t),selectionBackground:"rgba(0,0,0,0.15)",white:"#ffffff",brightWhite:"#fafafa"}}}const Io={light:"#ffffff",dark:"#3b62b0",zinc:"#808080",midnight:"#4A6BA8",claude:"#D97757",ghostty:"#8caaee"},ms=["light","dark","zinc","midnight","claude","ghostty"];function jo(e){if(e==="light")return ko();switch(e){case"dark":return Le({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 Le({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 Le({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 Le({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 Le({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 gs={};for(const e of ms){const t=e==="light"?"light":"dark";gs[e]={name:e,colorScheme:t,colors:jo(e),swatch:Io[e]}}const To=gs,Co={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,10:10,12:12,14:14,16:16,20:20,24:24,30:30,32:32,48:48,64:64,80:80,96:96,128:128},_t={"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},Eo={normal:"400",medium:"500",semibold:"600",bold:"700"},Ro={none:0,sm:2,base:4,md:6,lg:8,xl:12,"2xl":16,full:9999},Mo={0:0,1:1,2:2},No={0:0,50:.5,100:1},Po={xs:12,sm:14,md:16,lg:20},Do={diff:22},ys='system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',_s='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';function Ao(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 ws(e){const t=To[e];return{name:e,colorScheme:t.colorScheme,colors:t.colors,spacing:Co,fontSize:{..._t},fontFamily:{ui:ys,mono:_s},lineHeight:{...Do},iconSize:Po,fontWeight:Eo,borderRadius:Ro,borderWidth:Mo,opacity:No,shadow:Ao(t.colorScheme),swatch:t.swatch}}const $o=_t.base,qo=10,Bo=24;function Oo(e,t){const n=t.themeName??e.name,s=ws(n),r=t.uiFont&&t.uiFont.trim()!==""?t.uiFont:ys,o=t.monoFont&&t.monoFont.trim()!==""?t.monoFont:_s,i={...s.fontSize};if(t.fontSize!=null){const l=Math.max(qo,Math.min(Bo,t.fontSize))/$o;for(const u of Object.keys(_t))i[u]=Math.round(_t[u]*l)}return{...s,fontSize:i,fontFamily:{ui:r,mono:o}}}function zo(e){return ws(e)}const Fo="dark",Wo=16;function Lo(e){const t=e/Wo;return`${Number(t.toFixed(4))}rem`}function Ho(e){const t={};Uo(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}`]=Lo(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 r=s;t[`--pi-shadow-${n}`]=`${r.offsetX}px ${r.offsetY}px ${r.radius}px ${r.color}`}return t["--pi-color-scheme"]=e.colorScheme,t}function Uo(e,t){const{palette:n,syntax:s,terminal:r,...o}=e;for(const[i,a]of Object.entries(o))typeof a=="string"&&(t[`--pi-color-${i}`]=a);s&&Vo(s,t),r&&(t["--pi-terminal-bg"]=r.background,t["--pi-terminal-fg"]=r.foreground)}function Vo(e,t){for(const[n,s]of Object.entries(e))typeof s=="string"&&(t[`--syntax-${Ko(n)}`]=s)}function Ko(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function Go(e){if(typeof document>"u")return;const t=document.documentElement.style;for(const[s,r]of Object.entries(e))t.setProperty(s,r);const n=e["--pi-color-scheme"];n&&document.documentElement.style.setProperty("color-scheme",n)}function Yo(e){const t=Ho(e);Go(t)}const He=d().min(1,"Asset path must not be empty"),Xo=g({accent:d().refine(lt,{message:"accent must be a valid #rrggbb hex color"}),accentBright:d().refine(lt,{message:"accentBright must be a valid #rrggbb hex color"}).optional(),accentForeground:d().refine(lt,{message:"accentForeground must be a valid #rrggbb hex color"}).optional(),swatch:d().refine(lt,{message:"swatch must be a valid #rrggbb hex color"}).optional()}),Jo=g({logoLight:He,logoDark:He,logoMark:He.optional(),icon:He,splash:He.optional()}),Qo=g({docs:d().url().optional(),support:d().url().optional(),issues:d().url().optional(),website:d().url().optional()}).optional(),Zo=g({copyright:d().optional(),companyName:d().optional()}).optional();g({productName:d().min(1,"productName is required"),shortName:d().optional(),tagline:d().optional(),colors:Xo,assets:Jo,links:Qo,legal:Zo});function ei(e){const t=e.accent,n=e.accentBright??wo(t,.35),s=e.accentForeground??sn(t),r=e.swatch??t;return{accent:t,accentBright:n,accentForeground:s,swatch:r}}function ti(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 vn="pi-studio-appearance";function ni(e,t){let n=a(e),s=null;function r(f){return f==="system"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":f}function o(f,m){const h=r(f),p=zo(h);let w=Oo(p,{...m,themeName:h});if(t!=null&&t.colors){const y=ei(t.colors);w=ti(w,y)}return w}function i(){const f=JSON.stringify({mode:n.mode,settings:n.settings});e.set(vn,f)}function a(f){const m=f.get(vn);let h=Fo,p={};if(m)try{const y=JSON.parse(m);y.mode&&(ms.includes(y.mode)||y.mode==="system")&&(h=y.mode),y.settings&&typeof y.settings=="object"&&(p=y.settings)}catch{}const w=o(h,p);return{mode:h,settings:p,resolvedTheme:w}}function l(){n={...n,resolvedTheme:o(n.mode,n.settings)},i()}const u={getState(){return n},setMode(f){n={...n,mode:f},l(),u.apply()},updateSettings(f){n={...n,settings:{...n.settings,...f}},l(),u.apply()},apply(){Yo(n.resolvedTheme)},listen(){if(typeof window>"u")return()=>{};const f=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{n.mode==="system"&&(l(),u.apply())};return f.addEventListener("change",m),s=()=>f.removeEventListener("change",m),s}};return u}function si({store:e,brandConfig:t,children:n}){const s=b.useRef(null);return s.current||(s.current=ni(e,t),s.current.apply()),b.useEffect(()=>s.current.listen(),[]),c.jsx(c.Fragment,{children:n})}const rn={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 ri({children:e}){return c.jsx(si,{store:rn,children:c.jsx(Ir,{client:mo,children:e})})}const oi="_btn_1oc6k_4",ii="_secondary_1oc6k_47",ai="_outline_1oc6k_56",ci="_ghost_1oc6k_65",li="_destructive_1oc6k_75",di="_iconOnly_1oc6k_85",ui="_loadingSpinner_1oc6k_92",fi="_piSpin_1oc6k_1",dt={btn:oi,default:"_default_1oc6k_38",secondary:ii,outline:ai,ghost:ci,destructive:li,iconOnly:di,loadingSpinner:ui,piSpin:fi},xn={xs:28,sm:32,md:36,lg:40},pi={xs:12,sm:14,md:16,lg:20},Sn={xs:8,sm:10,md:12,lg:16},hi={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 mi(e){const{disabled:t,loading:n}=e;return t||n?{opacity:.5,isGhostHover:!1}:{opacity:1,isGhostHover:!1}}function se({variant:e="default",size:t="md",loading:n=!1,disabled:s=!1,leftIcon:r,trailing:o,iconOnly:i=!1,children:a,style:l,className:u,...f}){const{opacity:m}=mi({disabled:s??!1,loading:n}),h=s||n,p=pi[t];return c.jsxs("button",{className:W(dt.btn,dt[e],i&&dt.iconOnly,u),disabled:h,"aria-busy":n||void 0,style:{minHeight:xn[t],paddingLeft:i?void 0:Sn[t],paddingRight:i?void 0:Sn[t],fontSize:hi[t],opacity:m,...i?{width:xn[t]}:{},...l},...f,children:[n?c.jsx(Er,{className:dt.loadingSpinner,size:p,"aria-hidden":!0}):r?c.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:r}):null,a,o&&!n&&c.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:o})]})}const gi="_input_756jo_3",yi="_textarea_756jo_32",Wt={input:gi,textarea:yi},wt=b.forwardRef(function({className:t,...n},s){return c.jsx("input",{ref:s,className:W(Wt.input,t),...n})}),Bh=b.forwardRef(function({className:t,...n},s){return c.jsx("textarea",{ref:s,className:W(Wt.input,Wt.textarea,t),...n})}),bs=d().datetime({offset:!0});d().uuid();d().regex(/^[A-Za-z0-9_-]+$/,"expected base64url");const et=rs([F(),bs]),_i=Re(["mobile","browser","cli","mcp"]),wi=g({type:x("hello"),clientId:d(),clientType:_i,protocolVersion:F(),appVersion:d().optional(),capabilities:ye(d(),O()).optional()}),bi=g({status:x("server_info"),serverId:d(),hostname:d().optional(),version:d().optional(),capabilities:ye(d(),J()),features:ye(d(),J())}),vi=g({type:x("status"),payload:bi}),xi=g({type:x("ping"),requestId:d(),clientSentAt:et.optional()}),Si=g({type:x("pong"),requestId:d(),clientSentAt:et.optional(),serverReceivedAt:et,serverSentAt:et}),vs=Re(["initializing","idle","running","error","closed"]),It=g({mimeType:d().optional(),data:d().optional()}).passthrough(),ki=g({prs:U(J()).optional(),issues:U(J()).optional()}).passthrough(),Ii=g({provider:d(),cwd:d(),modeId:d().optional(),model:d().optional(),modelProvider:d().optional(),thinkingOptionId:d().optional(),featureValues:ye(d(),J()).optional(),title:d().nullable().optional(),approvalPolicy:d().optional(),sandboxMode:d().optional(),networkAccess:O().optional(),webSearch:O().optional(),extra:g({pi:J().optional()}).passthrough().optional(),systemPrompt:d().optional(),mcpServers:ye(d(),J()).optional()}),ji=g({type:x("create_agent_request"),requestId:d(),config:Ii,env:ye(d(),d()).optional(),workspaceId:d().optional(),worktreeName:d().optional(),initialPrompt:d().optional(),clientMessageId:d().optional(),outputSchema:ye(d(),J()).optional(),images:U(It).optional(),attachments:ki.optional(),git:J().optional(),worktree:J().optional(),autoArchive:O().optional(),labels:ye(d(),d()).default({})}),Ti=g({type:x("create_agent_response"),requestId:d(),payload:g({agentId:d()}).passthrough()}),Ci=g({type:x("agent_update"),agentId:d(),status:vs.optional(),title:d().nullable().optional(),labels:ye(d(),d()).optional()}),Ei=g({type:x("agent_status"),agentId:d(),status:vs}),Ri=g({type:x("agent_list"),agents:U(g({id:d()}).passthrough())}),Mi=g({type:x("agent_deleted"),agentId:d()}),Ni=g({type:x("agent_archived"),agentId:d(),archivedAt:bs.optional()}),xs=xt("kind",[g({kind:x("shell"),command:d().optional(),output:d().optional()}),g({kind:x("read"),path:d().optional(),output:d().optional()}),g({kind:x("edit"),path:d().optional(),diff:d().optional(),output:d().optional()}),g({kind:x("write"),path:d().optional(),output:d().optional()}),g({kind:x("search"),query:d().optional(),output:d().optional()}),g({kind:x("fetch"),url:d().optional(),output:d().optional()}),g({kind:x("task"),description:d().optional(),output:d().optional()})]),Pi=xt("kind",[g({kind:x("user_message"),messageId:d().optional(),text:d().optional(),images:U(It).optional()}),g({kind:x("assistant_message"),messageId:d().optional(),text:d().optional(),final:O().optional()}),g({kind:x("reasoning"),text:d().optional(),final:O().optional()}),g({kind:x("tool_call"),callId:d().optional(),tool:xs,status:d().optional()}),g({kind:x("turn_started"),turnId:d().optional()}),g({kind:x("turn_completed"),turnId:d().optional()}),g({kind:x("turn_failed"),turnId:d().optional(),error:d().optional()}),g({kind:x("turn_canceled"),turnId:d().optional()}),g({kind:x("error"),message:d().optional()}),g({kind:x("queue_update"),steering:U(d()).optional(),followUp:U(d()).optional()})]),Di=g({type:x("agent_stream"),agentId:d(),seq:F().optional(),timestamp:et.optional(),event:Pi}),Ai=Re(["before","after"]),$i=g({start:F(),end:F()}),qi=g({type:x("fetch_agent_timeline_request"),requestId:d(),agentId:d(),cursor:d().nullable().optional(),direction:Ai,limit:F().optional()}),Bi=g({type:x("fetch_agent_timeline_response"),requestId:d(),agentId:d().optional(),items:U(J()),seqStart:F(),seqEnd:F(),sourceSeqRanges:U($i),collapsed:O(),hasNewer:O(),startCursor:d().nullable().optional(),endCursor:d().nullable().optional()}),Oi=g({type:x("agent_permission_request"),requestId:d(),agentId:d(),toolName:d().optional(),tool:xs.optional(),action:J().optional(),responses:U(d()).optional()}),zi=g({type:x("agent_permission_resolved"),requestId:d(),agentId:d(),decision:d().optional()}),Fi=g({type:x("agent.permission.respond.request"),requestId:d(),permissionRequestId:d(),response:J()}),Wi=g({type:x("agent.permission.respond.response"),requestId:d(),payload:g({resolved:O()}).passthrough()}),Li=g({type:x("respond_to_permission"),requestId:d(),permissionRequestId:d(),response:J()}),Ss=Re(["conversation","files","both"]),Hi=g({type:x("agent.rewind.request"),requestId:d(),agentId:d(),messageId:d(),mode:Ss}).passthrough(),Ui=g({type:x("agent.rewind.response"),requestId:d(),payload:g({agentId:d(),messageId:d(),mode:Ss,truncatedAt:d().optional()}).passthrough()}).passthrough(),Vi=g({input:F().optional(),output:F().optional(),cacheRead:F().optional(),cacheWrite:F().optional(),total:F().optional()}).passthrough(),Ki=g({tokens:F().nullable().optional(),contextWindow:F().optional(),percent:F().nullable().optional()}).passthrough(),Gi=g({type:x("agent_session_stats_request"),requestId:d(),agentId:d()}).passthrough(),Yi=g({type:x("agent_session_stats_response"),requestId:d(),payload:g({sessionId:d().optional(),sessionFile:d().optional(),userMessages:F().optional(),assistantMessages:F().optional(),toolCalls:F().optional(),toolResults:F().optional(),totalMessages:F().optional(),tokens:Vi.optional(),cost:F().optional(),contextUsage:Ki.optional(),model:d().optional()}).passthrough()}).passthrough(),Xi=g({type:x("agent_compact_request"),requestId:d(),agentId:d(),customInstructions:d().optional()}).passthrough(),Ji=g({type:x("agent_compact_response"),requestId:d(),payload:g({summary:d().optional(),firstKeptEntryId:d().optional(),tokensBefore:F().optional(),details:J().optional()}).passthrough()}).passthrough(),Qi=g({type:x("agent_new_session_request"),requestId:d(),agentId:d()}).passthrough(),Zi=g({type:x("agent_new_session_response"),requestId:d(),payload:g({cancelled:O()}).passthrough()}).passthrough(),ea=g({type:x("agent_switch_session_request"),requestId:d(),agentId:d(),sessionPath:d()}).passthrough(),ta=g({type:x("agent_switch_session_response"),requestId:d(),payload:g({cancelled:O()}).passthrough()}).passthrough(),na=g({type:x("agent_fork_request"),requestId:d(),agentId:d(),entryId:d()}).passthrough(),sa=g({type:x("agent_fork_response"),requestId:d(),payload:g({text:d(),cancelled:O()}).passthrough()}).passthrough(),ra=g({type:x("agent_fork_messages_request"),requestId:d(),agentId:d()}).passthrough(),oa=g({type:x("agent_fork_messages_response"),requestId:d(),payload:g({messages:U(g({entryId:d(),text:d()}).passthrough())}).passthrough()}).passthrough(),ia=g({type:x("agent_clone_request"),requestId:d(),agentId:d()}).passthrough(),aa=g({type:x("agent_clone_response"),requestId:d(),payload:g({cancelled:O()}).passthrough()}).passthrough(),ca=g({type:x("agent_set_session_name_request"),requestId:d(),agentId:d(),name:d()}).passthrough(),la=g({type:x("agent_set_session_name_response"),requestId:d(),payload:g({}).passthrough().optional()}).passthrough(),da=g({type:x("agent_export_html_request"),requestId:d(),agentId:d(),outputPath:d().optional()}).passthrough(),ua=g({type:x("agent_export_html_response"),requestId:d(),payload:g({path:d()}).passthrough()}).passthrough(),fa=g({type:x("agent_set_model_request"),requestId:d(),agentId:d(),provider:d(),modelId:d()}).passthrough(),pa=g({type:x("agent_set_model_response"),requestId:d(),payload:g({}).passthrough()}).passthrough(),ha=g({type:x("agent_cycle_model_request"),requestId:d(),agentId:d()}).passthrough(),ma=g({type:x("agent_cycle_model_response"),requestId:d(),payload:g({model:J().nullable().optional(),thinkingLevel:d().optional(),isScoped:O().optional()}).passthrough()}).passthrough(),ga=g({type:x("agent_last_assistant_text_request"),requestId:d(),agentId:d()}).passthrough(),ya=g({type:x("agent_last_assistant_text_response"),requestId:d(),payload:g({text:d().nullable()}).passthrough()}).passthrough(),_a=g({type:x("steer_agent_request"),requestId:d(),agentId:d(),message:d(),images:U(It).optional(),clientMessageId:d().optional()}).passthrough(),wa=g({type:x("steer_agent_response"),requestId:d(),agentId:d(),ok:O()}).passthrough(),ba=g({type:x("follow_up_agent_request"),requestId:d(),agentId:d(),message:d(),images:U(It).optional(),clientMessageId:d().optional()}).passthrough(),va=g({type:x("follow_up_agent_response"),requestId:d(),agentId:d(),ok:O()}).passthrough(),xa=g({name:d(),id:d().optional(),description:d().optional(),source:Re(["extension","prompt","skill"]).optional(),scope:Re(["user","project","temporary"]).optional(),path:d().optional()}).passthrough(),Sa=g({type:x("agent_list_commands_request"),requestId:d(),agentId:d()}).passthrough(),ka=g({type:x("agent_list_commands_response"),requestId:d(),payload:g({commands:U(xa)}).passthrough()}).passthrough(),Ia=g({source:d(),identity:d(),addedIn:d(),deprecated:O().optional(),status:d(),lastError:g({at:d(),attempts:F(),reason:d(),message:d()}).passthrough().optional()}).passthrough(),ks=g({id:d(),title:d(),description:d(),packages:U(Ia)}).passthrough(),ja=g({identity:d(),source:d(),pack:d(),reason:d(),message:d()}).passthrough(),Ta=g({at:d(),outcome:d(),installed:U(d()),failures:U(ja)}).passthrough(),Is=g({at:d(),outcome:d()}).passthrough(),Ca=g({type:x("extension_packs_list_request"),requestId:d()}).passthrough(),Ea=g({type:x("extension_packs_list_response"),requestId:d(),autoSync:O(),selected:U(d()),packs:U(ks),lastSync:Is.optional()}).passthrough(),Ra=g({type:x("extension_packs_set_request"),requestId:d(),packs:U(d()).optional()}).passthrough(),Ma=g({type:x("extension_packs_set_response"),requestId:d(),autoSync:O(),selected:U(d()),packs:U(ks),lastSync:Is.optional(),ok:O(),error:d().optional(),report:Ta.optional()}).passthrough(),Na=g({type:x("rpc_error"),requestId:d(),code:d().optional(),message:d().optional(),error:d().optional()}),Pa=xt("type",[ji,Ti,Ci,Ei,Ri,Mi,Ni,Di,qi,Bi,Oi,zi,Fi,Wi,Li,Hi,Ui,Gi,Yi,Xi,Ji,Qi,Zi,ea,ta,na,sa,ra,oa,ia,aa,ca,la,da,ua,fa,pa,ha,ma,ga,ya,_a,wa,ba,va,Sa,ka,Ca,Ea,Ra,Ma,Na]),Da=g({type:d()}).passthrough(),Aa=g({type:x("session"),message:rs([Pa,Da])});xt("type",[wi,vi,xi,Si,Aa]);const kn={inline_image_markdown:"inline_image_markdown",file_link_markdown:"file_link_markdown"},$e={Output:1,Input:2,Resize:3,Snapshot:4,Restore:5},$a=Object.fromEntries(Object.entries($e).map(([e,t])=>[t,e])),js=g({rows:F().int().nonnegative(),cols:F().int().nonnegative()});class Ye extends Error{constructor(t){super(t),this.name="TerminalFrameError"}}const qa=new TextEncoder,Ba=new TextDecoder;function Oa(e){if(!Number.isInteger(e)||e<0||e>255)throw new Ye(`slot must be an integer 0–255, got ${e}`)}function Ue(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function Oh(e){switch(Oa(e.slot),e.opcode){case"Output":return Ue($e.Output,e.slot,e.data);case"Input":return Ue($e.Input,e.slot,e.data);case"Snapshot":return Ue($e.Snapshot,e.slot,e.data);case"Restore":return Ue($e.Restore,e.slot,e.data);case"Resize":{const t=JSON.stringify(js.parse({rows:e.rows,cols:e.cols}));return Ue($e.Resize,e.slot,qa.encode(t))}}}function za(e){if(e.length<2)throw new Ye(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=$a[t];if(!s)throw new Ye(`unknown terminal opcode 0x${t.toString(16)}`);const r=e.subarray(2);if(s==="Resize"){let o;try{o=JSON.parse(Ba.decode(r))}catch{throw new Ye("resize payload is not valid JSON")}const i=js.safeParse(o);if(!i.success)throw new Ye("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:r.slice()}}const Oe={Begin:16,Chunk:17,End:18,Error:19},Fa=Object.fromEntries(Object.entries(Oe).map(([e,t])=>[t,e])),Ts=g({transferId:d(),fileName:d().optional(),mimeType:d().optional(),totalBytes:F().int().nonnegative().optional()});class Xe extends Error{constructor(t){super(t),this.name="FileTransferFrameError"}}const In=new TextEncoder,jn=new TextDecoder;function Wa(e){if(!Number.isInteger(e)||e<0||e>255)throw new Xe(`stream must be an integer 0–255, got ${e}`)}function ut(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function Mt(e){switch(Wa(e.stream),e.opcode){case"Begin":return ut(Oe.Begin,e.stream,In.encode(JSON.stringify(Ts.parse(e.meta))));case"Chunk":return ut(Oe.Chunk,e.stream,e.data);case"End":return ut(Oe.End,e.stream,new Uint8Array([e.ok?1:0]));case"Error":return ut(Oe.Error,e.stream,In.encode(e.message))}}function La(e){if(e.length<2)throw new Xe(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=Fa[t];if(!s)throw new Xe(`unknown file-transfer opcode 0x${t.toString(16)}`);const r=e.subarray(2);switch(s){case"Begin":{let o;try{o=JSON.parse(jn.decode(r))}catch{throw new Xe("begin payload is not valid JSON")}const i=Ts.safeParse(o);if(!i.success)throw new Xe("begin payload is not a valid transfer header");return{opcode:"Begin",stream:n,meta:i.data}}case"Chunk":return{opcode:"Chunk",stream:n,data:r.slice()};case"End":return{opcode:"End",stream:n,ok:(r[0]??1)!==0};case"Error":return{opcode:"Error",stream:n,message:jn.decode(r)}}}function Ha(e){try{return La(e)}catch{return null}}const qe=256;function Ua(e,t=0){const n=(t%qe+qe)%qe;for(let s=0;s<qe;s++){const r=(n+s)%qe;if(!e.has(r))return r}return null}const Va=d().regex(/^[a-z][a-z0-9-]*$/,"invalid provider id"),Ka=Re(["safe","moderate","dangerous","planning"]),Ga=g({supportsStreaming:O(),supportsSessionPersistence:O(),supportsDynamicModes:O(),supportsMcpServers:O(),supportsReasoningStream:O(),supportsToolInvocations:O(),supportsRewindConversation:O().optional(),supportsRewindFiles:O().optional(),supportsRewindBoth:O().optional(),supportsSteering:O().optional()}).passthrough(),Ya=g({id:d(),label:d().optional(),description:d().optional(),icon:d().optional(),colorTier:Ka});g({id:Va,label:d(),description:d().optional(),extends:d().optional(),modes:U(Ya),capabilities:Ga});function Lt(e){return typeof e=="string"?e:e instanceof Uint8Array||Buffer.isBuffer(e)?e.toString("utf8"):String(e??"")}function Cs(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((r,o)=>{const i=e??(()=>new WebSocket(s));try{t=e?i(s):new WebSocket(s),t.binaryType="arraybuffer"}catch(a){o(a);return}t.onopen=()=>r(),t.onerror=a=>{var l;(t==null?void 0:t.readyState)!==1&&o(a),(l=n.onError)==null||l.call(n,a)},t.onclose=a=>{var l;(l=n.onClose)==null||l.call(n,a.code,Lt(a.reason))},t.onmessage=a=>{var u,f,m,h;const{data:l}=a;l instanceof ArrayBuffer||l instanceof Uint8Array?(u=n.onMessage)==null||u.call(n,l):typeof l=="string"?(f=n.onMessage)==null||f.call(n,l):typeof Blob<"u"&&l instanceof Blob?(m=n.onMessage)==null||m.call(n,l):Buffer.isBuffer(l)&&((h=n.onMessage)==null||h.call(n,l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)))}})},sendText(s){t==null||t.send(s)},sendBinary(s){t==null||t.send(s)},close(s=1e3,r=""){t==null||t.close(s,r),t=null}};return n}const Je="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Es(e){let t="";for(let n=0;n<e.length;n+=3){const s=e[n],r=n+1<e.length,o=n+2<e.length,i=r?e[n+1]:0,a=o?e[n+2]:0;t+=Je[s>>2],t+=Je[(s&3)<<4|i>>4],t+=r?Je[(i&15)<<2|a>>6]:"=",t+=o?Je[a&63]:"="}return t}function Rs(e){const t=e.replace(/=+$/,""),n=[];let s=0,r=0;for(const o of t){const i=Je.indexOf(o);if(i===-1)throw new Error(`invalid base64 character: ${JSON.stringify(o)}`);s=s<<6|i,r+=6,r>=8&&(r-=8,n.push(s>>r&255))}return new Uint8Array(n)}function Xa(e){try{const t=JSON.parse(e);return!t||typeof t.type!="string"?null:t}catch{return null}}const mt=24;function Ms(e,t){const n=ze.randomBytes(mt),s=ze.box.after(e,n,t),r=new Uint8Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),Es(r)}function Ns(e,t){let n;try{n=Rs(e)}catch{return null}if(n.length<mt)return null;const s=n.slice(0,mt),r=n.slice(mt);return ze.box.open.after(r,s,t)}function Ja(e,t){return Ms(new TextEncoder().encode(e),t)}function Qa(e,t){const n=Ns(e,t);return n?new TextDecoder().decode(n):null}function Za(e,t,n,s,r,o){let i=!1;return n.onClose(a=>{var l;i=!0,(l=s.onClose)==null||l.call(s,a)}),{handleAppFrame(a){var f,m;if(i)return;const l=r();if(!o()||!l)return;const u=Qa(a.frame,l);if(u===null){(f=s.onAuthError)==null||f.call(s,new Error(`relay ${e} channel: message failed authentication`));return}(m=s.onMessage)==null||m.call(s,u)},handleBinaryFrame(a){var f,m;if(i)return;const l=r();if(!o()||!l)return;const u=Ns(a.frame,l);if(u===null){(f=s.onAuthError)==null||f.call(s,new Error(`relay ${e} channel: binary message failed authentication`));return}(m=s.onBinaryMessage)==null||m.call(s,u)},send(a){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const l=r();if(!o()||!l)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_app",frame:Ja(a,l)}))},sendBinary(a){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const l=r();if(!o()||!l)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_bin",frame:Ms(a,l)}))},close(){i||(i=!0,n.close())}}}function ec(e){const{transport:t,attachment:n,daemonPublicKey:s}=e,r=e.events??{},o=ze.box.keyPair(),i=ze.box.before(s,o.secretKey);let a=!1;const l=Za("client",n,t,r,()=>i,()=>a);return t.onMessage(u=>{var m;const f=Xa(u);if(f){if(f.type==="e2ee_ready"){if(a)return;a=!0,(m=r.onReady)==null||m.call(r);return}if(f.type==="e2ee_app"){l.handleAppFrame(f);return}f.type==="e2ee_bin"&&l.handleBinaryFrame(f)}}),t.send(JSON.stringify({type:"e2ee_hello",ephemeralPublicKey:Es(o.publicKey)})),{role:"client",attachment:n,get ready(){return a},send:l.send,sendBinary:l.sendBinary,close:l.close}}const tc=16;function nc(e){const t=ze.hash(e);let n="";for(let s=0;s<tc;s++)n+=t[s].toString(16).padStart(2,"0");return n}function sc(e){const t=e.useTls?"wss":"ws",n=e.endpoint.replace(/^(?:https?|wss?):\/\//,"").replace(/\/+$/,"");return`${t}://${n}`}function rc(e){let t=null,n=null;const s=e.sessionId??nc(e.daemonPublicKey),r={onMessage:null,onClose:null,onError:null,get isOpen(){return t!==null&&t.readyState===1&&n!==null&&n.ready},connect(o){return new Promise((i,a)=>{const l=e.factory??(()=>new WebSocket(o));try{t=e.factory?l(o):new WebSocket(o)}catch(h){a(h);return}const u=t,f=[],m=[];u.onopen=()=>{u.send(JSON.stringify({type:"relay_register",sessionId:s})),n=ec({transport:{send:h=>u.send(h),onMessage:h=>f.push(h),onClose:h=>m.push(h),close:()=>u.close()},attachment:{sessionId:s},daemonPublicKey:e.daemonPublicKey,events:{onReady:()=>i(),onMessage:h=>{var p;return(p=r.onMessage)==null?void 0:p.call(r,h)},onBinaryMessage:h=>{var p;return(p=r.onMessage)==null?void 0:p.call(r,h.slice().buffer)},onAuthError:h=>{var p;return(p=r.onError)==null?void 0:p.call(r,h)}}})},u.onerror=h=>{var p;u.readyState!==1&&a(h),(p=r.onError)==null||p.call(r,h)},u.onclose=h=>{var p;for(const w of m)w(Lt(h.reason));(p=r.onClose)==null||p.call(r,h.code,Lt(h.reason))},u.onmessage=h=>{const{data:p}=h;if(typeof p=="string")for(const w of f)w(p)}})},sendText(o){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.send(o)},sendBinary(o){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.sendBinary(o)},close(o=1e3,i=""){n==null||n.close(),n=null,t==null||t.close(o,i),t=null}};return r}function oc(e){const t=e.indexOf("#"),n=t===-1?e:e.slice(t+1),s=new URLSearchParams(n),r=s.get("offer");if(!r)return null;let o;try{o=Rs(r)}catch{return null}const i=s.get("relay");if(i){const l={endpoint:i,useTls:s.get("relayTls")==="1"};return{publicKeyB64:r,publicKey:o,relay:l}}const a=s.get("host")??void 0;return{publicKeyB64:r,publicKey:o,...a?{host:a}:{}}}const ic=1;function Ht(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}class ac extends Error{constructor(t,n,s){super(t),this.requestId=n,this.code=s,this.name="RpcError"}}class Tn extends Error{constructor(t){super(`RPC ${t} timed out`),this.requestId=t,this.name="RpcTimeoutError"}}class cc{constructor(t){A(this,"transport");A(this,"rpcTimeoutMs");A(this,"now");A(this,"_state","idle");A(this,"_serverId",null);A(this,"_features",{});A(this,"_serverCapabilities",{});A(this,"pending",new Map);A(this,"sessionHandlers",new Set);A(this,"terminalHandlers",new Set);A(this,"fileTransferHandlers",new Set);A(this,"stateHandlers",new Set);A(this,"helloResolve",null);A(this,"helloReject",null);this.options=t,this.transport=t.transport??Cs(),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,r)=>{this.helloResolve=s,this.helloReject=r});this.transport.sendText(JSON.stringify({type:"hello",clientId:this.options.clientId,clientType:this.options.clientType,protocolVersion:this.options.protocolVersion??ic,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 r=n.requestId??Ht();return new Promise((o,i)=>{const a=s??this.rpcTimeoutMs,l=a>0?setTimeout(()=>{this.pending.delete(r),i(new Tn(r))},a):null;this.pending.set(r,{resolve:u=>o(u),reject:i,timer:l}),this.sendSession({type:t,...n,requestId:r})})}sendSession(t){this.transport.sendText(JSON.stringify({type:"session",message:t}))}sendBinary(t){this.transport.sendBinary(t)}ping(t=1e4){const n=Ht();return new Promise((s,r)=>{const o=t>0?setTimeout(()=>{this.pending.delete(n),r(new Tn(n))},t):null;this.pending.set(n,{resolve:()=>s(),reject:r,timer:o}),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(Oe).includes(n)){const o=Ha(t);if(!o)return;for(const i of this.fileTransferHandlers)i(o);return}const r=za(t);for(const o of this.terminalHandlers)o(r)}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 ac(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 lc{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 uc(this.daemon,t)}workspace(t){return new fc(this.daemon,t)}get providers(){return new pc(this.daemon)}listExtensionPacks(){return this.daemon.request("extension_packs_list_request",{})}setExtensionPacks(t,n){return this.daemon.request("extension_packs_set_request",{packs:t},n==null?void 0:n.timeoutMs)}syncExtensionPacks(t){return this.daemon.request("extension_packs_set_request",{},t==null?void 0:t.timeoutMs)}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 dc{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 uc{constructor(t,n){A(this,"timeline");this.daemon=t,this.agentId=n,this.timeline=new dc(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 fc{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 pc{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 Cn=32*1024,hc="invalid_or_expired_token";function mc(e){const t=e.reduce((r,o)=>r+o.length,0),n=new Uint8Array(t);let s=0;for(const r of e)n.set(r,s),s+=r.length;return n}class gc{constructor(t){A(this,"pending",new Map);A(this,"streamCursor",1);A(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!==hc)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=Ua(this.pending,this.streamCursor);if(s===null)throw new Error("no free download stream");this.streamCursor=(s+1)%qe;const r=new Promise((i,a)=>{this.pending.set(s,{chunks:[],meta:{},resolve:i,reject:a})});let o;try{o=await this.daemon.request("file_download_request",{token:n.token,stream:s})}catch(i){throw this.pending.delete(s),i}if(!o.ok)throw this.pending.delete(s),new Error(o.error??"download request failed");return r}async upload(t,n){const s=Ht(),r=await this.daemon.request("file_upload_request",{path:t,transferId:s});if(!r.ok||r.stream===void 0)throw new Error(r.error??"upload request failed");const o=r.stream;this.daemon.sendBinary(Mt({opcode:"Begin",stream:o,meta:{transferId:s}}));for(let i=0;i<n.length;i+=Cn){const a=n.subarray(i,i+Cn);this.daemon.sendBinary(Mt({opcode:"Chunk",stream:o,data:a}))}this.daemon.sendBinary(Mt({opcode:"End",stream:o,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:mc(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 yc{constructor(t,n={}){A(this,"initialDelayMs");A(this,"maxDelayMs");A(this,"factor");A(this,"jitter");A(this,"maxAttempts");A(this,"setTimer");A(this,"clearTimer");A(this,"random");A(this,"attempt",0);A(this,"timer",null);A(this,"active",!1);A(this,"reconnecting",!1);A(this,"detachState",null);A(this,"reconnectedHandlers",new Set);A(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,r)=>setTimeout(s,r)),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}reconnectNow(){this.active&&(this.reconnecting||this.daemon.state==="closed"&&(this.timer&&(this.clearTimer(this.timer),this.timer=null),this.attempt=0,this.tryReconnect()))}get attemptCount(){return this.attempt}scheduleReconnect(){if(!this.active||this.timer||this.attempt>=this.maxAttempts)return;this.attempt+=1;const t=this.delayForAttempt(this.attempt);this.timer=this.setTimer(()=>{this.timer=null,!this.reconnecting&&this.tryReconnect()},t)}async tryReconnect(){if(!this.active||this.reconnecting)return;this.reconnecting=!0;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()}finally{this.reconnecting=!1}}}function En(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(),r=t.slice(n[0].length).replace(/\/+$/,"");switch(s){case"http":return`ws://${r}`;case"https":return`wss://${r}`;case"ws":case"wss":return`${s}://${r}`;default:return t}}function _c(e){const t=oc(e);return t!=null&&t.relay?{mode:"relay",url:sc(t.relay),daemonPublicKey:t.publicKey}:t!=null&&t.host?{mode:"direct",url:En(t.host)}:{mode:"direct",url:En(e)}}const wc=`
|
|
3
|
+
const pending = new Set();
|
|
4
|
+
self.onmessage = (e) => {
|
|
5
|
+
const msg = e.data;
|
|
6
|
+
if (msg.cancel) {
|
|
7
|
+
pending.delete(msg.id);
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
pending.add(msg.id);
|
|
11
|
+
setTimeout(() => {
|
|
12
|
+
if (!pending.has(msg.id)) return; // cancelled before it fired
|
|
13
|
+
pending.delete(msg.id);
|
|
14
|
+
self.postMessage({ id: msg.id });
|
|
15
|
+
}, msg.ms);
|
|
16
|
+
};
|
|
17
|
+
`;function bc(){return{setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)}}function vc(){const e=new Blob([wc],{type:"application/javascript"}),t=URL.createObjectURL(e),n=new Worker(t);URL.revokeObjectURL(t);const s=new Map;let r=1;return n.addEventListener("message",o=>{const i=s.get(o.data.id);s.delete(o.data.id),i==null||i()}),{setTimer:(o,i)=>{const a=r++;return s.set(a,o),n.postMessage({id:a,ms:i}),a},clearTimer:o=>{const i=o;s.delete(i)&&n.postMessage({id:i,cancel:!0})}}}let Ve=null;function Rn(){if(Ve)return Ve;try{Ve=vc()}catch{Ve=bc()}return Ve}function xc(){return{setTimer:(e,t)=>Rn().setTimer(e,t),clearTimer:e=>Rn().clearTimer(e)}}const Sc=32,ie=new Map;function kc(){for(;ie.size>Sc;){let e=null;for(const[t,n]of ie)if(n.refs===0&&n.entry){URL.revokeObjectURL(n.entry.objectUrl),e=t;break}if(e===null)return;ie.delete(e)}}function zh(e,t){const n=ie.get(e);if(n)return n.refs+=1,ie.delete(e),ie.set(e,n),n.entry?Promise.resolve(n.entry):n.pending;const s={refs:1,entry:null,pending:null};return ie.set(e,s),kc(),s.pending=t(e).then(r=>{const o=new Blob([Uint8Array.from(r.bytes)],{type:r.mimeType||"application/octet-stream"}),i={objectUrl:URL.createObjectURL(o),mimeType:r.mimeType};return ie.get(e)===s?(s.entry=i,s.pending=null):URL.revokeObjectURL(i.objectUrl),i}).catch(r=>{throw ie.get(e)===s&&ie.delete(e),r}),s.pending}function Fh(e){const t=ie.get(e);t&&(t.refs=Math.max(0,t.refs-1))}function Ic(){for(const e of ie.values())e.entry&&URL.revokeObjectURL(e.entry.objectUrl);ie.clear()}function jc(){return"web-"+Math.random().toString(36).slice(2,10)}const $=xe()((e,t)=>({status:"idle",serverInfo:null,error:null,daemon:null,client:null,reconnection:null,async connect(n){t().disconnect();const s=_c(n.url);let r;s.mode==="relay"?r=rc({daemonPublicKey:s.daemonPublicKey}):n.password&&(r=Cs(f=>new WebSocket(f,[`pi-studio.bearer.${n.password}`])));const o=new cc({url:s.url,clientId:n.clientId??jc(),clientType:"browser",capabilities:{[kn.inline_image_markdown]:!0,[kn.file_link_markdown]:!0},transport:r,rpcTimeoutMs:1800*1e3}),i=new lc(o),{setTimer:a,clearTimer:l}=xc(),u=new yc(o,{setTimer:a,clearTimer:l});o.onStateChange(f=>e({status:f})),u.onReconnected(()=>e({error:null})),u.onReconnectFailed(f=>{e({error:f instanceof Error?f.message:String(f)})}),e({daemon:o,client:i,reconnection:u,error:null,status:"connecting"});try{const f=await o.connect();e({serverInfo:f}),u.start()}catch(f){throw e({error:f instanceof Error?f.message:String(f)}),f}},disconnect(){const{daemon:n,reconnection:s}=t();s==null||s.stop(),n==null||n.close(),Ic(),e({status:"idle",serverInfo:null,daemon:null,client:null,reconnection:null})}})),Tc=100,Cc=480,Ec=220,Rc=280;function ft(e){return Math.min(Cc,Math.max(Tc,e))}const E=xe()(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:Ec,rightSidebarWidth:Rc,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,r,o)=>e({fileMenu:{path:t,isDirectory:n,x:s,y:r,background:o}}),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:ft(t)}),setRightSidebarWidth:t=>e({rightSidebarWidth:ft(t)}),resizeLeftSidebar:t=>e(n=>({leftSidebarWidth:ft(n.leftSidebarWidth+t)})),resizeRightSidebar:t=>e(n=>({rightSidebarWidth:ft(n.rightSidebarWidth+t)}))})),Mc="_wrap_aquqo_1",Nc="_dot_aquqo_8",Pc="_open_aquqo_15",Dc="_connecting_aquqo_18",Ac="_closed_aquqo_21",$c="_idle_aquqo_22",qc="_closing_aquqo_23",Nt={wrap:Mc,dot:Nc,open:Pc,connecting:Dc,closed:Ac,idle:$c,closing:qc},Bc={idle:"disconnected",connecting:"connecting…",open:"connected",closing:"disconnecting…",closed:"disconnected"};function Oc(){const e=$(n=>n.status),t=$(n=>n.error);return c.jsxs("span",{className:Nt.wrap,title:t??void 0,children:[c.jsx("span",{className:W(Nt.dot,Nt[e])}),Bc[e]??e]})}const zc="_toolbar_1lcb1_1",Fc="_brand_1lcb1_10",Wc="_version_1lcb1_16",Lc="_sep_1lcb1_22",Hc="_host_1lcb1_28",Uc="_password_1lcb1_31",Vc="_sidebarToggles_1lcb1_34",ke={toolbar:zc,brand:Fc,version:Wc,sep:Lc,host:Hc,password:Uc,sidebarToggles:Vc};function Kc(){const e=$(h=>h.status),t=$(h=>h.connect),n=$(h=>h.disconnect),s=E(h=>h.host),r=E(h=>h.setHost),o=E(h=>h.password),i=E(h=>h.setPassword),a=E(h=>h.leftSidebarCollapsed),l=E(h=>h.toggleLeftSidebar),u=E(h=>h.rightSidebarCollapsed),f=E(h=>h.toggleRightSidebar),m=e==="open"||e==="connecting";return c.jsxs("div",{className:ke.toolbar,children:[c.jsx("span",{className:ke.brand,children:"Pi-Studio"}),c.jsxs("span",{className:ke.version,children:["v","0.0.75"]}),c.jsx(Oc,{}),c.jsx("div",{className:ke.sep}),c.jsx(wt,{className:ke.host,value:s,onChange:h=>r(h.target.value),placeholder:"host:port, ws://…/http://…, or a pasted pairing link",disabled:m}),c.jsx(wt,{className:ke.password,type:"password",value:o,onChange:h=>i(h.target.value),placeholder:"password",disabled:m}),e==="open"||e==="connecting"||e==="closing"?c.jsx(se,{size:"sm",onClick:()=>n(),children:"Disconnect"}):c.jsx(se,{size:"sm",variant:"default",onClick:()=>void t({url:s,password:o||void 0}),children:"Connect"}),c.jsxs("div",{className:ke.sidebarToggles,children:[c.jsx(se,{size:"sm",variant:"ghost",iconOnly:!0,title:a?"Show sessions sidebar":"Hide sessions sidebar",onClick:()=>l(),children:a?c.jsx(Rr,{size:16}):c.jsx(Mr,{size:16})}),c.jsx(se,{size:"sm",variant:"ghost",iconOnly:!0,title:u?"Show files/changes sidebar":"Hide files/changes sidebar",onClick:()=>f(),children:u?c.jsx(Nr,{size:16}):c.jsx(Pr,{size:16})})]})]})}const Ut={rows:[],streamingAssistantIndex:null,streamingReasoningIndex:null,toolIndexByCallId:{}};let Mn=0;function Se(){return Mn+=1,`row-${Mn}`}function Gc(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 Yc(e,t){return e??`${t.kind}:${Gc(t)}`}function Fe(e,t){if(t===null)return;const n=e[t];n&&(n.kind!=="assistant"&&n.kind!=="reasoning"||n.streaming&&(e[t]={...n,streaming:!1}))}function Ps(e){if(e.streamingAssistantIndex===null&&e.streamingReasoningIndex===null)return e;const t=e.rows.slice();return Fe(t,e.streamingAssistantIndex),Fe(t,e.streamingReasoningIndex),{...e,rows:t,streamingAssistantIndex:null,streamingReasoningIndex:null}}function Xc(e){return Ps(e)}function Jc(e,t,n){var i;const s=e.rows.slice();Fe(s,e.streamingReasoningIndex);let r=e.streamingAssistantIndex;if(r===null||((i=s[r])==null?void 0:i.kind)!=="assistant"){if(!t)return{...e,rows:s,streamingAssistantIndex:null,streamingReasoningIndex:null};const a={kind:"assistant",id:Se(),text:"",streaming:!0};s.push(a),r=s.length-1}const o=s[r];return!o||o.kind!=="assistant"?e:(s[r]={...o,text:o.text+t,streaming:!n},{...e,rows:s,streamingAssistantIndex:n?null:r,streamingReasoningIndex:null})}function Qc(e,t,n){var i;const s=e.rows.slice();Fe(s,e.streamingAssistantIndex);let r=e.streamingReasoningIndex;if(r===null||((i=s[r])==null?void 0:i.kind)!=="reasoning"){if(!t)return{...e,rows:s,streamingAssistantIndex:null,streamingReasoningIndex:null};const a={kind:"reasoning",id:Se(),text:"",streaming:!0};s.push(a),r=s.length-1}const o=s[r];return!o||o.kind!=="reasoning"?e:(s[r]={...o,text:o.text+t,streaming:!n},{...e,rows:s,streamingReasoningIndex:n?null:r,streamingAssistantIndex:null})}function Zc(e,t){if(e.kind!==t.kind)return t;const n={...e};for(const[s,r]of Object.entries(t))r!==void 0&&r!==""&&(n[s]=r);return n}function el(e,t){var a;const n=Yc(t.callId,t.tool),s=t.status==="completed"||t.status==="error"?t.status:"running",r=e.toolIndexByCallId[n],o=e.rows.slice();if(Fe(o,e.streamingAssistantIndex),Fe(o,e.streamingReasoningIndex),r!==void 0&&((a=o[r])==null?void 0:a.kind)==="tool"){const l=o[r];return l.kind!=="tool"?e:(o[r]={...l,tool:Zc(l.tool,t.tool),status:s},{...e,rows:o,streamingAssistantIndex:null,streamingReasoningIndex:null})}const i={kind:"tool",id:Se(),callId:n,tool:t.tool,status:s};return o.push(i),{...e,rows:o,toolIndexByCallId:{...e.toolIndexByCallId,[n]:o.length-1},streamingAssistantIndex:null,streamingReasoningIndex:null}}function on(e){return Ps(e)}function tl(e,t){const n=on(e),s={kind:"error",id:Se(),text:t||"turn failed"};return{...n,rows:[...n.rows,s]}}function nl(e){const t=on(e),n={kind:"system",id:Se(),text:"(canceled)"};return{...t,rows:[...t.rows,n]}}function sl(e,t){const n={kind:"error",id:Se(),text:t||"error"};return{...e,rows:[...e.rows,n]}}function rl(e,t,n,s){if(s!==void 0){const o=e.rows.findIndex(i=>i.kind==="user"&&i.pending&&i.clientMessageId===s);if(o!==-1){const i=e.rows.slice(),a=i[o];if((a==null?void 0:a.kind)==="user")return i[o]={...a,text:t,images:n,pending:!1},{...e,rows:i}}}const r={kind:"user",id:Se(),text:t,images:n,clientMessageId:s};return{...e,rows:[...e.rows,r]}}function ol(e,t){let n=!1;const s=e.rows.map(r=>r.kind!=="user"||!r.queued||t.includes(r.text)?r:(n=!0,{...r,queued:!1}));return n?{...e,rows:s}:e}function Ds(e,t){switch(t.kind){case"turn_started":return Xc(e);case"user_message":return rl(e,t.text??"",t.images,t.messageId);case"assistant_message":return Jc(e,t.text??"",t.final??!1);case"reasoning":return Qc(e,t.text??"",t.final??!1);case"tool_call":return el(e,t);case"turn_completed":return on(e);case"turn_failed":return tl(e,t.error);case"turn_canceled":return nl(e);case"error":return sl(e,t.message);case"queue_update":return ol(e,t.steering??[]);default:return e}}function il(e,t,n,s,r){const o={kind:"user",id:Se(),text:n,images:s,clientMessageId:t,pending:!0,queued:r};return{...e,rows:[...e.rows,o]}}function al(e,t){const n=e.rows.findIndex(o=>o.kind==="user"&&o.pending&&o.clientMessageId===t);if(n===-1)return e;const s=e.rows.slice(),r=s[n];return(r==null?void 0:r.kind)!=="user"?e:(s[n]={...r,pending:!1,failed:!0},{...e,rows:s})}let Nn=0;function cl(){return Nn+=1,`s-${Date.now().toString(36)}-${Nn}`}const N=xe()((e,t)=>({sessions:{},order:[],activeSessionId:null,createSession(n){const s=cl(),r={id:s,agentId:null,title:"New chat",status:"idle",cwd:n,timeline:Ut,userMessageCount:0};return e(o=>({sessions:{...o.sessions,[s]:r},order:[s,...o.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(r=>{const o=r.sessions[n];return o?{sessions:{...r.sessions,[n]:{...o,agentId:s}}}:r})},setStatus(n,s){e(r=>{const o=r.sessions[n];return o?{sessions:{...r.sessions,[n]:{...o,status:s}}}:r})},setStatusByAgentId(n,s){const r=t().findByAgentId(n);r&&t().setStatus(r.id,s)},setModel(n,s,r){e(o=>{const i=o.sessions[n];return i?{sessions:{...o.sessions,[n]:{...i,model:s,modelProvider:r}}}:o})},setModelByAgentId(n,s,r){const o=t().findByAgentId(n);o&&t().setModel(o.id,s,r)},setTitle(n,s){e(r=>{const o=r.sessions[n];return o?{sessions:{...r.sessions,[n]:{...o,title:s}}}:r})},setCwd(n,s){e(r=>{const o=r.sessions[n];return o?{sessions:{...r.sessions,[n]:{...o,cwd:s}}}:r})},applyStreamEvent(n,s){e(r=>{const o=r.sessions[n];if(!o)return r;const i=Ds(o.timeline,s);let a=o.title;if(s.kind==="turn_completed"&&a==="New chat"){const l=i.rows.slice().reverse().find(u=>u.kind==="assistant");l&&l.kind==="assistant"&&l.text&&(a=l.text.slice(0,40)+(l.text.length>40?"…":""))}return{sessions:{...r.sessions,[n]:{...o,timeline:i,title:a}}}})},addOptimisticUserMessage(n,s,r,o,i){e(a=>{const l=a.sessions[n];if(!l)return a;const u=il(l.timeline,s,r,o,i);return{sessions:{...a.sessions,[n]:{...l,timeline:u,userMessageCount:l.userMessageCount+1}}}})},markUserMessageFailed(n,s){e(r=>{const o=r.sessions[n];if(!o)return r;const i=al(o.timeline,s);return{sessions:{...r.sessions,[n]:{...o,timeline:i}}}})},activate(n){e({activeSessionId:n})},remove(n){e(s=>{const{[n]:r,...o}=s.sessions,i=s.order.filter(l=>l!==n),a=s.activeSessionId===n?i[0]??null:s.activeSessionId;return{sessions:o,order:i,activeSessionId:a}})},findByAgentId(n){return Object.values(t().sessions).find(s=>s.agentId===n)}})),Pn=new WeakMap;function ll(e,t="pi"){const n=Pn.get(e);if(n)return n;const s=e.providers.resolveDefaultModel(t).then(r=>({model:r.model,modelProvider:r.modelProvider})).catch(()=>({}));return Pn.set(e,s),s}const gt=new Map;function dl(e,t){const n=N.getState().sessions[t];if(!n)return Promise.reject(new Error(`unknown session: ${t}`));if(n.agentId)return Promise.resolve(n.agentId);const s=gt.get(t);if(s)return s;const r=(async()=>{if(!n.model){const l=await ll(e),u=N.getState().sessions[t];l.model&&u&&!u.model&&N.getState().setModel(t,l.model,l.modelProvider)}const o=N.getState().sessions[t];if(!o)throw new Error(`unknown session: ${t}`);const i={provider:"pi",cwd:o.cwd||"~"};o.model&&(i.model=o.model),o.modelProvider&&(i.modelProvider=o.modelProvider);const a=await e.createAgent({config:i,labels:{}});return N.getState().bindAgent(t,a.agentId),a.agentId})();return gt.set(t,r),r.finally(()=>gt.delete(t)),r}async function ul(e,t){var r;const n=N.getState().sessions[t];if(!n||n.userMessageCount>0||n.timeline.rows.length>0)return!1;await((r=gt.get(t))==null?void 0:r.catch(()=>{}));const s=N.getState().sessions[t];return s?(s.agentId&&e&&await e.agent(s.agentId).delete().catch(()=>{}),N.getState().remove(t),!0):!1}const fl=4;function As(e){return e==="left"||e==="right"?"row":"column"}function ae(e){return e.kind==="leaf"?[e.id]:e.children.flatMap(ae)}function an(e,t){return e.kind==="leaf"?e.id===t:e.children.some(n=>an(n,t))}function $s(e,t,n=1){if(e.kind==="leaf")return e.id===t?n:null;for(const s of e.children){const r=$s(s,t,n+1);if(r!==null)return r}return null}function qs(e,t){if(e.kind==="leaf")return null;if(cn(e,t)!==-1)return e;for(const n of e.children){const s=qs(n,t);if(s)return s}return null}function cn(e,t){return e.children.findIndex(n=>n.kind==="leaf"&&n.id===t)}function tt(e,t,n){const s=$s(e,t);if(s===null)return!1;const r=qs(e,t);return r&&r.direction===As(n)?!0:s+1<=fl}function Dn(e,t,n,s){if(!tt(e,t,n)||an(e,s))return e;const r=As(n),o=n==="left"||n==="top",i={kind:"leaf",id:s},a=u=>({kind:"split",direction:r,children:o?[i,u]:[u,i],sizes:[.5,.5]}),l=u=>{if(u.kind==="leaf")return u.id===t?a(u):u;const f=cn(u,t);if(f!==-1&&u.direction===r){const m=u.sizes[f]/2,h=o?f:f+1,p=u.children.slice(),w=u.sizes.slice();return w[f]=m,p.splice(h,0,i),w.splice(h,0,m),{kind:"split",direction:u.direction,children:p,sizes:w}}return{kind:"split",direction:u.direction,children:u.children.map(l),sizes:u.sizes.slice()}};return l(e)}function Bs(e,t){if(!an(e,t)||e.kind==="leaf")return e;const n=s=>{if(s.kind==="leaf")return s;const r=cn(s,t);if(r===-1)return{kind:"split",direction:s.direction,children:s.children.map(n),sizes:s.sizes.slice()};const o=s.sizes.filter((l,u)=>u!==r),i=o.reduce((l,u)=>l+u,0),a=i+s.sizes[r];return{kind:"split",direction:s.direction,children:s.children.filter((l,u)=>u!==r),sizes:o.map(l=>l/i*a)}};return Os(n(e))}function Os(e){if(e.kind==="leaf")return e;const t=e.children.map(Os);if(t.length===1)return t[0];const n=[],s=[];return t.forEach((r,o)=>{const i=e.sizes[o];r.kind==="split"&&r.direction===e.direction?r.children.forEach((a,l)=>{n.push(a),s.push(i*r.sizes[l])}):(n.push(r),s.push(i))}),n.length===1?n[0]:{kind:"split",direction:e.direction,children:n,sizes:s}}const An=.1;function pl(e){const t=new Map,n=(s,r)=>{if(s.kind==="leaf"){t.set(s.id,r);return}zs(s,r).forEach((o,i)=>n(s.children[i],o))};return n(e,{x:0,y:0,width:1,height:1}),t}function zs(e,t){const n=[];let s=0;for(const r of e.sizes)n.push(e.direction==="row"?{x:t.x+s*t.width,y:t.y,width:r*t.width,height:t.height}:{x:t.x,y:t.y+s*t.height,width:t.width,height:r*t.height}),s+=r;return n}function hl(e){const t=[],n=(s,r,o)=>{if(s.kind==="leaf")return;const i=zs(s,r);for(let a=0;a<s.children.length-1;a+=1){const l=i[a];t.push({splitPath:o.slice(),boundaryIndex:a,direction:s.direction,rect:s.direction==="row"?{x:l.x+l.width,y:r.y,width:0,height:r.height}:{x:r.x,y:l.y+l.height,width:r.width,height:0},splitRect:r})}i.forEach((a,l)=>n(s.children[l],a,[...o,l]))};return n(e,{x:0,y:0,width:1,height:1},[]),t}function ml(e,t){let n=e;for(const s of t){if(!n||n.kind!=="split")return null;n=n.children[s]}return n??null}function gl(e,t,n,s){const r=ml(e,t);if(!r||r.kind!=="split"||n<0||n>r.children.length-2||!Number.isFinite(s)||s===0)return e;const o=r.sizes[n],i=r.sizes[n+1],a=i-Math.min(i,An),l=o-Math.min(o,An),u=Math.max(-l,Math.min(a,s));if(u===0)return e;const f=h=>{const p=h.sizes.slice();return p[n]=o+u,p[n+1]=i-u,{kind:"split",direction:h.direction,children:h.children,sizes:p}},m=(h,p)=>{if(h.kind!=="split")return h;if(p===t.length)return f(h);const w=t[p],y=h.children.slice();return y[w]=m(h.children[w],p+1),{kind:"split",direction:h.direction,children:y,sizes:h.sizes.slice()}};return m(e,0)}function Fs(e,t){const n=ae(e).filter(s=>!t.has(s));return n.length===0?e:n.reduce((s,r)=>Bs(s,r),e)}const Ws=1;function yl(e){return Ls(e,new Set)}function Ls(e,t){if(typeof e!="object"||e===null)return null;const n=e;if(n.kind==="leaf"){const{id:o}=n;return typeof o!="string"||o.trim()===""||t.has(o)?null:(t.add(o),{kind:"leaf",id:o})}if(n.kind!=="split"||n.direction!=="row"&&n.direction!=="column"||!Array.isArray(n.children)||!Array.isArray(n.sizes)||n.children.length<2||n.sizes.length!==n.children.length)return null;let s=0;for(const o of n.sizes){if(typeof o!="number"||!Number.isFinite(o)||o<=0)return null;s+=o}const r=[];for(const o of n.children){const i=Ls(o,t);if(!i)return null;r.push(i)}return{kind:"split",direction:n.direction,children:r,sizes:n.sizes.map(o=>o/s)}}const _l=["sessions","terminals"];function Vt(){return`pane-${crypto.randomUUID()}`}function $n(){const e=Vt();return{tree:{kind:"leaf",id:e},placement:{},activeByPane:{},focusedPaneId:e,pendingPlacement:{},pendingActive:{},userActedPanes:new Set}}function Hs(e,t,n){return(n??Object.keys(e.placement)).filter(r=>e.placement[r]===t)}function Us(e,t,n,s){const r=Hs(e,t,s),o=r.indexOf(n),i=r.filter(a=>a!==n);if(i.length!==0)return i[Math.min(Math.max(o,0),i.length-1)]}function wl(e,t){return e.pendingActive[t]!==void 0?!0:Object.values(e.pendingPlacement).includes(t)}function ln(e,t){if(wl(e,t))return e;const n=Bs(e.tree,t);if(n===e.tree)return e;const s={...e.activeByPane};delete s[t];const r=ae(n);return{...e,tree:n,activeByPane:s,focusedPaneId:r.includes(e.focusedPaneId)?e.focusedPaneId:r[0]}}function pt(e,t,n,s){const r=e.placement[t],o={...e.placement,[t]:n},i={...e.activeByPane};if(s.activate&&(i[n]=t),r!==void 0&&r!==n&&i[r]===t){const u=Us(e,r,t,s.order);u===void 0?delete i[r]:i[r]=u}const a={...e,placement:o,activeByPane:i,focusedPaneId:s.focus?n:e.focusedPaneId};return r!==void 0&&r!==n&&!Object.values(o).includes(r)?ln(a,r):a}function Pe(e,t){return e.userActedPanes.has(t)?e:{...e,userActedPanes:new Set(e.userActedPanes).add(t)}}function bl(e){let t={...e,pendingPlacement:{},pendingActive:{}};const n=new Set(Object.values(t.placement));for(const o of ae(t.tree))n.has(o)||(t=ln(t,o));const s={...t.activeByPane};let r=!1;for(const o of ae(t.tree)){if(s[o]!==void 0)continue;const i=Object.keys(t.placement).find(a=>t.placement[a]===o);i!==void 0&&(s[o]=i,r=!0)}return r?{...t,activeByPane:s}:t}function vl(e,t){if(e===void 0)return!1;const n=e.placement[t];return n!==void 0&&e.activeByPane[n]===t}const P=xe()((e,t)=>{const n=(s,r)=>{e(o=>{const i=o.layouts[s]??$n(),a=r(i)??i;return a===o.layouts[s]?o:{layouts:{...o.layouts,[s]:a}}})};return{layouts:{},hydrationSources:{sessions:!1,terminals:!1},restoring:!1,pendingActiveWorkspace:null,ensureWorkspace(s){e(r=>r.layouts[s]?r:{layouts:{...r.layouts,[s]:$n()}})},assignTab(s,r,o,i,a){n(s,l=>{const u=ae(l.tree),f=o!==void 0&&u.includes(o)?o:u.includes(l.focusedPaneId)?l.focusedPaneId:u[0],m=i!==!0,h=pt(l,r,f,{activate:m,focus:m,order:a});return m?Pe(h,f):h})},moveTab(s,r,o,i){n(s,a=>{if(a.placement[r]===void 0||a.placement[r]===o||!ae(a.tree).includes(o))return null;const l=pt(a,r,o,{activate:!0,focus:!0,order:i});return Pe(l,o)})},splitWithTab(s,r,o,i,a){n(s,l=>{if(!ae(l.tree).includes(o)||!tt(l.tree,o,i))return null;const u=Hs(l,o,a);if(u.length===1&&u[0]===r)return null;const f=Vt(),m=Dn(l.tree,o,i,f);if(m===l.tree)return null;const h=pt({...l,tree:m},r,f,{activate:!0,focus:!0,order:a});return Pe(h,f)})},splitEmpty(s,r,o){let i=null;return n(s,a=>{if(!ae(a.tree).includes(r)||!tt(a.tree,r,o))return null;const l=Vt(),u=Dn(a.tree,r,o,l);return u===a.tree?null:(i=l,{...a,tree:u,focusedPaneId:l})}),i},removeTab(s,r,o){n(s,i=>{const a=i.placement[r];if(a===void 0)return null;const l={...i.placement};delete l[r];const u={...i.activeByPane};if(u[a]===r){const m=Us(i,a,r,o);m===void 0?delete u[a]:u[a]=m}const f={...i,placement:l,activeByPane:u};return Object.values(l).includes(a)?f:ln(f,a)})},setActiveTab(s,r,o){n(s,i=>i.placement[o]!==r?null:i.activeByPane[r]===o?Pe(i,r):Pe({...i,activeByPane:{...i.activeByPane,[r]:o}},r))},focusPane(s,r){n(s,o=>o.focusedPaneId===r||!ae(o.tree).includes(r)?null:{...o,focusedPaneId:r})},resizeDivider(s,r,o,i){n(s,a=>{const l=gl(a.tree,r,o,i);return l===a.tree?null:{...a,tree:l}})},installPersistedLayouts(s,r=null){e(o=>{const i={...o.layouts};for(const[a,l]of s){const u=ae(l.tree);i[a]={tree:l.tree,placement:{},activeByPane:{},focusedPaneId:l.activePaneId!==null&&u.includes(l.activePaneId)?l.activePaneId:u[0],pendingPlacement:{...l.placement},pendingActive:{...l.activeByPane},userActedPanes:new Set}}return{layouts:i,hydrationSources:{sessions:!1,terminals:!1},restoring:!0,pendingActiveWorkspace:r!==null&&i[r]!==void 0?r:null}})},claimPaneFor(s,r,o,i){n(s,a=>{const l=ae(a.tree);let u,f=!1;if(i!==void 0&&l.includes(i))u=i;else if(o!==null){const w=a.pendingPlacement[o];w!==void 0&&l.includes(w)&&(u=w,f=!0)}u??(u=l.includes(a.focusedPaneId)?a.focusedPaneId:l[0]);let m=a;if(f&&o!==null){const w={...a.pendingPlacement};delete w[o],m={...a,pendingPlacement:w}}let h=!0;if(f){const w=m.pendingActive[u];m.userActedPanes.has(u)?h=!1:w!==void 0&&w!==o&&(h=m.activeByPane[u]===void 0)}else t().restoring&&(h=m.activeByPane[u]===void 0);const p=pt(m,r,u,{activate:h,focus:!f&&h});return f?p:Pe(p,u)})},markHydrationSource(s){e(r=>{if(r.hydrationSources[s])return r;const o={...r.hydrationSources,[s]:!0};if(!_l.every(a=>o[a]))return{hydrationSources:o};const i={};for(const[a,l]of Object.entries(r.layouts))i[a]=bl(l);return{hydrationSources:o,layouts:i,restoring:!1,pendingActiveWorkspace:null}})},paneOfTab(s,r){var o;return((o=t().layouts[s])==null?void 0:o.placement[r])??null},activeTabOf(s){const r=t().layouts[s];return r?r.activeByPane[r.focusedPaneId]??null:null}}});function xl(e,t){return e.filter(n=>n.workspaceCwd===t)}function Sl(e,t){return xl(e,t).map(n=>n.id)}function Qe(e){const t=e===null?null:P.getState().activeTabOf(e);if(T.setState({activeTabId:t,activeWorkspaceCwd:e}),t!==null)return T.getState().tabs.find(n=>n.id===t)}function Ze(e){(e==null?void 0:e.kind)==="chat"&&N.getState().activate(e.data.sessionId)}const T=xe()((e,t)=>({tabs:[],activeTabId:null,activeWorkspaceCwd:null,open(n,s){const r=t().tabs.find(i=>i.id===n.id);if(r){t().activate(r.id);return}e(i=>({tabs:[...i.tabs,n]}));const o=P.getState();o.ensureWorkspace(n.workspaceCwd),o.claimPaneFor(n.workspaceCwd,n.id,bt(n),s),Ze(Qe(n.workspaceCwd))},close(n){const s=t().tabs.find(a=>a.id===n);if(!s)return;const r=Sl(t().tabs,s.workspaceCwd),o=t().activeTabId;e(a=>({tabs:a.tabs.filter(l=>l.id!==n)})),P.getState().removeTab(s.workspaceCwd,n,r);const i=Qe(t().activeWorkspaceCwd);t().activeTabId!==o&&Ze(i)},activate(n){const s=t().tabs.find(i=>i.id===n);if(!s)return;const r=P.getState();r.ensureWorkspace(s.workspaceCwd);const o=r.paneOfTab(s.workspaceCwd,n);o===null?r.claimPaneFor(s.workspaceCwd,n,bt(s)):(r.focusPane(s.workspaceCwd,o),r.setActiveTab(s.workspaceCwd,o,n)),Ze(Qe(s.workspaceCwd))},switchWorkspace(n){P.getState().ensureWorkspace(n),Ze(Qe(n))},reorder(n,s){e(r=>{const o=r.tabs.findIndex(u=>u.id===n),i=r.tabs.findIndex(u=>u.id===s);if(o===-1||i===-1||o===i)return r;const a=r.tabs.slice(),[l]=a.splice(o,1);return l?(a.splice(i,0,l),{tabs:a}):r})},updateLabel(n,s){e(r=>({tabs:r.tabs.map(o=>o.id===n?{...o,label:s}:o)}))},updateData(n,s){e(r=>({tabs:r.tabs.map(o=>o.id===n?{...o,data:{...o.data,...s}}:o)}))},closeByPathPrefix(n){const s=t().tabs.filter(r=>{if(r.kind!=="file"&&r.kind!=="diff"&&r.kind!=="molecule")return!1;const o=r.data.path;return o===n||((o==null?void 0:o.startsWith(`${n}/`))??!1)});for(const r of s)t().close(r.id)}}));function bt(e){var t;switch(e.kind){case"chat":{const{sessionId:n}=e.data,s=(t=N.getState().sessions[n])==null?void 0:t.agentId;return s?`agent:${s}`:null}case"file":return`file:${e.data.path}`;case"diff":{const{path:n,staged:s}=e.data;return`diff:${s?"staged":"worktree"}:${n}`}case"terminal":{const{slot:n}=e.data;return n===null?null:`terminal:${n}`}case"molecule":{const{path:n}=e.data;return n===null?null:`molecule:${n}`}}}function Wh(e){const t=T(n=>{var s;return((s=n.tabs.find(r=>r.id===e))==null?void 0:s.workspaceCwd)===n.activeWorkspaceCwd?n.activeWorkspaceCwd:null});return P(n=>t===null?!1:vl(n.layouts[t],e))}const K={chat:e=>`chat-${e}`,file:e=>`file-${e}`,diff:(e,t)=>`diff-${e}${t?"-staged":""}`,terminal:e=>`term-${e}`,molecule:e=>`mol-${e}`};let Pt=0;function Vs(e,t){Pt+=1,T.getState().open({id:K.terminal(`new-${Pt}`),kind:"terminal",label:`Terminal ${Pt}`,closable:!0,data:{slot:null,cwd:e},workspaceCwd:e},t)}let Dt=0;function kl(e,t){Dt+=1,T.getState().open({id:K.molecule(`new-${Dt}`),kind:"molecule",label:`Molecule ${Dt}`,closable:!0,data:{path:null},workspaceCwd:e},t)}function jt(e,t){const n=N.getState().createSession(e);T.getState().open({id:K.chat(n),kind:"chat",label:"New chat",closable:!0,data:{sessionId:n},workspaceCwd:e},t);const s=$.getState().client;s&&dl(s,n).catch(()=>{})}function Kt(e){const t=T.getState().tabs.find(s=>s.id===e);if(T.getState().close(e),(t==null?void 0:t.kind)!=="chat")return;const{sessionId:n}=t.data;ul($.getState().client,n)}P.subscribe(()=>{const{activeWorkspaceCwd:e,activeTabId:t}=T.getState();e!==null&&P.getState().activeTabOf(e)!==t&&Ze(Qe(e))});const Il="_panel_1de7t_3",jl={panel:Il};function Ks({className:e,...t}){return c.jsx("div",{className:W(jl.panel,e),...t})}const Tl="_emptyState_kp50e_3",Cl={emptyState:Tl};function Ce({className:e,...t}){return c.jsx("div",{className:W(Cl.emptyState,e),...t})}const te=xe()(e=>({rootPath:"",expanded:new Set,expandedByRoot:new Map,draft:null,renaming:null,selected:null,setRoot:t=>e(n=>{const s=new Map(n.expandedByRoot);n.rootPath&&s.set(n.rootPath,n.expanded);const r=s.get(t);return{rootPath:t,expanded:r?new Set(r):new Set([t]),expandedByRoot:s,draft:null,selected:null,renaming:null}}),toggle:t=>e(n=>{const s=new Set(n.expanded);s.has(t)?s.delete(t):s.add(t);const r=new Map(n.expandedByRoot);return r.set(n.rootPath,s),{expanded:s,expandedByRoot:r}}),startDraft:(t,n)=>e(s=>{const r=new Set(s.expanded);r.add(t);const o=new Map(s.expandedByRoot);return s.rootPath&&o.set(s.rootPath,r),{draft:{parentPath:t,kind:n},expanded:r,expandedByRoot:o,renaming:null}}),cancelDraft:()=>e({draft:null}),startRename:t=>e({renaming:t,draft:null}),cancelRename:()=>e({renaming:null}),setSelected:t=>e({selected:t}),repathAfterMove:(t,n,s)=>e(r=>{const o=u=>u===t?n:u.startsWith(`${t}/`)?n+u.slice(t.length):u,i=new Set([...r.expanded].map(o));i.add(s);const a=new Map(r.expandedByRoot);r.rootPath&&a.set(r.rootPath,i);const l=r.selected?{path:o(r.selected.path),isDirectory:r.selected.isDirectory}:null;return{expanded:i,expandedByRoot:a,selected:l,renaming:null}})}));let Be=null;const Gt=new Set;function El(e){return Gt.add(e),()=>Gt.delete(e)}async function Tt(e){var t;if(Be)return Be;try{const n=await e.connection.request("file_explorer_request",{path:"/home"}),r=(((t=n.result)==null?void 0:t.entries)??n.entries??[]).find(o=>o.kind==="directory"||o.type==="directory");Be="/home/"+((r==null?void 0:r.name)||"user")}catch{return"/tmp"}for(const n of Gt)n(Be);return Be}function Rl(){return Be}async function Ml(e,t){return t==="~"||t.startsWith("~/")?await Tt(e)+t.slice(1):t}function rt(){const e=$(r=>r.client),t=$(r=>r.status),[n,s]=b.useState(Rl());return b.useEffect(()=>El(s),[]),b.useEffect(()=>{!e||t!=="open"||n||Tt(e)},[e,t,n]),n}const Nl="_iconBtn_1unr3_3",Pl="_xs_1unr3_32",Dl="_sm_1unr3_36",qn={iconBtn:Nl,xs:Pl,sm:Dl};function _e({size:e="xs",hoverBase:t,className:n,style:s,type:r="button",...o}){return c.jsx("button",{type:r,className:W(qn.iconBtn,qn[e],n),style:t?{"--icon-btn-hover-base":t,...s}:s,...o})}const Al="_dot_1mn1j_3",$l="_spinner_1mn1j_16",Bn={dot:Al,spinner:$l};function ql(e){const{status:t,requiresAttention:n,attentionReason:s,showInactive:r}=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 r?"foregroundMuted":null}}const On=8,Bl={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 Ol({className:e,...t}){const n=ql(t);if(!n)return null;const s=t.status==="running"&&!t.requiresAttention,r=s?"var(--pi-color-accentBright, #a2b4d7)":Bl[n]??"currentColor";return c.jsx("span",{className:`${s?Bn.spinner:Bn.dot}${e?` ${e}`:""}`,style:s?{borderTopColor:r,borderRightColor:r}:{width:On,height:On,backgroundColor:r},role:"presentation"})}const zl={initializing:"queued",idle:"idle",running:"running",error:"error",closed:"finished"};function Fl(e){return zl[e]??"idle"}const Wl="_header_z4gra_1",Ll="_openBtn_z4gra_9",Hl="_list_z4gra_21",Ul="_item_z4gra_26",Vl="_active_z4gra_39",Kl="_title_z4gra_43",Gl="_meta_z4gra_52",Yl="_menuBtn_z4gra_60",Xl="_workspaceGroup_z4gra_69",Jl="_workspaceHeader_z4gra_72",Ql="_workspaceChevron_z4gra_97",Zl="_workspaceIcon_z4gra_105",ed="_workspaceLabel_z4gra_109",td="_workspaceCount_z4gra_115",nd="_workspaceMenuBtn_z4gra_120",sd="_workspaceSessions_z4gra_127",X={header:Wl,openBtn:Ll,list:Hl,item:Ul,active:Vl,title:Kl,meta:Gl,menuBtn:Yl,workspaceGroup:Xl,workspaceHeader:Jl,workspaceChevron:Ql,workspaceIcon:Zl,workspaceLabel:ed,workspaceCount:td,workspaceMenuBtn:nd,workspaceSessions:sd};function rd({session:e,active:t,draggable:n,onSelect:s,onOpenMenu:r,onDragStartRow:o}){return c.jsxs("div",{className:W(X.item,t&&X.active),draggable:n,onDragStart:o,onClick:s,onContextMenu:i=>{i.preventDefault(),r(i.clientX,i.clientY)},children:[c.jsxs("div",{className:X.title,children:[c.jsx(Ol,{status:Fl(e.status),showInactive:!0}),c.jsx("span",{children:e.title})]}),c.jsxs("div",{className:X.meta,children:[e.cwd||"~"," · ",e.agentId?e.agentId.slice(0,8):"new"," ·"," ",e.userMessageCount," msgs"]}),c.jsx(_e,{className:X.menuBtn,hoverBase:"var(--pi-color-surfaceSidebar)",title:"Actions",onClick:i=>{i.stopPropagation();const a=i.currentTarget.getBoundingClientRect();r(a.left,a.bottom)},children:c.jsx(Qt,{size:14})})]})}const od="_trigger_cd29a_3",id="_content_cd29a_15",ad="_item_cd29a_25",cd="_danger_cd29a_44",ld="_sep_cd29a_48",nt={trigger:od,content:id,item:ad,danger:cd,sep:ld},dn=b.forwardRef(function({x:t,y:n},s){return c.jsx("button",{ref:s,type:"button",className:nt.trigger,style:{left:t,top:n},"aria-hidden":!0,tabIndex:-1})});function Ct({className:e,minWidth:t,style:n,sideOffset:s=2,...r}){const o=t===void 0?n:{minWidth:t,...n};return c.jsx(Xr,{children:c.jsx(Jr,{className:W(nt.content,e),align:"start",sideOffset:s,style:o,...r})})}function H({className:e,danger:t,...n}){return c.jsx(Qr,{className:W(nt.item,t&&nt.danger,e),...n})}function Te(e){return c.jsx(Zr,{className:nt.sep,...e})}function dd(){const e=E(w=>w.sessionMenu),t=E(w=>w.closeSessionMenu),n=$(w=>w.client),s=b.useRef(null),[r,o]=b.useState(!1);b.useEffect(()=>{o(e!==null)},[e]);const i=N(w=>e?w.sessions[e.sessionId]:void 0);if(!e)return null;const a=!!(i!=null&&i.agentId)&&(i==null?void 0:i.status)==="running";function l(w){o(w),w||t()}function u(){if(!i)return;const w=window.prompt("Rename:",i.title);if(w!=null&&w.trim()){const y=w.trim();N.getState().setTitle(i.id,y),T.getState().updateLabel(K.chat(i.id),y),i.agentId&&(n==null||n.agent(i.agentId).update({title:y}).catch(()=>{}))}t()}function f(){i!=null&&i.agentId&&(n==null||n.agent(i.agentId).interrupt().catch(()=>{})),t()}function m(w){N.getState().remove(w),T.getState().close(K.chat(w))}async function h(){if(i){if(!window.confirm("Archive this agent? It can be resumed later."))return t();if(t(),!i.agentId){m(i.id);return}if(!n){window.alert("Not connected — cannot archive remotely.");return}try{await n.agent(i.agentId).archive(),m(i.id)}catch(w){window.alert(`Failed to archive: ${w instanceof Error?w.message:String(w)}`)}}}async function p(){if(i){if(!window.confirm("Permanently delete this agent? This cannot be undone."))return t();if(t(),!i.agentId){m(i.id);return}if(!n){window.alert("Not connected — cannot delete remotely.");return}try{await n.agent(i.agentId).delete(),m(i.id)}catch(w){window.alert(`Failed to delete: ${w instanceof Error?w.message:String(w)}`)}}}return c.jsxs(St,{open:r,onOpenChange:l,modal:!1,children:[c.jsx(kt,{asChild:!0,children:c.jsx(dn,{ref:s,x:e.x,y:e.y})}),c.jsxs(Ct,{minWidth:160,children:[c.jsxs(H,{onSelect:u,children:[c.jsx(os,{size:13}),"Rename"]}),c.jsxs(H,{disabled:!a,onSelect:f,children:[c.jsx(Dr,{size:13}),"Stop agent"]}),c.jsx(Te,{}),c.jsxs(H,{danger:!0,onSelect:h,children:[c.jsx(Ar,{size:13}),"Archive"]}),c.jsxs(H,{danger:!0,onSelect:p,children:[c.jsx(Zt,{size:13}),"Delete permanently"]})]})]})}function ud({label:e,cwd:t,sessionCount:n,collapsed:s,onToggleCollapsed:r,onOpenMenu:o}){return c.jsxs("div",{className:X.workspaceHeader,onClick:r,title:t,children:[c.jsx(_e,{className:X.workspaceChevron,"aria-label":s?"Expand workspace":"Collapse workspace",onClick:i=>{i.stopPropagation(),r()},children:s?c.jsx(en,{size:13}):c.jsx($r,{size:13})}),c.jsx(qr,{size:13,className:W(X.workspaceIcon)}),c.jsx("span",{className:X.workspaceLabel,children:e}),c.jsx("span",{className:X.workspaceCount,children:n}),c.jsx(_e,{className:X.workspaceMenuBtn,hoverBase:"var(--pi-color-surfaceSidebar)",title:"Workspace actions",onClick:i=>{i.stopPropagation();const a=i.currentTarget.getBoundingClientRect();o(a.left,a.bottom)},children:c.jsx(Qt,{size:13})})]})}function Ne(e,t){return t&&(e==="~"||e.startsWith("~/"))?t+e.slice(1):e}function un(e,t,n){const s=new Map;for(const r of e){const o=t[r];if(!o)continue;const i=Ne(o.cwd||"~",n),a=s.get(i);a?a.push(o):s.set(i,[o])}return Array.from(s,([r,o])=>({cwd:r,sessions:o}))}function Gs(e){return!e||e==="~"?"~":e.split("/").filter(Boolean).pop()||e}function fd(e,t){return new Set(e.filter(n=>n.cwd!==t).map(n=>n.cwd))}function pd(){const e=E(p=>p.workspaceMenu),t=E(p=>p.closeWorkspaceMenu),n=$(p=>p.client),s=N(p=>p.order),r=N(p=>p.sessions),o=rt(),i=b.useRef(null),[a,l]=b.useState(!1);if(b.useEffect(()=>{l(e!==null)},[e]),!e)return null;const u=s.map(p=>r[p]).filter(p=>!!p).filter(p=>Ne(p.cwd||"~",o)===e.cwd);function f(p){l(p),p||t()}function m(){e&&(t(),jt(e.cwd))}async function h(){if(!e)return;const p=u.length;if(!window.confirm(`Delete all ${p} conversation${p===1?"":"s"} in "${Gs(e.cwd)}"? This deletes the conversations only — files on disk are untouched. This cannot be undone.`))return t();t();for(const y of u){if(y.agentId&&n)try{await n.agent(y.agentId).delete()}catch(v){window.alert(`Failed to delete "${y.title}": ${v instanceof Error?v.message:String(v)}`);continue}N.getState().remove(y.id),T.getState().close(K.chat(y.id))}}return c.jsxs(St,{open:a,onOpenChange:f,modal:!1,children:[c.jsx(kt,{asChild:!0,children:c.jsx(dn,{ref:i,x:e.x,y:e.y})}),c.jsxs(Ct,{minWidth:160,children:[c.jsxs(H,{onSelect:m,children:[c.jsx(is,{size:13}),"New conversation"]}),c.jsx(Te,{}),c.jsxs(H,{danger:!0,onSelect:h,children:[c.jsx(Zt,{size:13}),"Delete workspace (all conversations)"]})]})]})}function vt(e,t,n){T.getState().open({id:K.chat(e.id),kind:"chat",label:e.title||"Chat",closable:!0,data:{sessionId:e.id},workspaceCwd:Ne(e.cwd||"~",t)},n)}const hd=.25;function Ys(e,t){if(t.width<=0||t.height<=0)return"center";const n=(e.x-(t.left+t.width/2))/t.width,s=(e.y-(t.top+t.height/2))/t.height;return Math.max(Math.abs(n),Math.abs(s))<hd?"center":Math.abs(n)>=Math.abs(s)?n<0?"left":"right":s<0?"top":"bottom"}function md(e,t){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}function Xs(e,t,n){return n==="center"?"center":tt(e,t,n)?n:"center"}function Yt(e,t,n,s){return s[n]!==t?!1:e==="center"?!0:Object.keys(s).every(o=>o===n||s[o]!==t)}const ot={chat:"application/x-pi-studio-open-chat",path:"application/x-pi-studio-open-path"},gd=["chat","path"];function Js(e){for(const t of gd)if(e.includes(ot[t]))return t;return null}function Lh(e){return t=>{t.dataTransfer.setData(ot.path,e),t.dataTransfer.effectAllowed="copyMove"}}function yd(e,t){const n=Js(e);if(n===null)return null;const s=t(ot[n]).trim();return s===""?null:{kind:n,value:s}}function _d(e,t,n,s){return Xs(e,t,Ys(n,s))}function wd(){const e=N(v=>v.order),t=N(v=>v.sessions),n=N(v=>v.activeSessionId),s=N(v=>v.activate),r=T(v=>v.activeWorkspaceCwd),o=$(v=>v.status),i=E(v=>v.openSessionMenu),a=E(v=>v.openWorkspaceMenu),l=E(v=>v.setCwd),u=E(v=>v.openCwdPicker),f=E(v=>v.collapsedWorkspaces),m=E(v=>v.toggleWorkspaceCollapsed),h=rt();function p(v){s(v);const I=t[v];I!=null&&I.cwd&&l(I.cwd),I&&vt(I,h)}function w(v,I,j){I===r&&(j.dataTransfer.setData(ot.chat,v),j.dataTransfer.effectAllowed="copy")}const y=un(e,t,h);return c.jsxs(Ks,{children:[c.jsxs("div",{className:X.header,children:[c.jsx("h3",{children:"Workspaces"}),c.jsx(se,{size:"xs",variant:"ghost",iconOnly:!0,className:X.openBtn,title:o!=="open"?"Connect to open a workspace":"Open a workspace folder",disabled:o!=="open",onClick:()=>u(),children:c.jsx(as,{size:13})})]}),c.jsxs("div",{className:X.list,children:[y.length===0&&c.jsx(Ce,{style:{padding:"var(--pi-spacing-12) var(--pi-spacing-10)"},children:o!=="open"?"Not connected":"No workspaces — open a folder to start"}),y.map(v=>{const I=f.has(v.cwd);return c.jsxs("div",{className:X.workspaceGroup,children:[c.jsx(ud,{label:Gs(v.cwd),cwd:v.cwd,sessionCount:v.sessions.length,collapsed:I,onToggleCollapsed:()=>m(v.cwd),onOpenMenu:(j,B)=>a(v.cwd,j,B)}),!I&&c.jsx("div",{className:X.workspaceSessions,children:v.sessions.map(j=>c.jsx(rd,{session:j,active:j.id===n,draggable:v.cwd===r,onSelect:()=>p(j.id),onOpenMenu:(B,z)=>i(j.id,B,z),onDragStartRow:B=>w(j.id,v.cwd,B)},j.id))})]},v.cwd)})]}),c.jsx(dd,{}),c.jsx(pd,{})]})}const bd="_spinner_ohxfo_3",vd={spinner:bd},xd={xs:12,sm:16,md:20,lg:24},Sd={xs:1,sm:2,md:2,lg:3};function kd({size:e="md",color:t="currentColor",className:n,"aria-label":s="Loading"}){const r=typeof e=="number"?e:xd[e],o=typeof e=="number"?2:Sd[e];return c.jsx("span",{className:`${vd.spinner}${n?` ${n}`:""}`,role:"status","aria-label":s,style:{width:r,height:r,borderWidth:o,color:t}})}const zn={tab:0,strip:1,pane:2};function At(e){if(e===null||typeof e!="object"||!("type"in e))return null;const{type:t}=e;if(t!=="tab"&&t!=="strip"&&t!=="pane")return null;const n="paneId"in e&&typeof e.paneId=="string"?e.paneId:null;return{kind:t,paneId:n}}function Id(e){const t=e.activatorEvent;return t instanceof MouseEvent?{x:t.clientX+e.delta.x,y:t.clientY+e.delta.y}:null}function jd(e,t,n){return e.kind==="tab"?n.placement[t]??null:e.paneId}function Td(e){const[t,n]=b.useState(null),[s,r]=b.useState(null),o=T(p=>p.tabs.find(w=>w.id===t)??null),i=ro(oo(ao,{activationConstraint:{distance:4}})),a=b.useMemo(()=>p=>{const w=io(p).map(y=>{var v;return{hit:y,target:At((v=p.droppableContainers.find(I=>I.id===y.id))==null?void 0:v.data.current)}}).filter(y=>y.target!==null).toSorted((y,v)=>zn[y.target.kind]-zn[v.target.kind]);return w.length===0?[]:[w[0].hit]},[]),l=b.useCallback(p=>{const{over:w,active:y}=p,v=At(w==null?void 0:w.data.current);if(!w||v===null||e===null)return null;const I=P.getState().layouts[e];if(I===void 0)return null;const j=String(y.id),B=String(w.id);if(v.kind!=="pane"){const G=jd(v,B,I);return G===null||v.kind==="tab"&&B===j?null:v.kind==="tab"&&I.placement[j]===G?{paneId:G,region:"center"}:Yt("center",G,j,I.placement)?null:{paneId:G,region:"center"}}const z=Id(p);if(v.paneId===null||z===null)return null;const Q=Xs(I.tree,v.paneId,Ys(z,w.rect));return Yt(Q,v.paneId,j,I.placement)?null:{paneId:v.paneId,region:Q}},[e]),u=b.useCallback(p=>{n(String(p.active.id))},[]),f=b.useCallback(p=>{const w=l(p);r(y=>(y==null?void 0:y.paneId)===(w==null?void 0:w.paneId)&&(y==null?void 0:y.region)===(w==null?void 0:w.region)?y:w)},[l]),m=b.useCallback(()=>{n(null),r(null)},[]),h=b.useCallback(p=>{var oe;n(null),r(null);const{active:w,over:y}=p,v=At(y==null?void 0:y.data.current);if(!y||v===null||e===null)return;const I=String(w.id),j=P.getState().layouts[e];if(j===void 0)return;const B=T.getState(),z=B.tabs.filter(ee=>ee.workspaceCwd===e).map(ee=>ee.id),{moveTab:Q,splitWithTab:G}=P.getState();if(v.kind==="tab"){const ee=String(y.id);if(ee===I)return;const ue=j.placement[ee];ue!==void 0&&ue!==j.placement[I]&&Q(e,I,ue,z),B.reorder(I,ee);return}const M=l(p);if(M===null)return;if(M.region!=="center"){G(e,I,M.paneId,M.region,z);return}Q(e,I,M.paneId,z);const Z=((oe=P.getState().layouts[e])==null?void 0:oe.placement)??{},re=z.filter(ee=>ee!==I&&Z[ee]===M.paneId).at(-1);re!==void 0&&z.indexOf(I)<z.indexOf(re)&&B.reorder(I,re)},[e,l]);return{sensors:i,collisionDetection:a,onDragStart:u,onDragMove:f,onDragEnd:h,onDragCancel:m,draggedTab:o,preview:s}}const Cd=b.lazy(()=>we(()=>import("./ChatPanel-BGaHXRkd.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])).then(e=>({default:e.ChatPanel}))),Fn=b.lazy(()=>we(()=>import("./FilePanel-Cg9NsETY.js"),__vite__mapDeps([16,1,7,6,5,2,17,11,12,3,13,14,18])).then(e=>({default:e.FilePanel}))),Ed=b.lazy(()=>we(()=>import("./TerminalPanel-CqbvRBBr.js"),__vite__mapDeps([19,1,20,21,7,6,5,2,3,13,14,22])).then(e=>({default:e.TerminalPanel}))),Rd=b.lazy(()=>we(()=>import("./MoleculeViewerPanel-DrXqIoI5.js"),__vite__mapDeps([23,1,24,25,9,10,26,2,17,7,6,5,3,13,14,27])).then(e=>({default:e.MoleculeViewerPanel}))),Md={chat:Cd,file:Fn,diff:Fn,terminal:Ed,molecule:Rd},st="var(--pane-strip-height)";function fn(e){return e===void 0?new Map:pl(Fs(e.tree,new Set(Object.values(e.placement))))}function V(e){const t=(e*100).toFixed(4);return`${t.includes(".")?t.replace(/\.?0+$/,""):t}%`}function Qs(e){if(e!==void 0)return{left:V(e.x),top:`calc(${V(e.y)} + ${st})`,width:V(e.width),height:`calc(${V(e.height)} - ${st})`}}function Nd(e,t){const n=`${V(e.y)} + ${st}`,s=`${V(e.height)} - ${st}`,r=`calc((${s}) / 2)`;switch(t){case"left":return{left:V(e.x),top:`calc(${n})`,width:V(e.width/2),height:`calc(${s})`};case"right":return{left:V(e.x+e.width/2),top:`calc(${n})`,width:V(e.width/2),height:`calc(${s})`};case"top":return{left:V(e.x),top:`calc(${n})`,width:V(e.width),height:r};case"bottom":return{left:V(e.x),top:`calc(${n} + (${s}) / 2)`,width:V(e.width),height:r};case"center":return{left:V(e.x),top:`calc(${n})`,width:V(e.width),height:`calc(${s})`}}}function Pd(e){const t=fn(e);return[...t].map(([n,s])=>({paneId:n,stripStyle:{left:V(s.x),top:V(s.y),width:V(s.width),height:st},focused:t.size>1&&(e==null?void 0:e.focusedPaneId)===n}))}function Dd(e){if(e===void 0)return[];const t=Fs(e.tree,new Set(Object.values(e.placement)));return t!==e.tree?[]:hl(t)}function Ad(e,t){return(t==null?void 0:t.placement[e])??null}function $d(e,t,n){const s=fn(n);return e.map(r=>{const o=r.workspaceCwd===t?n==null?void 0:n.placement[r.id]:void 0;return{tabId:r.id,style:Qs(o===void 0?void 0:s.get(o)),visible:o!==void 0&&(n==null?void 0:n.activeByPane[o])===r.id}})}const qd="_divider_4eg4l_9",Bd="_vertical_4eg4l_26",Od="_horizontal_4eg4l_41",$t={divider:qd,vertical:Bd,horizontal:Od};function zd({cwd:e,dividers:t,hostRef:n}){const s=P(i=>i.resizeDivider),r=b.useRef(0);function o(i,a){var p;const l=(p=n.current)==null?void 0:p.getBoundingClientRect();if(!l)return;i.preventDefault(),i.stopPropagation();const u=a.direction==="row",f=u?a.splitRect.width*l.width:a.splitRect.height*l.height;if(f<=0)return;r.current=u?i.clientX:i.clientY,document.body.style.cursor=u?"col-resize":"row-resize",document.body.style.userSelect="none";const m=w=>{const y=u?w.clientX:w.clientY,v=y-r.current;r.current=y,s(e,a.splitPath,a.boundaryIndex,v/f)},h=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",h),document.body.style.cursor="",document.body.style.userSelect=""};window.addEventListener("pointermove",m),window.addEventListener("pointerup",h)}return t.map(i=>{const a=i.direction==="row";return c.jsx("div",{className:W($t.divider,a?$t.vertical:$t.horizontal),style:a?{left:`${i.rect.x*100}%`,top:`${i.rect.y*100}%`,height:`${i.rect.height*100}%`}:{left:`${i.rect.x*100}%`,top:`${i.rect.y*100}%`,width:`${i.rect.width*100}%`},role:"separator","aria-orientation":a?"vertical":"horizontal",onPointerDown:l=>o(l,i)},`${i.splitPath.join(".")}:${i.boundaryIndex}`)})}const Fd=b.lazy(()=>we(()=>import("./TextViewer-Bd-xuyEa.js"),__vite__mapDeps([28,1,29,2,7,6,5,30,26,3,13,14,31])).then(e=>({default:e.TextViewer}))),Wd=b.lazy(()=>we(()=>import("./MarkdownFileViewer-BzB1d4TY.js"),__vite__mapDeps([32,1,29,2,7,6,5,30,4,8,3,13,14,33])).then(e=>({default:e.MarkdownFileViewer}))),Ld=b.lazy(()=>we(()=>import("./ImageViewer-BJp-etHM.js"),__vite__mapDeps([34,1,26,2,7,6,5,3,13,14,35])).then(e=>({default:e.ImageViewer}))),Hd=b.lazy(()=>we(()=>import("./VideoViewer-q6x3q8Rf.js"),__vite__mapDeps([36,1,26,2,7,6,5,3,13,14,37])).then(e=>({default:e.VideoViewer}))),Ud=b.lazy(()=>we(()=>import("./BinaryFallbackViewer-BcXz7eRe.js"),__vite__mapDeps([38,1,26,2,3,7,6,5,13,14,39])).then(e=>({default:e.BinaryFallbackViewer}))),Hh={text:Fd,markdown:Wd,image:Ld,video:Hd,binary:Ud},Vd={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"},Kd=[["image/","image"],["video/","video"]];function Zs(e){const t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}const Gd={pdb:!0,cif:!0,mmcif:!0,mol:!0,mol2:!0,xyz:!0,extxyz:!0,gro:!0,lammpstrj:!0,xsf:!0},Yd={poscar:!0,contcar:!0};function er(e){if(Gd[Zs(e)])return!0;const t=e.split("/").pop()??e;return!!Yd[t.toLowerCase()]}function Uh(e,t={}){const n=Vd[Zs(e)];if(n)return n;const s=t.mimeHint??"";for(const[r,o]of Kd)if(s.startsWith(r))return o;return t.isBinary?"binary":"text"}function pn(e,t,n){er(e)?nr(e,t,n):tr(e,t,n)}function tr(e,t,n){const s=e.split("/").pop()||e;T.getState().open({id:K.file(e),kind:"file",label:s,closable:!0,data:{path:e},workspaceCwd:t},n)}function nr(e,t,n){const s=e.split("/").pop()||e;T.getState().open({id:K.molecule(e),kind:"molecule",label:s,closable:!0,data:{path:e},workspaceCwd:t},n)}const Xt="data-pane-drop";function Xd(e){return{[Xt]:e}}function Jd(e,t){if(e===null)return null;for(const n of e.querySelectorAll(`[${Xt}]`)){const s=n.getBoundingClientRect(),r={left:s.left,top:s.top,width:s.width,height:s.height},o=n.getAttribute(Xt);if(o!==null&&o!==""&&md(r,t))return{paneId:o,bounds:r}}return null}function Qd(e){const{tabs:t}=T.getState(),n=s=>t.some(r=>r.id===s)?s:null;return e.kind==="chat"?n(K.chat(e.value)):n(K.file(e.value))??n(K.molecule(e.value))}function Zd(e,t,n,s,r){const o=P.getState().layouts[t];if(o===void 0)return;const i=T.getState().tabs.filter(f=>f.workspaceCwd===t).map(f=>f.id),a=Qd(e);if(a!==null){if(Yt(s,n,a,o.placement))return;const{moveTab:f,splitWithTab:m}=P.getState();s==="center"?f(t,a,n,i):m(t,a,n,s,i);return}let l=n;if(s!=="center"&&(l=P.getState().splitEmpty(t,n,s)),l===null)return;if(e.kind==="path"){pn(e.value,t,l);return}const u=N.getState().sessions[e.value];u!==void 0&&vt(u,r,l)}function eu(e,t){const[n,s]=b.useState(null),r=rt(),o=b.useCallback(u=>{if(e===null)return null;const f=P.getState().layouts[e];if(f===void 0)return null;const m={x:u.clientX,y:u.clientY},h=Jd(t.current,m);return h===null?null:{paneId:h.paneId,region:_d(f.tree,h.paneId,m,h.bounds)}},[e,t]),i=b.useCallback(u=>{if(Js(u.dataTransfer.types)===null)return;u.preventDefault(),u.dataTransfer.dropEffect="copy";const f=o(u);s(m=>(m==null?void 0:m.paneId)===(f==null?void 0:f.paneId)&&(m==null?void 0:m.region)===(f==null?void 0:f.region)?m:f)},[o]),a=b.useCallback(u=>{u.currentTarget.contains(u.relatedTarget)||s(null)},[]),l=b.useCallback(u=>{const f=yd(u.dataTransfer.types,h=>u.dataTransfer.getData(h));if(f===null)return;u.preventDefault(),s(null);const m=o(u);m===null||e===null||Zd(f,e,m.paneId,m.region,r)},[e,r,o]);return{preview:n,onDragOver:i,onDragLeave:a,onDrop:l}}const tu="_strip_1xy58_1",nu="_tabs_1xy58_13",su="_paneStrip_1xy58_23",ru="_focused_1xy58_28",ou="_tab_1xy58_13",iu="_active_1xy58_47",au="_icon_1xy58_51",cu="_label_1xy58_56",lu="_close_1xy58_61",du="_newTab_1xy58_71",uu="_splitAction_1xy58_77",fu="_itemIcon_1xy58_81",ne={strip:tu,tabs:nu,paneStrip:su,focused:ru,tab:ou,active:iu,icon:au,label:cu,close:lu,newTab:du,splitAction:uu,itemIcon:fu},sr={chat:us,file:ds,diff:ls,terminal:cs,molecule:tn};function pu({tab:e,active:t}){const n=T(f=>f.activate),s=sr[e.kind],{attributes:r,listeners:o,setNodeRef:i,transform:a,transition:l,isDragging:u}=uo({id:e.id,data:{type:"tab"}});return c.jsxs("div",{ref:i,className:W(ne.tab,t&&ne.active),style:{transform:fo.Transform.toString(a),transition:l,opacity:u?.5:1},onClick:()=>n(e.id),onAuxClick:f=>{f.button===1&&e.closable&&Kt(e.id)},title:e.label,...r,...o,children:[c.jsx("span",{className:ne.icon,children:c.jsx(s,{size:13})}),c.jsx("span",{className:ne.label,children:e.label}),e.closable&&c.jsx("span",{className:ne.close,onClick:f=>{f.stopPropagation(),Kt(e.id)},children:c.jsx(Ot,{size:12})})]})}function hu({workspaceCwd:e,paneId:t}){const n=s=>()=>{e!==null&&s(e,t??void 0)};return c.jsxs(St,{children:[c.jsx(kt,{asChild:!0,children:c.jsx(_e,{className:ne.newTab,hoverBase:"var(--pi-color-background)",style:{borderRadius:"var(--pi-radius-sm)"},title:"New tab",disabled:!e,children:c.jsx(is,{size:14})})}),c.jsxs(Ct,{minWidth:160,sideOffset:4,children:[c.jsxs(H,{onSelect:n(jt),children:[c.jsx(us,{size:13,className:ne.itemIcon}),"New chat"]}),c.jsxs(H,{onSelect:n(Vs),children:[c.jsx(cs,{size:13,className:ne.itemIcon}),"New terminal"]}),c.jsxs(H,{onSelect:n(kl),children:[c.jsx(tn,{size:13,className:ne.itemIcon}),"New molecule view"]})]})]})}function mu({cwd:e,paneId:t}){const n=P(a=>{var l;return e===null||(l=a.layouts[e])==null?void 0:l.tree}),s=a=>()=>{if(e===null||t===null)return;const l=P.getState().splitEmpty(e,t,a);l!==null&&jt(e,l)},r=a=>n===void 0||t===null?"Open a workspace to split":tt(n,t,a)?null:"Maximum split depth reached",o=r("right"),i=r("bottom");return c.jsxs(c.Fragment,{children:[c.jsx(_e,{className:ne.splitAction,hoverBase:"var(--pi-color-background)",style:{borderRadius:"var(--pi-radius-sm)"},title:o??"Split right",disabled:o!==null,onClick:s("right"),children:c.jsx(Br,{size:14})}),c.jsx(_e,{className:ne.splitAction,hoverBase:"var(--pi-color-background)",style:{borderRadius:"var(--pi-radius-sm)"},title:i??"Split down",disabled:i!==null,onClick:s("bottom"),children:c.jsx(Or,{size:14})})]})}function Wn({cwd:e,paneId:t,style:n,focused:s=!1}){const r=T(f=>f.tabs),o=P(f=>f.focusPane),i=P(f=>{var m;return e===null||(m=f.layouts[e])==null?void 0:m.placement}),a=P(f=>{var m;return e===null||t===null||(m=f.layouts[e])==null?void 0:m.activeByPane[t]}),l=t===null?[]:r.filter(f=>(i==null?void 0:i[f.id])===t),{setNodeRef:u}=fs({id:`strip:${t??"none"}`,disabled:t===null,data:{type:"strip",paneId:t}});return c.jsxs("div",{ref:u,className:W(ne.strip,ne.paneStrip,s&&ne.focused),style:n,onPointerDown:()=>{e!==null&&t!==null&&o(e,t)},children:[c.jsx("div",{className:ne.tabs,children:c.jsx(co,{items:l.map(f=>f.id),strategy:lo,children:l.map(f=>c.jsx(pu,{tab:f,active:f.id===a},f.id))})}),c.jsx(hu,{workspaceCwd:e,paneId:t}),c.jsx(mu,{cwd:e,paneId:t})]})}const gu="_preview_1txmv_1",yu="_chip_1txmv_9",_u="_chipLabel_1txmv_23",Jt={preview:gu,chip:yu,chipLabel:_u};function wu({rect:e,region:t}){return c.jsx("div",{className:Jt.preview,style:Nd(e,t)})}function bu({tab:e}){const t=sr[e.kind];return c.jsxs("div",{className:Jt.chip,children:[c.jsx(t,{size:13}),c.jsx("span",{className:Jt.chipLabel,children:e.label})]})}const vu="_area_1kpjf_1",xu="_panel_1kpjf_10",Su="_dropZone_1kpjf_26",ku="_active_1kpjf_30",Iu="_empty_1kpjf_34",ju="_emptyStack_1kpjf_46",Tu="_emptyTitle_1kpjf_60",Cu="_emptyHint_1kpjf_64",ve={area:vu,panel:xu,dropZone:Su,active:ku,empty:Iu,emptyStack:ju,emptyTitle:Tu,emptyHint:Cu};function Eu({paneId:e,style:t}){const{setNodeRef:n}=fs({id:`pane:${e}`,data:{type:"pane",paneId:e}});return c.jsx("div",{ref:n,className:ve.dropZone,style:t,...Xd(e)})}function Ru(){const e=T(y=>y.tabs),t=T(y=>y.activeWorkspaceCwd),n=P(y=>t===null?void 0:y.layouts[t]),s=$(y=>y.status),r=E(y=>y.openCwdPicker),o=P(y=>y.focusPane),i=e.some(y=>y.workspaceCwd===t),a=b.useRef(null),l=b.useMemo(()=>$d(e,t,n),[e,t,n]),u=b.useMemo(()=>Pd(n),[n]),f=b.useMemo(()=>Dd(n),[n]),m=b.useMemo(()=>fn(n),[n]),h=Td(t),p=eu(t,a),w=h.preview??p.preview;return c.jsxs(po,{sensors:h.sensors,collisionDetection:h.collisionDetection,onDragStart:h.onDragStart,onDragMove:h.onDragMove,onDragEnd:h.onDragEnd,onDragCancel:h.onDragCancel,children:[c.jsxs("div",{className:ve.area,ref:a,onDragOver:p.onDragOver,onDragLeave:p.onDragLeave,onDrop:p.onDrop,children:[u.length===0?c.jsx(Wn,{cwd:t,paneId:null}):u.map(y=>c.jsx(Wn,{cwd:t,paneId:y.paneId,style:y.stripStyle,focused:y.focused},y.paneId)),t!==null&&f.length>0&&c.jsx(zd,{cwd:t,dividers:f,hostRef:a}),u.map(y=>c.jsx(Eu,{paneId:y.paneId,style:Qs(m.get(y.paneId))},`drop-${y.paneId}`)),w!==null&&m.has(w.paneId)&&c.jsx(wu,{rect:m.get(w.paneId),region:w.region}),t===null&&c.jsxs("div",{className:ve.emptyStack,children:[c.jsx("div",{className:ve.emptyTitle,children:"No workspace open"}),c.jsx("div",{className:ve.emptyHint,children:"Open a project folder to start a chat."}),c.jsx(se,{size:"sm",variant:"secondary",leftIcon:c.jsx(as,{size:14}),disabled:s!=="open",title:s!=="open"?"Connect to open a workspace":"Open a workspace folder",onClick:()=>r(),children:"Open Workspace"})]}),t!==null&&!i&&c.jsx("div",{className:ve.empty,children:"No open tabs in this workspace"}),e.map((y,v)=>{const I=Md[y.kind],j=l[v],B=n==null?void 0:n.placement[y.id];return c.jsx("div",{className:W(ve.panel,j.visible&&ve.active),style:j.style,onPointerDown:()=>{t!==null&&B!==void 0&&o(t,B)},children:c.jsx(b.Suspense,{fallback:c.jsx(kd,{size:"md"}),children:c.jsx(I,{tab:y,owningPaneId:Ad(y.id,n)})})},y.id)})]}),c.jsx(ho,{dropAnimation:null,children:h.draggedTab&&c.jsx(bu,{tab:h.draggedTab})})]})}const Ee={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 Mu(e){const t=e.kind==="directory"||e.type==="directory"?"directory":"file";return{name:e.name??"",kind:t,size:e.size,mtimeMs:e.mtimeMs}}function Nu(e){return e.slice().sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}async function rr(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 r="entries"in s?s.entries??[]:[];return{path:s.resolvedPath??t,entries:Nu(r.map(Mu))}}function Pu(e,t=!0){const n=$(s=>s.client);return jr({queryKey:Ee.explorer(e),queryFn:()=>{if(!n)throw new Error("not connected");return rr(n,e)},enabled:!!n&&!!e&&t})}function Du(e){const t=$(r=>r.client),n=b.useMemo(()=>Array.from(e),[e]),s=Tr({queries:n.map(r=>({queryKey:Ee.explorer(r),queryFn:()=>{if(!t)throw new Error("not connected");return rr(t,r)},enabled:!!t&&!!r}))});return b.useMemo(()=>{const r=new Map;return n.forEach((o,i)=>{const a=s[i];r.set(o,{listing:a==null?void 0:a.data,isLoading:!!(a!=null&&a.isLoading),isError:!!(a!=null&&a.isError),error:a==null?void 0:a.error})}),r},[n,s])}function Au(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="file_changed"&&"path"in e&&typeof e.path=="string"}function $u(e,t){const n=new Set,s=e.connection.onSessionMessage(r=>{const o=r;Au(o)&&n.has(o.path)&&t(o.path)});return{sync(r){for(const o of n)r.has(o)||(n.delete(o),e.connection.request("file_watch_unsubscribe",{path:o}).catch(()=>{}));for(const o of r)n.has(o)||(n.add(o),e.connection.request("file_watch_subscribe",{path:o}).then(i=>{const a=i;(a==null?void 0:a.ok)===!1&&console.warn(`useExplorerWatch: ${a.error??"subscribe failed"} for "${o}"`)}).catch(()=>{}))},dispose(){s();for(const r of n)e.connection.request("file_watch_unsubscribe",{path:r}).catch(()=>{});n.clear()}}}function qu(e){const t=$(i=>i.client),n=We(),s=b.useRef(null),r=b.useRef(null),o=Array.from(e).toSorted().join("\0");b.useEffect(()=>{var i,a;t&&(r.current!==t&&((i=s.current)==null||i.dispose(),s.current=$u(t,l=>{n.invalidateQueries({queryKey:Ee.explorer(l)})}),r.current=t),(a=s.current)==null||a.sync(new Set(o?o.split("\0"):[])))},[t,o,n]),b.useEffect(()=>()=>{var i;(i=s.current)==null||i.dispose(),s.current=null,r.current=null},[])}const Ln=new WeakMap;function Hn(e){let t=Ln.get(e);return t||(t=new gc(e),t.start(),Ln.set(e,t)),t}function Bu(e,t,n){const s=new Blob([Uint8Array.from(e)],{type:n||"application/octet-stream"}),r=URL.createObjectURL(s),o=document.createElement("a");o.href=r,o.download=t,o.rel="noopener",document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}function or(){const e=$(r=>r.daemon),t=We(),n=b.useCallback(async(r,o)=>{if(!e)throw new Error("not connected");const i=r?`${r}/${o.name}`:o.name,a=new Uint8Array(await o.arrayBuffer());await Hn(e).upload(i,a),await t.invalidateQueries({queryKey:["explorer"]})},[e,t]),s=b.useCallback(async r=>{if(!e)throw new Error("not connected");const o=await Hn(e).download(r);Bu(o.bytes,o.fileName||r.split("/").pop()||"download",o.mimeType)},[e]);return{upload:n,saveToDisk:s}}const Un={available:!1,branch:null,upstream:null,ahead:0,behind:0,detached:!1,conflictCount:0},de=xe()(e=>({subscribedCwd:null,changes:[],ignored:[],...Un,setSubscribedCwd:t=>e({subscribedCwd:t}),applyProjection:t=>{if(!t||!t.available){e({changes:[],ignored:[],...Un});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,ignored:t.ignored??[],available:!0,branch:t.branch,upstream:t.upstream,ahead:t.ahead,behind:t.behind,detached:t.detached,conflictCount:t.conflicted.length})}}));function Vh(e,t){return e?e.startsWith("/")||e.startsWith("~")?e:t?`${t.replace(/\/+$/,"")}/${e}`:null:null}function me(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):"/"}function Ou(e,t){return!t||!e.startsWith(t)?e:e.slice(t.length).replace(/^\/+/,"")}function Kh(e){if(!e.startsWith("/"))return e;const t=e.split("/"),n=[];for(const s of t)s===""||s==="."||(s===".."?n.length>0&&n.pop():n.push(s));return"/"+n.join("/")}function Vn(e,t,n){if(t.kind!=="file"&&t.kind!=="directory")return null;const s=t.kind==="directory"?t.path:me(t.path);if(s===me(e)||s===e||s.startsWith(`${e}/`)||s!==n&&!s.startsWith(`${n}/`))return null;const r=e.split("/").pop();return{destinationDir:s,destination:`${s}/${r}`}}function Kn(e,t){if(e.kind!=="file"&&e.kind!=="directory")return null;const n=e.kind==="directory"?e.path:me(e.path);return n!==t&&!n.startsWith(`${t}/`)?null:n}const zu={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 Fu(e,t,n){const s=await e.connection.request("file_move_request",{path:t,destination:n});if(!s.ok){const r=s.error??"";throw new Error(zu[r]??r??"Failed to move")}return s.destination??n}function Gn(e,t){return t===0?e:`${e} — closed ${t} ${t===1?"diff tab":"diff tabs"}`}function Wu(e){return`${e.kind}:${e.path}`}function ir(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}function ar(e,t,n,s,r,o,i){var l;(o==null?void 0:o.parentPath)===t&&e.push({kind:"draft",path:`${t}::draft`,depth:n,draftKind:o.kind,parentPath:t});const a=r.get(t);if(!a||a.isLoading){e.push({kind:"loading",path:t,depth:n});return}if(a.isError){const u=a.error instanceof Error?a.error.message:"failed to load";e.push({kind:"error",path:t,depth:n,message:u});return}for(const u of((l=a.listing)==null?void 0:l.entries)??[])Lu(e,t,u,n,s,r,o,i)}function Lu(e,t,n,s,r,o,i,a){const l=ir(t,n.name),u=n.kind==="directory",f=u&&r.has(l);l===a?e.push({kind:"rename",path:l,depth:s,name:n.name,isDirectory:u}):u?e.push({kind:"directory",path:l,name:n.name,depth:s,expanded:f}):e.push({kind:"file",path:l,name:n.name,depth:s}),f&&ar(e,l,s+1,r,o,i,a)}function Hu(e,t,n,s,r){if(!e)return[];const o=t.has(e),i=[{kind:"directory",path:e,name:e.split("/").pop()||e,depth:0,expanded:o}];return o&&ar(i,e,1,t,n,s,r),i}const Uu=()=>{};function Vu(e,t){return e===void 0?t:e==="deleted"||t==="deleted"?"deleted":e==="added"||t==="added"?"added":"modified"}function Ku(e){return e==="added"?"added":"modified"}function Gu(e,t){if(!e||t.length===0)return Uu;const n=e.replace(/\/+$/,""),s=new Map,r=new Map,o=[];for(const i of t){const a=i.path.endsWith("/"),l=a?i.path.slice(0,-1):i.path;if(!l)continue;const u=`${n}/${l}`;s.set(u,Vu(s.get(u),i.status)),a&&o.push(u);const f=Ku(i.status);let m=me(u);for(;m.length>n.length&&m.startsWith(n);){const h=r.get(m);r.set(m,h===void 0||h===f?f:"modified");const p=me(m);if(p===m)break;m=p}}return i=>{const a=s.get(i)??r.get(i);if(a!==void 0)return a;for(const l of o)if(i.startsWith(`${l}/`))return"added"}}const Yu=()=>!1;function Xu(e,t){if(!e||t.length===0)return Yu;const n=e.replace(/\/+$/,""),s=new Set,r=[];for(const o of t){const i=o.endsWith("/"),a=i?o.slice(0,-1):o;if(!a)continue;const l=`${n}/${a}`;s.add(l),i&&r.push(`${l}/`)}return o=>{if(s.has(o))return!0;for(const i of r)if(o.startsWith(i))return!0;return!1}}const Ju="_container_1wywk_1",Qu="_header_1wywk_7",Zu="_uploadButton_1wywk_14",ef="_hiddenInput_1wywk_33",tf="_status_1wywk_36",nf="_statusError_1wywk_37",sf="_rowAction_1wywk_50",rf="_item_1wywk_53",of="_list_1wywk_60",af="_active_1wywk_83",cf="_selected_1wywk_88",lf="_dropTarget_1wywk_92",df="_rootItem_1wywk_99",uf="_dirName_1wywk_98",ff="_chevronSlot_1wywk_104",pf="_chevron_1wywk_104",hf="_chevronOpen_1wywk_115",mf="_icon_1wywk_118",gf="_name_1wywk_125",yf="_gitAdded_1wywk_140",_f="_gitModified_1wywk_145",wf="_gitDeleted_1wywk_150",bf="_hiddenEntry_1wywk_162",vf="_statusRow_1wywk_171",xf="_statusRowError_1wywk_182",Sf="_draftInput_1wywk_185",D={container:Ju,header:Qu,uploadButton:Zu,hiddenInput:ef,status:tf,statusError:nf,rowAction:sf,item:rf,list:of,active:af,selected:cf,dropTarget:lf,rootItem:df,dirName:uf,chevronSlot:ff,chevron:pf,chevronOpen:hf,icon:mf,name:gf,gitAdded:yf,gitModified:_f,gitDeleted:wf,hiddenEntry:bf,statusRow:vf,statusRowError:xf,draftInput:Sf};function kf({draftKind:e,indentStyle:t,onSubmit:n,onCancel:s}){const[r,o]=b.useState("");return c.jsxs("div",{className:D.item,style:t,onClick:i=>i.stopPropagation(),children:[c.jsx("span",{className:D.chevronSlot}),c.jsx("span",{className:D.icon,children:e==="directory"?c.jsx(Me,{size:16}):c.jsx(nn,{size:16})}),c.jsx("input",{className:D.draftInput,autoFocus:!0,spellCheck:!1,placeholder:e==="directory"?"New folder":"New file",value:r,onChange:i=>o(i.target.value),onKeyDown:i=>{if(i.key==="Enter"){i.preventDefault();const a=r.trim();a?n(a):s()}else i.key==="Escape"&&(i.preventDefault(),s())},onBlur:s})]})}function If({name:e,isDirectory:t,indentStyle:n,onSubmit:s,onCancel:r}){const[o,i]=b.useState(e),a=b.useRef(null);return b.useEffect(()=>{const l=a.current;if(!l)return;l.focus();const u=e.lastIndexOf("."),f=t||u<=0?e.length:u;l.setSelectionRange(0,f)},[e,t]),c.jsxs("div",{className:D.item,style:n,onClick:l=>l.stopPropagation(),children:[c.jsx("span",{className:D.chevronSlot}),c.jsx("span",{className:D.icon,children:t?c.jsx(Me,{size:16}):c.jsx(nn,{size:16})}),c.jsx("input",{ref:a,className:D.draftInput,spellCheck:!1,value:o,onChange:l=>i(l.target.value),onKeyDown:l=>{if(l.key==="Enter"){l.preventDefault();const u=o.trim();!u||u===e?r():s(u)}else l.key==="Escape"&&(l.preventDefault(),r())},onBlur:r})]})}const jf=14,Tf={added:D.gitAdded,modified:D.gitModified,deleted:D.gitDeleted};function Cf({row:e,active:t,selected:n,dropTarget:s,gitStatus:r,hidden:o,isRoot:i,onToggle:a,onOpenFile:l,onContextMenu:u,onSubmitDraft:f,onCancelDraft:m,onSubmitRename:h,onCancelRename:p,onDragStartRow:w,onDragEndRow:y}){const v={paddingLeft:8+e.depth*jf};if(e.kind==="loading")return c.jsx("div",{className:D.statusRow,style:v,children:"Loading…"});if(e.kind==="error")return c.jsx("div",{className:W(D.statusRow,D.statusRowError),style:v,children:e.message??"failed to load"});if(e.kind==="draft")return c.jsx(kf,{draftKind:e.draftKind,indentStyle:v,onSubmit:j=>f(e.parentPath,j),onCancel:m});if(e.kind==="rename")return c.jsx(If,{name:e.name,isDirectory:e.isDirectory,indentStyle:v,onSubmit:j=>h(e.path,j),onCancel:p});const I=e.kind==="directory";return c.jsxs("div",{className:W(D.item,i&&D.rootItem,t&&D.active,n&&D.selected,s&&D.dropTarget,r&&Tf[r],o&&D.hiddenEntry),style:v,title:e.path,draggable:!i,onDragStart:j=>w(e.path,I,j),onDragEnd:y,onClick:()=>I?a(e.path):l(e.path),onContextMenu:j=>{j.preventDefault(),j.stopPropagation(),u(e.path,I,j.clientX,j.clientY)},children:[c.jsx("span",{className:D.chevronSlot,children:I&&c.jsx(en,{size:14,className:W(D.chevron,e.expanded&&D.chevronOpen)})}),c.jsx("span",{className:D.icon,children:I?c.jsx(Me,{size:16}):c.jsx(nn,{size:16})}),c.jsx("span",{className:I?D.dirName:D.name,children:e.name}),c.jsx(_e,{className:D.rowAction,title:"Actions",onClick:j=>{j.stopPropagation();const B=j.currentTarget.getBoundingClientRect();u(e.path,I,B.left,B.bottom)},children:c.jsx(Qt,{size:14})})]})}async function Yn(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 Ef={empty_path:"Nothing to delete.",not_found:"That item no longer exists."};async function Rf(e,t){const n=await e.connection.request("file_delete_request",{path:t});if(!n.ok){const s=n.error??"";throw new Error(Ef[s]??s??"Failed to delete")}}function Mf(){const e=E(M=>M.fileMenu),t=E(M=>M.closeFileMenu),n=$(M=>M.client),s=te(M=>M.startDraft),r=te(M=>M.startRename),o=te(M=>M.rootPath),i=T(M=>M.activeWorkspaceCwd),{saveToDisk:a}=or(),l=We(),u=b.useRef(null),[f,m]=b.useState(!1);if(b.useEffect(()=>{m(e!==null)},[e]),!e)return null;const h=e.path.split("/").pop()||e.path;function p(M){m(M),M||t()}function w(){e&&(t(),pn(e.path,i||"~"))}function y(){e&&(t(),nr(e.path,i||"~"))}function v(){e&&(t(),tr(e.path,i||"~"))}async function I(){if(e){t();try{await Yn(e.path)}catch{window.alert("Failed to copy to clipboard.")}}}async function j(){if(e){t();try{await Yn(Ou(e.path,o)||"/")}catch{window.alert("Failed to copy to clipboard.")}}}async function B(){if(e){t();try{await a(e.path)}catch(M){window.alert(`Failed to download: ${M instanceof Error?M.message:String(M)}`)}}}async function z(){if(!e)return;const M=e.isDirectory?"folder (and everything inside it)":"file";if(!window.confirm(`Permanently delete this ${M}? "${h}" — this cannot be undone.`))return t();if(t(),!n){window.alert("Not connected — cannot delete remotely.");return}try{await Rf(n,e.path),await l.invalidateQueries({queryKey:["explorer"]}),T.getState().closeByPathPrefix(e.path)}catch(Z){window.alert(`Failed to delete: ${Z instanceof Error?Z.message:String(Z)}`)}}function Q(M){if(!e)return;const Z=e.isDirectory?e.path:me(e.path);t(),s(Z,M)}function G(){e&&(t(),r(e.path))}return c.jsxs(St,{open:f,onOpenChange:p,modal:!1,children:[c.jsx(kt,{asChild:!0,children:c.jsx(dn,{ref:u,x:e.x,y:e.y})}),c.jsx(Ct,{minWidth:140,children:e.background?c.jsxs(c.Fragment,{children:[c.jsxs(H,{onSelect:()=>Q("file"),children:[c.jsx(zt,{size:13}),"New File"]}),c.jsxs(H,{onSelect:()=>Q("directory"),children:[c.jsx(yt,{size:13}),"New Folder"]}),c.jsx(Te,{}),c.jsxs(H,{onSelect:I,children:[c.jsx(ct,{size:13}),"Copy Current Directory Path"]}),c.jsxs(H,{onSelect:j,children:[c.jsx(ct,{size:13}),"Copy Current Directory Relative Path"]})]}):c.jsxs(c.Fragment,{children:[!e.isDirectory&&c.jsxs(c.Fragment,{children:[c.jsxs(H,{onSelect:w,children:[c.jsx(zr,{size:13}),"Open"]}),c.jsxs(H,{onSelect:y,children:[c.jsx(tn,{size:13}),"Open in MolViewer"]}),er(e.path)&&c.jsxs(H,{onSelect:v,children:[c.jsx(ds,{size:13}),"Open as Text"]}),c.jsx(Te,{})]}),e.isDirectory&&c.jsxs(c.Fragment,{children:[c.jsxs(H,{onSelect:()=>Q("file"),children:[c.jsx(zt,{size:13}),"New File"]}),c.jsxs(H,{onSelect:()=>Q("directory"),children:[c.jsx(yt,{size:13}),"New Folder"]}),c.jsx(Te,{})]}),c.jsxs(H,{onSelect:I,children:[c.jsx(ct,{size:13}),"Copy Absolute Path"]}),c.jsxs(H,{onSelect:j,children:[c.jsx(ct,{size:13}),"Copy Relative Path"]}),c.jsx(Te,{}),!e.isDirectory&&c.jsxs(c.Fragment,{children:[c.jsxs(H,{onSelect:B,children:[c.jsx(Fr,{size:13}),"Download"]}),c.jsx(Te,{})]}),c.jsxs(H,{onSelect:G,children:[c.jsx(os,{size:13}),"Rename"]}),c.jsxs(H,{danger:!0,onSelect:z,children:[c.jsx(Zt,{size:13}),"Delete"]})]})})]})}const Nf={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."};class Pf extends Error{constructor(t,n){super(n),this.code=t,this.name="CreateEntryError"}}async function cr(e,t,n,s){const r=await e.connection.request("file_create_request",{path:t,name:n,kind:s});if(!r.ok){const o=r.error??"";throw new Pf(o,Nf[o]??o??"Failed to create")}return r.path??(t.endsWith("/")?`${t}${n}`:`${t}/${n}`)}const Df=28,Ke="application/x-pi-studio-path",qt="Files";function Af(){const e=$(_=>_.client),t=te(_=>_.rootPath),n=te(_=>_.expanded),s=te(_=>_.setRoot),r=te(_=>_.toggle),o=te(_=>_.draft),i=te(_=>_.startDraft),a=te(_=>_.cancelDraft),l=te(_=>_.renaming),u=te(_=>_.cancelRename),f=te(_=>_.selected),m=te(_=>_.setSelected),h=T(_=>_.activeWorkspaceCwd),p=T(_=>_.tabs.find(k=>k.id===_.activeTabId)),w=de(_=>_.changes),y=de(_=>_.ignored),{upload:v}=or(),I=E(_=>_.openFileMenu),j=We(),[B,z]=b.useState(null),[Q,G]=b.useState(null),M=b.useRef(null),Z=b.useRef(null),re=b.useRef(null),oe=b.useRef(null),ee=(p==null?void 0:p.kind)==="file"||(p==null?void 0:p.kind)==="molecule"?p.data.path:null,ue=f?f.isDirectory?f.path:me(f.path):t,it=b.useRef(null);b.useEffect(()=>{if(!e)return;const _=h||"~";it.current!==_&&(it.current=_,Ml(e,_).then(k=>s(k)))},[e,h,s]);const C=Du(n);qu(n);const ce=b.useMemo(()=>Hu(t,n,C,o,l),[t,n,C,o,l]),pr=b.useMemo(()=>Gu(t,w),[t,w]),hr=b.useMemo(()=>Xu(t,y),[t,y]),mn=Cr({count:ce.length,getScrollElement:()=>Z.current,estimateSize:()=>Df,overscan:12,getItemKey:_=>{const k=ce[_];return k?Wu(k):_}});function Et(_){pn(_,h||"~")}function mr(_,k,q){q.dataTransfer.setData(Ke,_),k||q.dataTransfer.setData(ot.path,_),q.dataTransfer.effectAllowed=k?"move":"copyMove",re.current=_}function gr(){re.current=null}function Rt(){G(null),oe.current&&(clearTimeout(oe.current.timer),oe.current=null)}function gn(_){var q;if(((q=oe.current)==null?void 0:q.path)===_.path||(oe.current&&clearTimeout(oe.current.timer),oe.current=null,_.kind!=="directory"||_.expanded))return;const k=window.setTimeout(()=>r(_.path),700);oe.current={path:_.path,timer:k}}async function yn(_,k){if(!e)throw new Error("Not connected.");const q=await Fu(e,_,k),R=me(q);await j.invalidateQueries({queryKey:Ee.explorer(me(_))}),await j.invalidateQueries({queryKey:Ee.explorer(R)}),te.getState().repathAfterMove(_,q,R);const L=T.getState().tabs.filter(le=>{if(le.kind!=="file"&&le.kind!=="diff"&&le.kind!=="molecule")return!1;const at=le.data.path;return at===_||((at==null?void 0:at.startsWith(`${_}/`))??!1)}),fe=L.some(le=>(le.kind==="file"||le.kind==="molecule")&&le.data.path===_),Y=L.filter(le=>le.kind==="diff").length;return T.getState().closeByPathPrefix(_),fe&&Et(q),{destination:q,closedDiffs:Y}}async function yr(_,k){const q=Vn(_,k,t);if(!q||!e)return;const R=_.split("/").pop()??_;z({text:`Moving ${R}…`,error:!1});try{const{destination:L,closedDiffs:fe}=await yn(_,q.destination);z({text:Gn(`Moved to ${me(L).split("/").pop()||"/"}`,fe),error:!1})}catch(L){z({text:L instanceof Error?L.message:"Failed to move",error:!0})}}async function _r(_,k){const q=(o==null?void 0:o.kind)??"file";if(a(),!!e)try{const R=await cr(e,_,k,q);await j.invalidateQueries({queryKey:Ee.explorer(_)}),z({text:`Created ${R}`,error:!1}),q==="file"&&Et(R)}catch(R){z({text:R instanceof Error?R.message:"Failed to create",error:!0})}}async function wr(_,k){if(u(),!e)return;const q=ir(me(_),k);z({text:`Renaming ${_.split("/").pop()}…`,error:!1});try{const{destination:R,closedDiffs:L}=await yn(_,q);z({text:Gn(`Renamed to ${R.split("/").pop()}`,L),error:!1})}catch(R){z({text:R instanceof Error?R.message:"Failed to rename",error:!0})}}async function _n(_,k){var fe;if(!k.length||!_)return;const q=(fe=C.get(_))==null?void 0:fe.listing,R=new Set((q==null?void 0:q.entries.map(Y=>Y.name))??[]),L=k.filter(Y=>R.has(Y.name));if(L.length>0){const Y=L.map(le=>le.name).join(", ");if(!window.confirm(`Overwrite ${L.length>1?"these files":"this file"}? ${Y}`))return}z({text:`Uploading ${k.length} file${k.length>1?"s":""}…`,error:!1});try{for(const Y of k)await v(_,Y);z({text:`Uploaded ${k.length} file${k.length>1?"s":""}`,error:!1})}catch(Y){z({text:`Upload failed: ${Y instanceof Error?Y.message:"unknown"}`,error:!0})}}function wn(_,k){if(_.preventDefault(),_.dataTransfer.types.includes(Ke)){const L=_.dataTransfer.getData(Ke)||re.current;Rt(),L&&yr(L,k??{kind:"directory",path:t});return}if(Rt(),!_.dataTransfer.types.includes(qt))return;const q=k?Kn(k,t):t;if(!q)return;const R=Array.from(_.dataTransfer.files);R.length&&_n(q,R)}function br(_){const k=_.dataTransfer.types.includes(Ke);!k&&!_.dataTransfer.types.includes(qt)||(_.preventDefault(),_.dataTransfer.dropEffect=k?"move":"copy")}return e?c.jsxs("div",{className:D.container,onDragOver:br,onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||Rt()},onDrop:_=>wn(_),children:[c.jsxs("div",{className:D.header,children:[c.jsx("button",{type:"button",className:D.uploadButton,onClick:()=>i(ue,"file"),disabled:!t,title:f?`New file in ${ue.split("/").pop()||"/"}`:"New file in workspace root",children:c.jsx(zt,{size:14})}),c.jsx("button",{type:"button",className:D.uploadButton,onClick:()=>i(ue,"directory"),disabled:!t,title:f?`New folder in ${ue.split("/").pop()||"/"}`:"New folder in workspace root",children:c.jsx(yt,{size:14})}),c.jsxs("button",{type:"button",className:D.uploadButton,onClick:()=>{var _;return(_=M.current)==null?void 0:_.click()},disabled:!t,title:"Upload files to the workspace root",children:[c.jsx(Wr,{size:14}),c.jsx("span",{children:"Upload"})]}),c.jsx("input",{ref:M,type:"file",multiple:!0,className:D.hiddenInput,onChange:_=>{_n(t,Array.from(_.target.files??[])),_.target.value=""}})]}),B&&c.jsx("div",{className:B.error?D.statusError:D.status,children:B.text}),c.jsxs("div",{className:D.list,ref:Z,onContextMenu:_=>{_.preventDefault(),I(t,!0,_.clientX,_.clientY,!0)},children:[ce.length===0&&c.jsx(Ce,{children:"No files loaded"}),c.jsx("div",{style:{position:"relative",height:mn.getTotalSize()},children:mn.getVirtualItems().map(_=>{const k=ce[_.index];if(!k)return null;const q=k.path===t&&k.kind==="directory";return c.jsx("div",{"data-index":_.index,style:{position:"absolute",top:0,left:0,width:"100%",height:_.size,transform:`translateY(${_.start}px)`},onDragEnter:R=>{if(R.dataTransfer.types.includes(Ke)){const fe=re.current;if(!fe)return;const Y=Vn(fe,k,t);G(Y?k.path:null),gn(k);return}if(!R.dataTransfer.types.includes(qt))return;const L=Kn(k,t);G(L?k.path:null),gn(k)},onDrop:R=>{R.stopPropagation(),wn(R,k)},children:c.jsx(Cf,{row:k,active:(k.kind==="file"||k.kind==="directory")&&k.path===ee,selected:(k.kind==="file"||k.kind==="directory")&&k.path===(f==null?void 0:f.path),gitStatus:!q&&(k.kind==="file"||k.kind==="directory")?pr(k.path):void 0,hidden:!q&&(k.kind==="file"||k.kind==="directory")&&(k.name.startsWith(".")||hr(k.path)),isRoot:q,onToggle:R=>{m({path:R,isDirectory:!0}),r(R)},onOpenFile:R=>{m({path:R,isDirectory:!1}),Et(R)},onContextMenu:(R,L,fe,Y)=>I(R,L,fe,Y,q),onSubmitDraft:(R,L)=>void _r(R,L),onCancelDraft:a,onSubmitRename:(R,L)=>void wr(R,L),onCancelRename:u,onDragStartRow:mr,onDragEndRow:gr,dropTarget:(k.kind==="file"||k.kind==="directory")&&k.path===Q})},_.key)})})]}),c.jsx(Mf,{})]}):c.jsx(Ce,{children:"Connect to browse files"})}const $f="_list_1n3q6_1",qf="_summary_1n3q6_4",Bf="_item_1n3q6_11",Of="_badge_1n3q6_23",zf="_added_1n3q6_30",Ff="_modified_1n3q6_34",Wf="_deleted_1n3q6_38",Lf="_name_1n3q6_42",De={list:$f,summary:qf,item:Bf,badge:Of,added:zf,modified:Ff,deleted:Wf,name:Lf},Hf={added:"A",modified:"M",deleted:"D"};function Uf(){const t=T(o=>o.activeWorkspaceCwd)||"~",n=de(o=>o.changes),s=T(o=>o.open);function r(o,i){s({id:K.diff(o,i),kind:"diff",label:o.split("/").pop()||o,closable:!0,data:{path:o,staged:i},workspaceCwd:t})}return n.length===0?c.jsx(Ce,{children:"No changes detected"}):c.jsxs("div",{className:De.list,children:[c.jsxs("div",{className:De.summary,children:[n.length," changed file",n.length===1?"":"s"]}),n.map((o,i)=>c.jsxs("div",{className:De.item,onClick:()=>r(o.path,o.staged),children:[c.jsx("span",{className:W(De.badge,De[o.status]),children:Hf[o.status]}),c.jsx("span",{className:De.name,children:o.path})]},`${o.path}-${o.staged}-${i}`))]})}const Vf="_tabBar_1tvri_1",Kf="_tabBtn_1tvri_7",Gf="_active_1tvri_23",Yf="_refreshBtn_1tvri_27",Xf="_content_1tvri_31",Ie={tabBar:Vf,tabBtn:Kf,active:Gf,refreshBtn:Yf,content:Xf};function Jf(){const e=E(a=>a.rightSidebarTab),t=E(a=>a.setRightSidebarTab),s=T(a=>a.activeWorkspaceCwd)||"~",r=$(a=>a.client),o=We();function i(){o.invalidateQueries({queryKey:["explorer"]}),r&&s&&r.connection.request("checkout_refresh_request",{cwd:s}).catch(()=>{})}return c.jsxs(Ks,{children:[c.jsxs("div",{className:Ie.tabBar,children:[c.jsxs("button",{type:"button",className:W(Ie.tabBtn,e==="files"&&Ie.active),onClick:()=>t("files"),children:[c.jsx(Me,{size:13}),"Files"]}),c.jsxs("button",{type:"button",className:W(Ie.tabBtn,e==="changes"&&Ie.active),onClick:()=>t("changes"),children:[c.jsx(ls,{size:13}),"Changes"]}),c.jsx(se,{size:"xs",variant:"ghost",iconOnly:!0,title:"Refresh",className:Ie.refreshBtn,onClick:i,children:c.jsx(Lr,{size:13})})]}),c.jsx("div",{className:Ie.content,children:e==="files"?c.jsx(Af,{}):c.jsx(Uf,{})})]})}const lr=xe()(e=>({bySession:{},setStats(t,n){e(s=>({bySession:{...s.bySession,[t]:{...s.bySession[t],...n}}}))},clear(t){e(n=>{const{[t]:s,...r}=n.bySession;return{bySession:r}})}})),Qf=12e3;function Zf(e,t){return e==="running"&&t!=="running"}function Xn(e,t){var s,r,o,i,a,l;const n={};((s=t.contextUsage)==null?void 0:s.tokens)!=null&&(n.contextTokens=t.contextUsage.tokens),((r=t.contextUsage)==null?void 0:r.contextWindow)!==void 0&&(n.contextWindow=t.contextUsage.contextWindow),((o=t.contextUsage)==null?void 0:o.percent)!=null&&(n.contextPercent=t.contextUsage.percent),((i=t.tokens)==null?void 0:i.total)!==void 0&&(n.totalTokens=t.tokens.total),((a=t.tokens)==null?void 0:a.input)!==void 0&&(n.inputTokens=t.tokens.input),((l=t.tokens)==null?void 0:l.output)!==void 0&&(n.outputTokens=t.tokens.output),t.cost!==void 0&&(n.cost=t.cost),t.model!==void 0&&(n.model=t.model,N.getState().setModel(e,t.model)),lr.getState().setStats(e,n)}function ep(e){const t=$(a=>a.client),n=$(a=>a.status),s=N(a=>{var l;return e?((l=a.sessions[e])==null?void 0:l.agentId)??null:null}),r=N(a=>{var l;return e?(l=a.sessions[e])==null?void 0:l.status:void 0}),o=b.useRef(!1),i=b.useRef(void 0);b.useEffect(()=>{if(n!=="open"||!t||!e||!s)return;let a=!1;const l=async()=>{if(!o.current){o.current=!0;try{const f=await t.agent(s).sessionStats();a||Xn(e,f)}catch{}finally{o.current=!1}}};l();const u=setInterval(()=>void l(),Qf);return()=>{a=!0,clearInterval(u)}},[n,t,e,s]),b.useEffect(()=>{const a=i.current;i.current=r,Zf(a,r)&&(n!=="open"||!t||!e||!s||(o.current=!1,t.agent(s).sessionStats().then(l=>Xn(e,l)).catch(()=>{})))},[r,n,t,e,s])}function tp(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 np(e){const t=$(o=>o.client),n=de(o=>o.applyProjection),s=de(o=>o.setSubscribedCwd),r=b.useRef(t);return r.current=t,b.useEffect(()=>{if(!t||!e)return;let o=!1;t.connection.request("checkout_status_subscribe",{cwd:e}).catch(()=>{}),s(e);const i=t.connection.onSessionMessage(a=>{if(o)return;const l=a;tp(l)&&l.cwd===e&&n(l.projection)});return t.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{}),()=>{o=!0,i(),t.connection.request("checkout_status_unsubscribe",{cwd:e}).catch(()=>{}),s(null)}},[t,e,n,s]),{refresh(){const o=r.current;!o||!e||o.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{})}}}const hn="--";function Ge(e){return e===void 0?hn:e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function sp(e){if(e==null)return hn;const t=e<=1?e*100:e;return`${Math.round(t)}%`}function rp(e){if(e===void 0)return hn;const t=e<1?4:2;return`$${e.toFixed(t)}`}function op(e,t){return t?e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e:e}function ip(e,t){const n=[];return e>0&&n.push(`↑${e}`),t>0&&n.push(`↓${t}`),n.join(" ")}const ap="_statusBar_t655h_1",cp="_segmentGroup_t655h_16",lp="_chevron_t655h_20",dp="_segment_t655h_16",up="_icon_t655h_33",fp="_text_t655h_39",Ae={statusBar:ap,segmentGroup:cp,chevron:lp,segment:dp,icon:up,text:fp};function pp(){const e=N(p=>p.activeSessionId),t=N(p=>e?p.sessions[e]:void 0),n=rt(),s=T(p=>p.activeWorkspaceCwd);np(s||"");const r=de(p=>p.available),o=de(p=>p.branch),i=de(p=>p.ahead),a=de(p=>p.behind),l=de(p=>p.detached),u=de(p=>p.conflictCount),f=de(p=>p.changes.length),m=lr(p=>e?p.bySession[e]:void 0);ep(e);const h=[];if(t){const p=op(t.cwd,n);h.push({key:"cwd",icon:c.jsx(Me,{size:13}),text:p,title:t.cwd})}if(r){const p=ip(i,a),w=[l?"(detached)":o??"?"];p&&w.push(p),f>0&&w.push(`●${f}`),u>0&&w.push(`⚠${u}`),h.push({key:"branch",icon:c.jsx(Hr,{size:13}),text:w.join(" ")})}if(t){const p=`${sp(m==null?void 0:m.contextPercent)} (${Ge(m==null?void 0:m.contextTokens)}/${Ge(m==null?void 0:m.contextWindow)})`;h.push({key:"context",icon:c.jsx(Ur,{size:13}),text:p}),h.push({key:"tokens",icon:c.jsx(Vr,{size:13}),text:Ge(m==null?void 0:m.totalTokens),title:`in ${Ge(m==null?void 0:m.inputTokens)} / out ${Ge(m==null?void 0:m.outputTokens)}`}),h.push({key:"cost",icon:c.jsx(Kr,{size:13}),text:rp(m==null?void 0:m.cost)})}return c.jsx("div",{className:Ae.statusBar,children:h.map((p,w)=>c.jsxs("span",{className:Ae.segmentGroup,children:[w>0&&c.jsx(en,{size:12,className:Ae.chevron,"aria-hidden":"true"}),c.jsxs("span",{className:Ae.segment,title:p.title,children:[c.jsx("span",{className:Ae.icon,children:p.icon}),c.jsx("span",{className:Ae.text,children:p.text})]})]},p.key))})}const hp="_wrapper_14joh_3",mp="_box_14joh_18",gp="_checkmark_14joh_38",yp="_nativeInput_14joh_43",ht={wrapper:hp,box:mp,checkmark:gp,nativeInput:yp};b.forwardRef(function({label:t,checked:n=!1,disabled:s,className:r,onChange:o,...i},a){return c.jsxs("label",{className:ht.wrapper,"data-disabled":s||void 0,children:[c.jsx("input",{ref:a,type:"checkbox",className:ht.nativeInput,checked:n,disabled:s,onChange:o,...i}),c.jsx("span",{className:ht.box,"data-checked":n,"aria-hidden":!0,children:n&&c.jsx(Gr,{size:12,className:ht.checkmark})}),t&&c.jsx("span",{children:t})]})});const _p="_select_dl3mw_3",wp={select:_p};b.forwardRef(function({options:t,placeholder:n,className:s,...r},o){return c.jsxs("select",{ref:o,className:W(wp.select,s),...r,children:[n&&c.jsx("option",{value:"",disabled:!0,children:n}),t.map(i=>c.jsx("option",{value:i.value,children:i.label},i.value))]})});const bp="_overlay_1k4ng_1",vp="_contentWrapper_1k4ng_7",xp="_dialog_1k4ng_16",Sp="_header_1k4ng_28",kp="_title_1k4ng_36",Ip="_body_1k4ng_43",jp="_footer_1k4ng_49",Tp="_bare_1k4ng_58",Cp="_bareBody_1k4ng_64",Ep="_bareCloseBtn_1k4ng_68",Rp="_visuallyHidden_1k4ng_73",he={overlay:bp,contentWrapper:vp,dialog:xp,header:Sp,title:kp,body:Ip,footer:jp,bare:Tp,bareBody:Cp,bareCloseBtn:Ep,visuallyHidden:Rp},Mp=Ft;function Np({open:e,onOpenChange:t,title:n,children:s,footer:r,width:o,className:i,bare:a=!1}){return c.jsx(eo,{open:e,onOpenChange:t,children:c.jsxs(to,{children:[c.jsx(no,{className:he.overlay}),c.jsx("div",{className:he.contentWrapper,children:c.jsxs(so,{className:W(he.dialog,a&&he.bare,i),style:o!==void 0?{width:o}:void 0,children:[a?c.jsx(bn,{className:he.visuallyHidden,children:n}):c.jsxs("div",{className:he.header,children:[c.jsx(bn,{className:he.title,children:n}),c.jsx(Ft,{asChild:!0,children:c.jsx(_e,{size:"sm","aria-label":"Close",children:c.jsx(Ot,{size:16})})})]}),c.jsx("div",{className:W(he.body,a&&he.bareBody),children:s}),a&&c.jsx(Ft,{asChild:!0,children:c.jsx(_e,{size:"sm","aria-label":"Close",className:he.bareCloseBtn,style:{background:"var(--pi-color-surface1)",border:"1px solid var(--pi-color-border)",borderRadius:"50%"},children:c.jsx(Ot,{size:16})})}),r&&c.jsx("div",{className:he.footer,children:r})]})})]})})}const Pp="_handle_1j18v_1",Dp={handle:Pp};function Jn({side:e,onResize:t,className:n}){const s=b.useRef(0),r=b.useCallback(a=>{const l=a.clientX-s.current;s.current=a.clientX,t(e==="left"?l:-l)},[t,e]),o=b.useCallback(a=>{var l,u;window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),document.body.style.cursor="",document.body.style.userSelect="",(u=(l=a.target)==null?void 0:l.releasePointerCapture)==null||u.call(l,a.pointerId)},[r]);function i(a){a.preventDefault(),s.current=a.clientX,document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",r),window.addEventListener("pointerup",o)}return c.jsx("div",{className:W(Dp.handle,n),onPointerDown:i,role:"separator","aria-orientation":"vertical"})}function Ap(e,t){const{order:n,sessions:s}=N.getState(),o=un(n,s,t).find(i=>i.cwd===e);if(o!=null&&o.sessions[0]){const i=o.sessions[0].id;N.getState().activate(i);const a=N.getState().sessions[i];T.getState().open({id:K.chat(i),kind:"chat",label:(a==null?void 0:a.title)??"New chat",closable:!0,data:{sessionId:i},workspaceCwd:e})}else jt(e);E.getState().setCwd(e)}const $p="_pathRow_1mu84_1",qp="_pathInput_1mu84_9",Bp="_createRow_1mu84_13",Op="_createInput_1mu84_21",zp="_createError_1mu84_25",Fp="_list_1mu84_30",Wp="_item_1mu84_37",Lp="_name_1mu84_49",be={pathRow:$p,pathInput:qp,createRow:Bp,createInput:Op,createError:zp,list:Fp,item:Wp,name:Lp};function Hp(){const e=E(C=>C.cwdPickerOpen),t=E(C=>C.closeCwdPicker),n=T(C=>C.activeWorkspaceCwd),s=E(C=>C.cwd),r=$(C=>C.client),o=rt(),[i,a]=b.useState("/"),[l,u]=b.useState("/"),[f,m]=b.useState(!1),[h,p]=b.useState(""),[w,y]=b.useState(null),[v,I]=b.useState(!1),j=We();b.useEffect(()=>{if(!e)return;const C=Ne(n||s||"~",o);a(C),u(C),Z()},[e,r,n,s]);const{data:B,isLoading:z,isError:Q,error:G}=Pu(i,e&&!!r),M=((B==null?void 0:B.entries)??[]).filter(C=>C.kind==="directory");function Z(){m(!1),p(""),y(null)}function re(C){const ce=C.length>1?C.replace(/\/+$/,"")||"/":C;a(ce),u(ce),Z()}function oe(){re(i.split("/").slice(0,-1).join("/")||"/")}function ee(){re(l.trim())}async function ue(){const C=h.trim();if(!(!C||!r||v)){I(!0),y(null);try{const ce=await cr(r,i,C,"directory");await j.invalidateQueries({queryKey:Ee.explorer(i)}),re(ce)}catch(ce){y(ce instanceof Error?ce.message:"Failed to create folder")}finally{I(!1)}}}function it(){Ap(i,o),t()}return c.jsxs(Np,{open:e,onOpenChange:C=>!C&&t(),title:"Open Workspace",footer:c.jsxs(c.Fragment,{children:[c.jsx(Mp,{asChild:!0,children:c.jsx(se,{size:"sm",variant:"secondary",children:"Cancel"})}),c.jsx(se,{size:"sm",onClick:it,children:"Open this folder"})]}),children:[c.jsxs("div",{className:be.pathRow,children:[c.jsx(se,{size:"xs",variant:"ghost",iconOnly:!0,title:"Up",onClick:oe,children:c.jsx(Yr,{size:13})}),c.jsx(wt,{className:be.pathInput,value:l,onChange:C=>u(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),ee())}}),c.jsx(se,{size:"xs",onClick:ee,children:"Go"}),c.jsx(se,{size:"xs",variant:"ghost",iconOnly:!0,title:"New folder",disabled:!r||Q||f,onClick:()=>{m(!0),p(""),y(null)},children:c.jsx(yt,{size:13})})]}),f&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:be.createRow,children:[c.jsx(Me,{size:14}),c.jsx(wt,{className:be.createInput,autoFocus:!0,placeholder:"New folder name",value:h,onChange:C=>p(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),ue()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),Z())}}),c.jsx(se,{size:"xs",loading:v,disabled:!h.trim()||v,onClick:()=>void ue(),children:"Create"}),c.jsx(se,{size:"xs",variant:"secondary",onClick:Z,children:"Cancel"})]}),w&&c.jsx("div",{className:be.createError,children:w})]}),c.jsx("div",{className:be.list,children:z?c.jsx(Ce,{children:"Loading..."}):Q?c.jsxs(Ce,{children:["Error: ",G instanceof Error?G.message:"unknown error"]}):M.length===0?c.jsx(Ce,{children:"No subdirectories"}):M.map(C=>c.jsxs("div",{className:be.item,onClick:()=>re(i==="/"?`/${C.name}`:`${i}/${C.name}`),children:[c.jsx(Me,{size:14}),c.jsx("span",{className:be.name,children:C.name})]},C.name))})]})}const Up="_shell_570m8_1",Vp="_main_570m8_7",Kp="_sidebarLeft_570m8_13",Gp="_leftHandle_570m8_25",Yp="_center_570m8_28",Xp="_sidebarRight_570m8_35",Jp="_rightHandle_570m8_43",je={shell:Up,main:Vp,sidebarLeft:Kp,leftHandle:Gp,center:Yp,sidebarRight:Xp,rightHandle:Jp};function Qp(){const e=E(i=>i.leftSidebarCollapsed),t=E(i=>i.rightSidebarCollapsed),n=E(i=>i.leftSidebarWidth),s=E(i=>i.rightSidebarWidth),r=E(i=>i.resizeLeftSidebar),o=E(i=>i.resizeRightSidebar);return c.jsxs("div",{className:je.shell,children:[c.jsx(Kc,{}),c.jsxs("div",{className:je.main,children:[!e&&c.jsxs("aside",{className:je.sidebarLeft,style:{width:n},children:[c.jsx(wd,{}),c.jsx(Jn,{side:"left",className:je.leftHandle,onResize:r})]}),c.jsx("div",{className:je.center,children:c.jsx(Ru,{})}),!t&&c.jsxs("aside",{className:je.sidebarRight,style:{width:s},children:[c.jsx(Jn,{side:"right",className:je.rightHandle,onResize:o}),c.jsx(Jf,{})]})]}),c.jsx(pp,{}),c.jsx(Hp,{})]})}function Zp(){const e=b.useRef(!1);b.useEffect(()=>{if(e.current)return;if(e.current=!0,window.location.hash.includes("offer=")){const l=window.location.href;E.getState().setHost(l),$.getState().connect({url:l});return}const t=new URLSearchParams(window.location.search),n=t.get("host"),s=t.get("pair"),r=t.get("password"),o=t.get("cwd"),i=t.get("connect")==="1",a=E.getState();if(s?a.setHost(s):n&&a.setHost(n),r&&a.setPassword(r),o&&a.setCwd(o),s)$.getState().connect({url:s});else if(i){const{host:l,password:u}=E.getState();$.getState().connect({url:l,password:u||void 0})}},[])}const dr="pi-studio-pane-layout",eh=250;function th(){const e=new Map,t={workspaces:e,activeWorkspaceCwd:null},n=rn.get(dr);if(!n)return t;let s;try{s=JSON.parse(n)}catch{return t}if(typeof s!="object"||s===null)return t;const r=s;if(r.version!==Ws||typeof r.workspaces!="object"||r.workspaces===null)return t;for(const[i,a]of Object.entries(r.workspaces)){const l=nh(a);l&&e.set(i,l)}const o=r.activeWorkspaceCwd;return{workspaces:e,activeWorkspaceCwd:typeof o=="string"&&e.has(o)?o:null}}function nh(e){if(typeof e!="object"||e===null)return null;const t=e,n=yl(t.tree);if(!n)return null;const s=new Set(ae(n)),r={};for(const[a,l]of Qn(t.placement))s.has(l)&&(r[a]=l);const o={};for(const[a,l]of Qn(t.activeByPane))s.has(a)&&(o[a]=l);const i=t.activePaneId;return{tree:n,placement:r,activeByPane:o,activePaneId:typeof i=="string"&&s.has(i)?i:null}}function Qn(e){return typeof e!="object"||e===null?[]:Object.entries(e).filter(t=>typeof t[1]=="string")}let ge=null;function Zn(){ge==null||ge();const e=setTimeout(()=>{ge=null,ur()},eh);ge=()=>clearTimeout(e)}function sh(){ge==null||ge(),ge=null,ur()}function ur(){const e=new Map;for(const s of T.getState().tabs){const r=bt(s);r!==null&&e.set(s.id,r)}const t={};for(const[s,r]of Object.entries(P.getState().layouts)){const o={...r.pendingPlacement};for(const[a,l]of Object.entries(r.placement)){const u=e.get(a);u!==void 0&&(o[u]=l)}const i={...r.pendingActive};for(const[a,l]of Object.entries(r.activeByPane)){const u=e.get(l);u!==void 0&&(i[a]=u)}t[s]={tree:r.tree,placement:o,activeByPane:i,activePaneId:r.focusedPaneId}}const n={version:Ws,workspaces:t,activeWorkspaceCwd:T.getState().activeWorkspaceCwd??void 0};rn.set(dr,JSON.stringify(n))}function rh(){let e=es(T.getState().tabs);const t=()=>{const o=es(T.getState().tabs);o!==e&&(e=o,Zn())},n=P.subscribe(Zn),s=T.subscribe(t),r=N.subscribe(t);return()=>{n(),s(),r()}}function es(e){return e.map(t=>`${t.id}\0${bt(t)??""}`).join("")}const oh=/^diff:(staged|worktree):(.+)$/;function ih(e){for(const[t,n]of e)for(const s of Object.keys(n.placement)){const r=ah(s,t);r!==null&&T.getState().open(r)}}function ah(e,t){const n=ts(e,"file:");if(n!==null)return{id:K.file(n),kind:"file",...Bt(n),workspaceCwd:t,data:{path:n}};const s=ts(e,"molecule:");if(s!==null)return{id:K.molecule(s),kind:"molecule",...Bt(s),workspaceCwd:t,data:{path:s}};const r=oh.exec(e);if(r!==null){const o=r[2],i=r[1]==="staged";return{id:K.diff(o,i),kind:"diff",...Bt(o),workspaceCwd:t,data:{path:o,staged:i}}}return null}function ts(e,t){if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""?null:n}function Bt(e){return{label:e.split("/").pop()||e,closable:!0}}function ch(e){if(e===null)return()=>{};if(ss())return ns(e),()=>{};const t=P.subscribe(()=>{ss()&&(t(),ns(e))});return t}function ns(e){if(P.getState().layouts[e]===void 0||!T.getState().tabs.some(n=>n.workspaceCwd===e))return!1;const t=T.getState().activeWorkspaceCwd!==e;return t&&T.getState().switchWorkspace(e),lh(e),t}function lh(e){const t=T.getState().tabs.filter(s=>s.workspaceCwd===e&&s.kind==="chat");if(t.length===0)return;const n=N.getState().activeSessionId;t.some(s=>s.data.sessionId===n)||N.getState().activate(t[0].data.sessionId)}function ss(){const{sessions:e,terminals:t}=P.getState().hydrationSources;return e&&t}const dh={workspaces:new Map,activeWorkspaceCwd:null};function uh(){const e=$(s=>s.status),t=b.useRef(dh),n=b.useRef(!1);b.useEffect(()=>{const s=th();t.current=s,P.getState().installPersistedLayouts(s.workspaces,s.activeWorkspaceCwd);const r=rh(),o=()=>sh();return window.addEventListener("pagehide",o),()=>{window.removeEventListener("pagehide",o),r()}},[]),b.useEffect(()=>{if(e!=="open"||n.current)return;n.current=!0;const s=t.current;ih(s.workspaces),ch(s.activeWorkspaceCwd)},[e])}function fh(e){return typeof e=="object"&&e!==null&&"kind"in e}function ph(e){const t=[];for(const n of e)if(fh(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 hh(e){const t=[];let n=null;for(;;){const s=await e(n);if(s.items.length===0||(t.push(...ph(s.items)),!s.hasNewer))return t;const r=s.endCursor;if(typeof r!="string"||r===n)return t;n=r}}function mh(e){return typeof e.model=="string"}function gh(){const e=$(s=>s.client),t=$(s=>s.status),n=b.useRef(!1);b.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,yh(e))},[t,e]),b.useEffect(()=>{if(!(t!=="open"||!e))return e.onAgentUpdate(s=>{if(mh(s)){const r=typeof s.modelProvider=="string"?s.modelProvider:void 0;N.getState().setModelByAgentId(s.agentId,s.model,r)}})},[t,e])}async function yh(e){try{await _h(e)}finally{P.getState().markHydrationSource("sessions")}}async function _h(e){var w;let t=[];try{t=(await e.connection.request("list_agents_request",{all:!1})).agents??[]}catch{t=[]}t.sort((y,v)=>(v.lastActivity??0)-(y.lastActivity??0));const n=N.getState();for(const y of t){if(n.findByAgentId(y.agentId))continue;let v=Ut;try{v=(await hh(B=>e.agent(y.agentId).timeline.fetch({direction:"after",cursor:B??void 0,limit:200}))).reduce(Ds,Ut)}catch{}const I=v.rows.length===0;n.hydrate({id:`s-${y.agentId.slice(0,12)}`,agentId:y.agentId,title:y.title||(I?"New chat":(w=y.cwd)==null?void 0:w.split("/").pop())||"Restored",status:y.status??"idle",cwd:y.cwd||"~",timeline:v,userMessageCount:v.rows.filter(j=>j.kind==="user").length,model:y.model,modelProvider:y.modelProvider})}const{order:s,sessions:r}=N.getState(),o=s.length>0?r[s[0]??""]:void 0;if(!o)return;const i=await Tt(e).catch(()=>null),a=Ne(o.cwd||"~",i),l=P.getState().pendingActiveWorkspace??a,u=un(s,r,i);E.getState().setCollapsedWorkspaces(fd(u,l));const f=s.find(y=>{var v;return Ne(((v=r[y])==null?void 0:v.cwd)||"~",i)===l});N.getState().activate(f??o.id),E.getState().setCwd(l);const m=wh(),h=new Set;for(const y of s){const v=r[y];!(v!=null&&v.agentId)||!m.has(`agent:${v.agentId}`)||(vt(v,i),h.add(y))}const p=P.getState().layouts[a]!==void 0;!h.has(o.id)&&!p&&vt(o,i)}function wh(){const e=new Set;for(const t of Object.values(P.getState().layouts))for(const n of Object.keys(t.pendingPlacement))n.startsWith("agent:")&&e.add(n);return e}async function bh(e){try{let t=[];try{t=(await e.connection.request("list_terminals_request",{})).terminals??[]}catch{t=[]}if(t.length===0)return;const n=P.getState().layouts,s=vh(),r=await Tt(e).catch(()=>null),o=T.getState().open;for(const i of t){if(i.closed)continue;const a=Ne(i.cwd||"~",r);n[a]!==void 0&&!s.has(`terminal:${i.slot}`)||o({id:K.terminal(i.slot),kind:"terminal",label:i.name,closable:!0,data:{slot:i.slot,cwd:a},workspaceCwd:a})}}finally{P.getState().markHydrationSource("terminals")}}function vh(){const e=new Set;for(const t of Object.values(P.getState().layouts))for(const n of Object.keys(t.pendingPlacement))n.startsWith("terminal:")&&e.add(n);return e}function xh(){const e=$(s=>s.client),t=$(s=>s.status),n=b.useRef(!1);b.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,bh(e))},[t,e])}function Sh(){b.useEffect(()=>{function e(t){const n=E.getState();if(t.key==="Escape"){n.closeCwdPicker(),n.closeSessionMenu();return}const s=t.ctrlKey||t.metaKey;if(s&&t.key.toLowerCase()==="t"){t.preventDefault(),Vs(T.getState().activeWorkspaceCwd||"~");return}if(s&&t.key.toLowerCase()==="w"){const{activeTabId:r,tabs:o}=T.getState();if(!r)return;const i=o.find(a=>a.id===r);(i==null?void 0:i.closable)!==!1&&(t.preventDefault(),Kt(r))}}return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}function kh(){return Zp(),uh(),gh(),xh(),Sh(),null}function Ih(){return c.jsxs(ri,{children:[c.jsx(kh,{}),c.jsx(Qp,{})]})}function jh(e){return e.managerActive?e.status==="closed"?"reconnect-now":e.status==="open"?e.probeInFlight?"none":"probe":"none":"none"}const Th=5e3;function Ch(){let e=!1;function t(){const{status:s,reconnection:r,daemon:o}=$.getState(),i=jh({status:s,managerActive:r!==null,probeInFlight:e});if(i==="reconnect-now"){r==null||r.reconnectNow();return}if(i==="probe"){if(!o)return;e=!0,o.ping(Th).catch(()=>{$.getState().daemon===o&&o.close(4e3,"stale-connection-probe")}).finally(()=>{e=!1})}}function n(){document.visibilityState==="visible"&&t()}return document.addEventListener("visibilitychange",n),window.addEventListener("online",t),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("online",t)}}const fr=document.getElementById("root");if(!fr)throw new Error("Missing #root element");Sr.createRoot(fr).render(c.jsx(b.StrictMode,{children:c.jsx(Ih,{})}));Ch();export{se as B,Pf as C,Np as D,Ce as E,Ct as M,Ks as P,kd as S,Bh as T,Hh as V,$ as a,rt as b,Vh as c,Uh as d,dl as e,Oh as f,Wh as g,_t as h,T as i,vl as j,P as k,or as l,me as m,Ne as n,nr as o,cr as p,Rf as q,Ee as r,Kh as s,Gc as t,N as u,zh as v,Fh as w,Hn as x,Lh as y,pn as z};
|
|
18
|
+
//# sourceMappingURL=index-CO_ZzVSZ.js.map
|