@av-pi-studio/web-client 0.0.69 → 0.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/web/assets/{BinaryFallbackViewer-CY-sOJ-s.js → BinaryFallbackViewer-BWzvrIhq.js} +2 -2
  2. package/dist/web/assets/{BinaryFallbackViewer-CY-sOJ-s.js.map → BinaryFallbackViewer-BWzvrIhq.js.map} +1 -1
  3. package/dist/web/assets/{ChatPanel-CHvnaWVh.js → ChatPanel-CEH_GK7N.js} +2 -2
  4. package/dist/web/assets/{ChatPanel-CHvnaWVh.js.map → ChatPanel-CEH_GK7N.js.map} +1 -1
  5. package/dist/web/assets/{CodeView-BG2-voMV.js → CodeView-vzOAirYe.js} +2 -2
  6. package/dist/web/assets/{CodeView-BG2-voMV.js.map → CodeView-vzOAirYe.js.map} +1 -1
  7. package/dist/web/assets/{FilePanel-D0C36TRP.js → FilePanel-WQVK2120.js} +2 -2
  8. package/dist/web/assets/{FilePanel-D0C36TRP.js.map → FilePanel-WQVK2120.js.map} +1 -1
  9. package/dist/web/assets/{ImageViewer-YJE3nuMb.js → ImageViewer-Bc0i-JGb.js} +2 -2
  10. package/dist/web/assets/{ImageViewer-YJE3nuMb.js.map → ImageViewer-Bc0i-JGb.js.map} +1 -1
  11. package/dist/web/assets/{MarkdownFileViewer-Dio7ZIAS.js → MarkdownFileViewer-I0b0agu_.js} +2 -2
  12. package/dist/web/assets/{MarkdownFileViewer-Dio7ZIAS.js.map → MarkdownFileViewer-I0b0agu_.js.map} +1 -1
  13. package/dist/web/assets/{MoleculeViewerPanel-Cw5RrDrk.js → MoleculeViewerPanel-DYKfUyuF.js} +2 -2
  14. package/dist/web/assets/{MoleculeViewerPanel-Cw5RrDrk.js.map → MoleculeViewerPanel-DYKfUyuF.js.map} +1 -1
  15. package/dist/web/assets/{TerminalPanel-BHj10l7-.js → TerminalPanel-Do6WsYb9.js} +2 -2
  16. package/dist/web/assets/TerminalPanel-Do6WsYb9.js.map +1 -0
  17. package/dist/web/assets/{TextViewer-DdViYQah.js → TextViewer-C7U5fAYp.js} +2 -2
  18. package/dist/web/assets/{TextViewer-DdViYQah.js.map → TextViewer-C7U5fAYp.js.map} +1 -1
  19. package/dist/web/assets/{VideoViewer-rhO-urrJ.js → VideoViewer-DeIrV1Ql.js} +2 -2
  20. package/dist/web/assets/{VideoViewer-rhO-urrJ.js.map → VideoViewer-DeIrV1Ql.js.map} +1 -1
  21. package/dist/web/assets/{index-DM5KSYdn.js → index-DonKPQN3.js} +3 -3
  22. package/dist/web/assets/{index-DM5KSYdn.js.map → index-DonKPQN3.js.map} +1 -1
  23. package/dist/web/assets/{markdown-BLewcN0h.js → markdown-DRKdD_IM.js} +2 -2
  24. package/dist/web/assets/{markdown-BLewcN0h.js.map → markdown-DRKdD_IM.js.map} +1 -1
  25. package/dist/web/assets/{use-file-download-BOCZENOG.js → use-file-download-C2Lrmbfe.js} +2 -2
  26. package/dist/web/assets/{use-file-download-BOCZENOG.js.map → use-file-download-C2Lrmbfe.js.map} +1 -1
  27. package/dist/web/assets/{use-file-watch-CWtZGJOx.js → use-file-watch-skGpUUS7.js} +2 -2
  28. package/dist/web/assets/{use-file-watch-CWtZGJOx.js.map → use-file-watch-skGpUUS7.js.map} +1 -1
  29. package/dist/web/index.html +1 -1
  30. package/package.json +3 -3
  31. package/dist/web/assets/TerminalPanel-BHj10l7-.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import{r as d,j as s}from"./vendor-react-CWo7Do4s.js";import{c as w}from"./vendor-highlight-Efc6A-g6.js";import{n as S,c as E,m as C,d as M,a as k,o as H,p as T,q as y,b as p,S as F,v as x,w as I}from"./index-DM5KSYdn.js";import{M as D,r as z}from"./vendor-markdown-YvkQLm_s.js";const b="github-dark";let f=null;const h=new Set(["plaintext"]);function L(){return f||(f=w({themes:[b],langs:["plaintext"]})),f}async function N(n,e){if(h.has(e))return e;try{return await n.loadLanguage(e),h.add(e),e}catch{return"plaintext"}}async function R(n,e){const t=await L(),r=await N(t,e);return t.codeToHtml(n,{lang:r,theme:b})}const U="_prose_1cnx5_1",P="_inlineCode_1cnx5_40",A="_inlineImage_1cnx5_66",W="_inlineImageSkeleton_1cnx5_75",Z="_inlineImageFallback_1cnx5_86",u={prose:U,inlineCode:P,inlineImage:A,inlineImageSkeleton:W,inlineImageFallback:Z},$=/^([a-zA-Z][a-zA-Z0-9+.-]*):/;function q(n){try{return decodeURIComponent(n)}catch{return n}}function j(n,e,t){const r=n.trim();if(!r)return null;const a=r.split(/[?#]/,1)[0];if(!a||$.exec(a))return null;let l;if(a.startsWith("/")?l=a:a==="~"||a.startsWith("~/")?l=t?S(a,t):null:l=E(a,e??""),!l)return null;const c=C(l);return q(c)}const O={"http:":!0,"https:":!0,"data:":!0,"blob:":!0},V=/^([a-zA-Z][a-zA-Z0-9+.-]*):/;function G(n,e,t){const r=n.trim();if(!r)return{kind:"unresolvable"};const a=r.split(/[?#]/,1)[0];if(!a)return{kind:"unresolvable"};const i=V.exec(a);if(i)return`${i[1].toLowerCase()}:`in O?{kind:"remote"}:{kind:"unresolvable"};const l=j(n,e,t);return l?M(l)!=="image"?{kind:"unresolvable"}:{kind:"local",path:l}:{kind:"unresolvable"}}function K(n,e,t,r){return n.kind==="remote"?{kind:"remote",src:t||"",alt:r}:n.kind==="unresolvable"?{kind:"unresolvable",fallbackText:r||t||"(image)"}:e.status==="loading"||e.status==="idle"?{kind:"loading"}:e.status==="ready"?{kind:"ready",objectUrl:e.objectUrl,alt:r,path:n.path}:{kind:"error",fallbackText:r||n.path||"(image)"}}function v(n,e,t){return{workspaceCwd:t??(n||"~"),targetPaneId:e??void 0}}function J(n,e,t){if(!n||!e){t({status:"idle"});return}let r=!1;return t({status:"loading"}),H(n,e).then(a=>{r||t({status:"ready",objectUrl:a.objectUrl})}).catch(a=>{r||t({status:"error",message:a instanceof Error?a.message:String(a)})}),()=>{r=!0,T(n)}}function Q(n){const e=k(i=>i.client),t=k(i=>i.daemon),[r,a]=d.useState({status:"idle"});return d.useEffect(()=>J(n,e&&t?l=>y(t).download(l):null,a),[e,t,n]),r}const X=d.memo(function({src:e,alt:t,assetBase:r,owningPaneId:a,workspaceCwd:i}){const l=p(),c=d.useMemo(()=>G(e||"",r,l),[e,r,l]),m=Q(c.kind==="local"?c.path:null),o=K(c,m,e,t);if(o.kind==="remote")return s.jsx("img",{src:o.src,alt:o.alt,className:u.inlineImage});if(o.kind==="unresolvable"||o.kind==="error")return s.jsx("code",{className:u.inlineImageFallback,children:o.fallbackText});if(o.kind==="loading")return s.jsx("div",{className:u.inlineImageSkeleton,children:s.jsx(F,{size:"sm"})});const g=v(r,a??null,i??null),_=()=>{I(o.path,g.workspaceCwd,g.targetPaneId)};return s.jsx("img",{src:o.objectUrl,alt:o.alt,className:u.inlineImage,title:o.path,draggable:!0,onDragStart:x(o.path),onClick:_,style:{cursor:"pointer"}})});function Y(n,e,t){const r=n.trim();if(!r)return{kind:"external"};if(r.startsWith("#"))return{kind:"external"};const a=j(n,e,t);return a?{kind:"local",path:a}:{kind:"external"}}function B({href:n,children:e,assetBase:t,owningPaneId:r,workspaceCwd:a}){const i=p(),l=Y(n??"",t,i);if(l.kind==="external")return s.jsx("a",{href:n,children:e});const c=l.path,m=v(t,r,a);return s.jsx("a",{href:n,draggable:!0,onDragStart:x(c),onClick:o=>{o.preventDefault(),I(c,m.workspaceCwd,m.targetPaneId)},children:e})}function ee({language:n,code:e}){const[t,r]=d.useState(null);return d.useEffect(()=>{let a=!1;return R(e,n).then(i=>{a||r(i)}),()=>{a=!0}},[e,n]),t?s.jsx("div",{className:u.prose,dangerouslySetInnerHTML:{__html:t}}):s.jsx("pre",{children:s.jsx("code",{children:e})})}function ne({className:n,children:e,...t}){const r=/language-(\w+)/.exec(n??""),a=!!r,i=String(e).replace(/\n$/,"");return a&&r?s.jsx(ee,{language:r[1]??"plaintext",code:i}):s.jsx("code",{className:u.inlineCode,...t,children:e})}const le=d.memo(function({text:e,assetBase:t=null,owningPaneId:r=null,workspaceCwd:a=null}){return s.jsx("div",{className:u.prose,children:s.jsx(D,{remarkPlugins:[z],components:{code:ne,img:i=>s.jsx(X,{...i,assetBase:t,owningPaneId:r,workspaceCwd:a}),a:i=>s.jsx(B,{...i,assetBase:t,owningPaneId:r,workspaceCwd:a})},children:e})})});export{le as M};
2
- //# sourceMappingURL=markdown-BLewcN0h.js.map
1
+ import{r as d,j as s}from"./vendor-react-CWo7Do4s.js";import{c as w}from"./vendor-highlight-Efc6A-g6.js";import{n as S,c as E,m as C,d as M,a as k,o as H,p as T,q as y,b as p,S as F,v as x,w as I}from"./index-DonKPQN3.js";import{M as D,r as z}from"./vendor-markdown-YvkQLm_s.js";const b="github-dark";let f=null;const h=new Set(["plaintext"]);function L(){return f||(f=w({themes:[b],langs:["plaintext"]})),f}async function N(n,e){if(h.has(e))return e;try{return await n.loadLanguage(e),h.add(e),e}catch{return"plaintext"}}async function R(n,e){const t=await L(),r=await N(t,e);return t.codeToHtml(n,{lang:r,theme:b})}const U="_prose_1cnx5_1",P="_inlineCode_1cnx5_40",A="_inlineImage_1cnx5_66",W="_inlineImageSkeleton_1cnx5_75",Z="_inlineImageFallback_1cnx5_86",u={prose:U,inlineCode:P,inlineImage:A,inlineImageSkeleton:W,inlineImageFallback:Z},$=/^([a-zA-Z][a-zA-Z0-9+.-]*):/;function q(n){try{return decodeURIComponent(n)}catch{return n}}function j(n,e,t){const r=n.trim();if(!r)return null;const a=r.split(/[?#]/,1)[0];if(!a||$.exec(a))return null;let l;if(a.startsWith("/")?l=a:a==="~"||a.startsWith("~/")?l=t?S(a,t):null:l=E(a,e??""),!l)return null;const c=C(l);return q(c)}const O={"http:":!0,"https:":!0,"data:":!0,"blob:":!0},V=/^([a-zA-Z][a-zA-Z0-9+.-]*):/;function G(n,e,t){const r=n.trim();if(!r)return{kind:"unresolvable"};const a=r.split(/[?#]/,1)[0];if(!a)return{kind:"unresolvable"};const i=V.exec(a);if(i)return`${i[1].toLowerCase()}:`in O?{kind:"remote"}:{kind:"unresolvable"};const l=j(n,e,t);return l?M(l)!=="image"?{kind:"unresolvable"}:{kind:"local",path:l}:{kind:"unresolvable"}}function K(n,e,t,r){return n.kind==="remote"?{kind:"remote",src:t||"",alt:r}:n.kind==="unresolvable"?{kind:"unresolvable",fallbackText:r||t||"(image)"}:e.status==="loading"||e.status==="idle"?{kind:"loading"}:e.status==="ready"?{kind:"ready",objectUrl:e.objectUrl,alt:r,path:n.path}:{kind:"error",fallbackText:r||n.path||"(image)"}}function v(n,e,t){return{workspaceCwd:t??(n||"~"),targetPaneId:e??void 0}}function J(n,e,t){if(!n||!e){t({status:"idle"});return}let r=!1;return t({status:"loading"}),H(n,e).then(a=>{r||t({status:"ready",objectUrl:a.objectUrl})}).catch(a=>{r||t({status:"error",message:a instanceof Error?a.message:String(a)})}),()=>{r=!0,T(n)}}function Q(n){const e=k(i=>i.client),t=k(i=>i.daemon),[r,a]=d.useState({status:"idle"});return d.useEffect(()=>J(n,e&&t?l=>y(t).download(l):null,a),[e,t,n]),r}const X=d.memo(function({src:e,alt:t,assetBase:r,owningPaneId:a,workspaceCwd:i}){const l=p(),c=d.useMemo(()=>G(e||"",r,l),[e,r,l]),m=Q(c.kind==="local"?c.path:null),o=K(c,m,e,t);if(o.kind==="remote")return s.jsx("img",{src:o.src,alt:o.alt,className:u.inlineImage});if(o.kind==="unresolvable"||o.kind==="error")return s.jsx("code",{className:u.inlineImageFallback,children:o.fallbackText});if(o.kind==="loading")return s.jsx("div",{className:u.inlineImageSkeleton,children:s.jsx(F,{size:"sm"})});const g=v(r,a??null,i??null),_=()=>{I(o.path,g.workspaceCwd,g.targetPaneId)};return s.jsx("img",{src:o.objectUrl,alt:o.alt,className:u.inlineImage,title:o.path,draggable:!0,onDragStart:x(o.path),onClick:_,style:{cursor:"pointer"}})});function Y(n,e,t){const r=n.trim();if(!r)return{kind:"external"};if(r.startsWith("#"))return{kind:"external"};const a=j(n,e,t);return a?{kind:"local",path:a}:{kind:"external"}}function B({href:n,children:e,assetBase:t,owningPaneId:r,workspaceCwd:a}){const i=p(),l=Y(n??"",t,i);if(l.kind==="external")return s.jsx("a",{href:n,children:e});const c=l.path,m=v(t,r,a);return s.jsx("a",{href:n,draggable:!0,onDragStart:x(c),onClick:o=>{o.preventDefault(),I(c,m.workspaceCwd,m.targetPaneId)},children:e})}function ee({language:n,code:e}){const[t,r]=d.useState(null);return d.useEffect(()=>{let a=!1;return R(e,n).then(i=>{a||r(i)}),()=>{a=!0}},[e,n]),t?s.jsx("div",{className:u.prose,dangerouslySetInnerHTML:{__html:t}}):s.jsx("pre",{children:s.jsx("code",{children:e})})}function ne({className:n,children:e,...t}){const r=/language-(\w+)/.exec(n??""),a=!!r,i=String(e).replace(/\n$/,"");return a&&r?s.jsx(ee,{language:r[1]??"plaintext",code:i}):s.jsx("code",{className:u.inlineCode,...t,children:e})}const le=d.memo(function({text:e,assetBase:t=null,owningPaneId:r=null,workspaceCwd:a=null}){return s.jsx("div",{className:u.prose,children:s.jsx(D,{remarkPlugins:[z],components:{code:ne,img:i=>s.jsx(X,{...i,assetBase:t,owningPaneId:r,workspaceCwd:a}),a:i=>s.jsx(B,{...i,assetBase:t,owningPaneId:r,workspaceCwd:a})},children:e})})});export{le as M};
2
+ //# sourceMappingURL=markdown-DRKdD_IM.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"markdown-BLewcN0h.js","sources":["../../../src/timeline/highlight.ts","../../../src/timeline/href-resolution.ts","../../../src/timeline/image-src.ts","../../../src/timeline/inline-image-view.ts","../../../src/timeline/file-open-target.ts","../../../src/hooks/use-inline-image.ts","../../../src/timeline/InlineImage.tsx","../../../src/timeline/file-link-src.ts","../../../src/timeline/FileLink.tsx","../../../src/timeline/markdown.tsx"],"sourcesContent":["/**\n * Shiki wrapper + lang-from-path map. Replaces the POC's CDN `highlight.js`\n * (POC_TO_APP_PLAN_UI.md §2, §4.8). Grammars/themes are loaded lazily and cached — the\n * highlighter is not paid for until a code block/file view actually renders.\n */\n\nimport { createHighlighter, type Highlighter } from \"shiki\";\n\n/** POC `getLangFromPath` extension → language map, ported verbatim. */\nconst EXT_TO_LANG: Record<string, string> = {\n js: \"javascript\",\n ts: \"typescript\",\n jsx: \"javascript\",\n tsx: \"typescript\",\n py: \"python\",\n rb: \"ruby\",\n rs: \"rust\",\n go: \"go\",\n java: \"java\",\n c: \"c\",\n cpp: \"cpp\",\n h: \"c\",\n hpp: \"cpp\",\n cs: \"csharp\",\n html: \"html\",\n css: \"css\",\n scss: \"scss\",\n json: \"json\",\n yaml: \"yaml\",\n yml: \"yaml\",\n toml: \"toml\",\n xml: \"xml\",\n md: \"markdown\",\n sh: \"bash\",\n bash: \"bash\",\n sql: \"sql\",\n swift: \"swift\",\n kt: \"kotlin\",\n dart: \"dart\",\n vue: \"xml\",\n svelte: \"xml\",\n};\n\nexport function langFromPath(path: string): string {\n const ext = path.split(\".\").pop()?.toLowerCase() ?? \"\";\n return EXT_TO_LANG[ext] ?? \"plaintext\";\n}\n\nconst THEME = \"github-dark\";\n\nlet highlighterPromise: Promise<Highlighter> | null = null;\nconst loadedLangs = new Set<string>([\"plaintext\"]);\n\nfunction getHighlighter(): Promise<Highlighter> {\n if (!highlighterPromise) {\n highlighterPromise = createHighlighter({ themes: [THEME], langs: [\"plaintext\"] });\n }\n return highlighterPromise;\n}\n\nasync function ensureLang(highlighter: Highlighter, lang: string): Promise<string> {\n if (loadedLangs.has(lang)) return lang;\n try {\n await highlighter.loadLanguage(lang as never);\n loadedLangs.add(lang);\n return lang;\n } catch {\n return \"plaintext\"; // unknown grammar to Shiki — fall back rather than throw\n }\n}\n\n/** Highlight `code` for `lang` (or a path via `langFromPath`) to sanitized HTML. */\nexport async function highlightToHtml(code: string, lang: string): Promise<string> {\n const highlighter = await getHighlighter();\n const resolved = await ensureLang(highlighter, lang);\n return highlighter.codeToHtml(code, { lang: resolved, theme: THEME });\n}\n","/**\n * Shared href/src candidate resolution — used by both classifyImageSrc and classifyFileLinkSrc.\n *\n * Handles the common steps: strip fragments/query, detect schemes, expand ~/relative paths,\n * normalize, and percent-decode. Returns a resolved local candidate (absolute, normalized,\n * percent-decoded) or null if external/unresolvable.\n */\n\nimport { normalizeCwd } from \"@pi-studio-ui/features/sessions/workspace-grouping.js\";\nimport { collapseDotSegments, resolveWorkspacePath } from \"@pi-studio-ui/lib/paths.js\";\n\n/** Matches a leading `scheme:` (e.g. `http:`, `file:`, `mailto:`) — not a Windows drive letter\n * (`C:\\...`) or a bare `:` with no scheme name. */\nconst SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\n\n/**\n * Try to percent-decode a string using decodeURIComponent. On malformed sequences (e.g. `%E0%`),\n * return the original string unchanged rather than throwing.\n */\nfunction percentDecode(str: string): string {\n try {\n return decodeURIComponent(str);\n } catch {\n // Malformed percent sequence; return unchanged\n return str;\n }\n}\n\n/**\n * Shared resolution step for markdown hrefs/srcs. Strips fragments/query, detects schemes,\n * expands tilde and relatives, normalizes and percent-decodes the result.\n *\n * Returns a resolved local candidate (absolute path, normalized, percent-decoded) or null\n * if the input is external (has a scheme) or unresolvable (no base for a relative path, etc).\n *\n * @param href The raw markdown href/src\n * @param base The asset base (absolute, tilde-normalized) or null\n * @param homeDir The home directory or null\n * @returns The resolved candidate or null\n */\nexport function resolveHrefCandidate(\n href: string,\n base: string | null,\n homeDir: string | null,\n): string | null {\n const trimmed = href.trim();\n if (!trimmed) return null;\n\n // Strip `#fragment` and `?query` before classifying\n const stripped = trimmed.split(/[?#]/, 1)[0]!;\n if (!stripped) return null;\n\n // Detect explicit schemes (http:, file:, etc). If found, it's external — return null.\n const schemeMatch = SCHEME_RE.exec(stripped);\n if (schemeMatch) {\n return null; // Has a scheme; external\n }\n\n // Resolve the candidate: absolute, tilde-prefixed, or relative\n let candidate: string | null;\n if (stripped.startsWith(\"/\")) {\n candidate = stripped;\n } else if (stripped === \"~\" || stripped.startsWith(\"~/\")) {\n candidate = homeDir ? normalizeCwd(stripped, homeDir) : null;\n } else {\n // Relative path\n candidate = resolveWorkspacePath(stripped, base ?? \"\");\n }\n\n if (!candidate) return null;\n\n // Normalize (collapse ./ and ../ segments) and percent-decode\n const normalized = collapseDotSegments(candidate);\n return percentDecode(normalized);\n}\n","/**\n * Markdown image source classification (features/inline-image-rendering.md § Public Contract →\n * Markdown image source classification, § Asset base). The single gate every `![](src)` in a\n * rendered chat message passes through before any network request is even considered — deciding\n * remote (render directly), local (fetch via the daemon's file-transfer path, task-003), or\n * unresolvable (render as plain fallback text, never attempt a request).\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\n\nimport { detectViewerKind } from \"@pi-studio-ui/features/files/viewer-registry.js\";\nimport { resolveHrefCandidate } from \"./href-resolution.js\";\n\nexport type ImageSrcClassification =\n | { kind: \"remote\" }\n | { kind: \"local\"; path: string }\n | { kind: \"unresolvable\" };\n\nconst REMOTE_SCHEMES: Record<string, true> = {\n \"http:\": true,\n \"https:\": true,\n \"data:\": true,\n \"blob:\": true,\n};\n\n/** Matches a leading `scheme:` (e.g. `http:`, `file:`, `mailto:`) — not a Windows drive letter\n * (`C:\\...`) or a bare `:` with no scheme name. */\nconst SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\n\n/**\n * Classifies a markdown image `src`. `base` is the asset base (absolute, tilde-normalized) or\n * `null` when unknown; `homeDir` may be `null` when the daemon's home directory hasn't been\n * learned yet. Order matters — this mirrors the scope's classification table exactly:\n *\n * 1. empty/whitespace → unresolvable\n * 2. `http:`/`https:`/`data:`/`blob:` → remote\n * 3. any other `scheme:` prefix (including `file:`) → unresolvable\n * 4. `/…` → candidate local path as-is\n * 5. `~`/`~/…` → expand against `homeDir` (unknown home dir → unresolvable)\n * 6. `./…`, `../…`, bare relative → resolve against `base` (no base → unresolvable)\n * 7. final gate: the candidate must be an image per `detectViewerKind`, else unresolvable\n */\nexport function classifyImageSrc(\n src: string,\n base: string | null,\n homeDir: string | null,\n): ImageSrcClassification {\n const trimmed = src.trim();\n if (!trimmed) return { kind: \"unresolvable\" };\n\n // Markdown may carry a title/version via `#fragment`/`?query`; strip both before classifying so\n // a trailing `?` never defeats the extension gate below.\n const stripped = trimmed.split(/[?#]/, 1)[0]!;\n if (!stripped) return { kind: \"unresolvable\" };\n\n const schemeMatch = SCHEME_RE.exec(stripped);\n if (schemeMatch) {\n const scheme = `${schemeMatch[1]!.toLowerCase()}:`;\n return scheme in REMOTE_SCHEMES ? { kind: \"remote\" } : { kind: \"unresolvable\" };\n }\n\n // Use the shared resolution step: resolves path, applies normalization + percent-decoding\n const candidate = resolveHrefCandidate(src, base, homeDir);\n if (!candidate) return { kind: \"unresolvable\" };\n\n // Image-specific gate: must be an image extension\n if (detectViewerKind(candidate) !== \"image\") return { kind: \"unresolvable\" };\n return { kind: \"local\", path: candidate };\n}\n","/**\n * Pure, testable logic for rendering inline images — extracted from the component\n * so tests can verify branch logic without JSX rendering (mirror of molecule-reload.ts,\n * text-viewer-state.ts; see AGENTS.md testing conventions).\n *\n * Returns a discriminated union describing what to render: the component switches\n * on it to decide remote passthrough, skeleton, ready image, or text fallback.\n */\n\nimport type { ImageSrcClassification } from \"./image-src.js\";\nimport type { InlineImageState } from \"@pi-studio-ui/hooks/use-inline-image.js\";\n\nexport type InlineImageView =\n | { kind: \"remote\"; src: string; alt?: string }\n | { kind: \"unresolvable\"; fallbackText: string }\n | { kind: \"loading\" }\n | { kind: \"ready\"; objectUrl: string; alt?: string; path: string }\n | { kind: \"error\"; fallbackText: string };\n\n/**\n * Decides what to render for an inline image given its classification and loading state.\n * Pure: no hooks, no store access — all state passed in as arguments.\n */\nexport function selectInlineImageView(\n classification: ImageSrcClassification,\n imageState: InlineImageState,\n src: string | undefined,\n alt: string | undefined,\n): InlineImageView {\n if (classification.kind === \"remote\") {\n return { kind: \"remote\", src: src || \"\", alt };\n }\n\n if (classification.kind === \"unresolvable\") {\n const fallbackText = alt || src || \"(image)\";\n return { kind: \"unresolvable\", fallbackText };\n }\n\n // classification.kind === \"local\"\n if (imageState.status === \"loading\" || imageState.status === \"idle\") {\n return { kind: \"loading\" };\n }\n\n if (imageState.status === \"ready\") {\n return { kind: \"ready\", objectUrl: imageState.objectUrl, alt, path: classification.path };\n }\n\n // imageState.status === \"error\"\n const fallbackText = alt || classification.path || \"(image)\";\n return { kind: \"error\", fallbackText };\n}\n","/**\n * Resolves the `openFileTab` workspace-cwd/target-pane arguments shared by `FileLink` and\n * `InlineImage`'s converged click-to-open dispatch (features/file-link-rendering.md §\n * Click-to-open pane targeting, features/inline-image-rendering.md § Click-to-open, amended).\n *\n * The owning chat tab's real `workspaceCwd` always wins — `assetBase || \"~\"` is only a fallback\n * for markdown surfaces rendered outside any tab, where no owning tab exists to name; the chat\n * render path always threads a real `workspaceCwd` (task-002) and never hits the fallback.\n * `owningPaneId`'s `null` (no owning pane yet known, e.g. a tab not yet placed by restore)\n * converts to `undefined`, matching `openFileTab`'s `targetPaneId: string | undefined` contract —\n * `undefined` falls back to whichever pane is currently focused.\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\nexport function resolveFileOpenTarget(\n assetBase: string | null,\n owningPaneId: string | null,\n workspaceCwd: string | null,\n): { workspaceCwd: string; targetPaneId: string | undefined } {\n return {\n workspaceCwd: workspaceCwd ?? (assetBase || \"~\"),\n targetPaneId: owningPaneId ?? undefined,\n };\n}\n","/**\n * `use-inline-image` — fetches (via the shared ref-counted `inline-image-cache`) and hands back\n * an object URL for an inline chat image (features/inline-image-rendering.md § Inline image fetch\n * + cache). Consumed by the markdown `img` node override (task-004) once a `classifyImageSrc`\n * result is `local`.\n *\n * Deliberately NOT a TanStack Query hook, and therefore no `rpcKeys` entry: the whole point of\n * `inline-image-cache.ts` is a retention policy (revoke only on LRU eviction, never on unmount)\n * that Query's cache cannot express. Do not \"fix\" this into a `useQuery` — see that module's\n * header for why.\n *\n * `loadInlineImage` is the actual effect body, extracted for direct unit testing without\n * rendering — this package has no jsdom/React-Testing-Library environment (`AGENTS.md`'s testing\n * convention; mirrors `use-file-watch.ts`'s `watchFile` extraction).\n */\n\nimport { useEffect, useState } from \"react\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { acquireInlineImage, releaseInlineImage } from \"@pi-studio-ui/lib/inline-image-cache.js\";\nimport { transferFor } from \"./file-transfer-instance.js\";\n\nexport type InlineImageState =\n | { status: \"idle\" } // no client yet, or path is null\n | { status: \"loading\" }\n | { status: \"ready\"; objectUrl: string }\n | { status: \"error\"; message: string };\n\n/**\n * Runs one effect cycle: `download === null` (no live connection, or no path) is the idle case —\n * nothing to acquire, nothing to clean up. Otherwise acquires `path`, reports the loading →\n * ready/error transition via `onStateChange`, and returns a cleanup that releases the path and\n * ignores a resolution that lands after it (the `cancelled` flag pattern used across the existing\n * hooks, e.g. `use-checkout-status.ts`).\n */\nexport function loadInlineImage(\n path: string | null,\n download: ((path: string) => Promise<{ bytes: Uint8Array; mimeType?: string }>) | null,\n onStateChange: (state: InlineImageState) => void,\n): (() => void) | void {\n if (!path || !download) {\n onStateChange({ status: \"idle\" });\n return;\n }\n\n let cancelled = false;\n onStateChange({ status: \"loading\" });\n\n acquireInlineImage(path, download)\n .then((entry) => {\n if (!cancelled) onStateChange({ status: \"ready\", objectUrl: entry.objectUrl });\n })\n .catch((error: unknown) => {\n if (!cancelled) {\n onStateChange({\n status: \"error\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n return () => {\n cancelled = true;\n releaseInlineImage(path);\n };\n}\n\nexport function useInlineImage(path: string | null): InlineImageState {\n const client = useConnectionStore((s) => s.client);\n const daemon = useConnectionStore((s) => s.daemon);\n const [state, setState] = useState<InlineImageState>({ status: \"idle\" });\n\n useEffect(() => {\n const download = client && daemon ? (p: string) => transferFor(daemon).download(p) : null;\n return loadInlineImage(path, download, setState);\n }, [client, daemon, path]);\n\n return state;\n}\n","/**\n * `![alt](src)` renderer for finalized assistant markdown (features/inline-image-rendering.md §\n * Behavior & Algorithms → Render pipeline). Handles remote passthrough, local file fetch via\n * useInlineImage (task-003), classification (task-002), and click-to-open file tab.\n *\n * Props are optional (react-markdown may omit them) and must be handled defensively.\n */\n\nimport { memo, useMemo } from \"react\";\nimport { classifyImageSrc } from \"./image-src.js\";\nimport { selectInlineImageView } from \"./inline-image-view.js\";\nimport { resolveFileOpenTarget } from \"./file-open-target.js\";\nimport { useInlineImage } from \"@pi-studio-ui/hooks/use-inline-image.js\";\nimport { useHomeDir } from \"@pi-studio-ui/hooks/use-home-dir.js\";\nimport { openFileTab } from \"@pi-studio-ui/features/files/open-file-tab.js\";\nimport { pathDragStartHandler } from \"@pi-studio-ui/features/workspace/external-drag.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport styles from \"./markdown.module.css\";\n\nexport interface InlineImageProps {\n src?: string;\n alt?: string;\n assetBase: string | null;\n owningPaneId?: string | null;\n workspaceCwd?: string | null;\n}\n\nexport const InlineImage = memo(function InlineImage({\n src,\n alt,\n assetBase,\n owningPaneId,\n workspaceCwd,\n}: InlineImageProps) {\n const homeDir = useHomeDir();\n\n // Classify the source once at render time.\n const classification = useMemo(\n () => classifyImageSrc(src || \"\", assetBase, homeDir),\n [src, assetBase, homeDir],\n );\n\n // For local images, fetch and track state.\n const imageState = useInlineImage(classification.kind === \"local\" ? classification.path : null);\n\n // Decide what to render.\n const view = selectInlineImageView(classification, imageState, src, alt);\n\n // Remote images: pass through unchanged (what react-markdown's default would do).\n if (view.kind === \"remote\") {\n return <img src={view.src} alt={view.alt} className={styles.inlineImage} />;\n }\n\n // Unresolvable or error: render text fallback in inline monospace.\n if (view.kind === \"unresolvable\" || view.kind === \"error\") {\n return <code className={styles.inlineImageFallback}>{view.fallbackText}</code>;\n }\n\n // Loading or idle: skeleton.\n if (view.kind === \"loading\") {\n return (\n <div className={styles.inlineImageSkeleton}>\n <Spinner size=\"sm\" />\n </div>\n );\n }\n\n // Ready: render the fetched image with click-to-open handler, converged onto the same\n // `openFileTab` dispatch the Files tree and `FileLink` use — puts the pane-targeting fix\n // (owning tab's real `workspaceCwd`, `owningPaneId`) in exactly one place for both features.\n const target = resolveFileOpenTarget(assetBase, owningPaneId ?? null, workspaceCwd ?? null);\n const handleClick = () => {\n openFileTab(view.path, target.workspaceCwd, target.targetPaneId);\n };\n\n return (\n <img\n src={view.objectUrl}\n alt={view.alt}\n className={styles.inlineImage}\n title={view.path}\n draggable\n onDragStart={pathDragStartHandler(view.path)}\n onClick={handleClick}\n style={{ cursor: \"pointer\" }}\n />\n );\n});\n","/**\n * Markdown file link source classification (features/file-link-rendering.md § Public Contract →\n * Markdown link source classification). Decides whether a markdown link `[label](href)` should\n * open a local file (intercepted by the client) or navigate as a regular link.\n *\n * Two-way classification simpler than the image classifier's three-way one:\n * - `local`: resolves to a local filesystem path → intercept, open as a file\n * - `external`: anything else → pass through as a regular navigating anchor\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\n\nimport { resolveHrefCandidate } from \"./href-resolution.js\";\n\nexport type FileLinkClassification = { kind: \"local\"; path: string } | { kind: \"external\" };\n\n/**\n * Classifies a markdown link `href`. `base` is the asset base (absolute, tilde-normalized) or\n * `null` when unknown; `homeDir` may be `null` when the daemon's home directory hasn't been\n * learned yet. Order matters — this mirrors the scope's classification table exactly:\n *\n * 1. empty/whitespace → external\n * 2. fragment-only (`#section`) → external (in-page anchor must not be intercepted)\n * 3. path+fragment (`README.md#usage`) → fragment stripped by resolver, remainder classifies\n * 4. `http:`/`https:` scheme → external\n * 5. any other `scheme:` prefix (incl. `file:`) → external\n * 6. `/…` → local, path used as-is\n * 7. `~`/`~/…` → local, `~` expanded (unknown home dir → external)\n * 8. `./…`, `../…`, bare relative → local, joined against `base` (no base → external)\n * 9. No extension gate (unlike images) — any resolved local path qualifies, including directories\n */\nexport function classifyFileLinkSrc(\n href: string,\n base: string | null,\n homeDir: string | null,\n): FileLinkClassification {\n const trimmed = href.trim();\n if (!trimmed) return { kind: \"external\" };\n\n // Fragment-only check: if the href contains only `#`, it's an in-page anchor\n if (trimmed.startsWith(\"#\")) return { kind: \"external\" };\n\n // Use the shared resolution step: strips fragments/query, resolves paths, normalizes + decodes\n const candidate = resolveHrefCandidate(href, base, homeDir);\n\n // If resolved successfully, it's a local file link; otherwise external\n if (candidate) {\n return { kind: \"local\", path: candidate };\n }\n return { kind: \"external\" };\n}\n","/**\n * `[label](href)` renderer for finalized assistant markdown (features/file-link-rendering.md §\n * Render pipeline, § Click-to-open pane targeting, § Drag-to-split). `classifyFileLinkSrc`'s\n * `external` result renders an ordinary, unmodified anchor — never intercepted, so in-page anchors\n * and real links keep working exactly as the browser's default. A `local` result renders an\n * actionable, draggable anchor: click prevents navigation and dispatches through the same\n * `openFileTab` primitive the Files tree and its context menu already use, targeted at the owning\n * chat tab's pane — the converged click-to-open dispatch `InlineImage` also uses\n * (features/inline-image-rendering.md § Click-to-open, amended); drag carries the identical\n * `EXTERNAL_DRAG_MIME.path` payload a Files-tree row drag carries, so dropping it onto a pane's\n * edge splits and opens it there, with zero drop-side changes needed.\n */\n\nimport type { ReactNode } from \"react\";\nimport { classifyFileLinkSrc } from \"./file-link-src.js\";\nimport { resolveFileOpenTarget } from \"./file-open-target.js\";\nimport { useHomeDir } from \"@pi-studio-ui/hooks/use-home-dir.js\";\nimport { openFileTab } from \"@pi-studio-ui/features/files/open-file-tab.js\";\nimport { pathDragStartHandler } from \"@pi-studio-ui/features/workspace/external-drag.js\";\n\nexport interface FileLinkProps {\n href?: string;\n children?: ReactNode;\n assetBase: string | null;\n owningPaneId: string | null;\n workspaceCwd: string | null;\n}\n\nexport function FileLink({ href, children, assetBase, owningPaneId, workspaceCwd }: FileLinkProps) {\n const homeDir = useHomeDir();\n const classification = classifyFileLinkSrc(href ?? \"\", assetBase, homeDir);\n\n if (classification.kind === \"external\") {\n return <a href={href}>{children}</a>;\n }\n\n const path = classification.path;\n const target = resolveFileOpenTarget(assetBase, owningPaneId, workspaceCwd);\n return (\n <a\n href={href}\n draggable\n onDragStart={pathDragStartHandler(path)}\n onClick={(event) => {\n event.preventDefault();\n openFileTab(path, target.workspaceCwd, target.targetPaneId);\n }}\n >\n {children}\n </a>\n );\n}\n","/**\n * react-markdown + remark-gfm rendering, replacing the POC's CDN `marked` + `innerHTML`\n * (POC_TO_APP_PLAN_UI.md §4.8). Sanitized by default — react-markdown never injects raw HTML.\n * Fenced code blocks highlight asynchronously via Shiki (`highlight.ts`).\n */\n\nimport { memo, useEffect, useState, type ComponentPropsWithoutRef } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport { highlightToHtml } from \"./highlight.js\";\nimport styles from \"./markdown.module.css\";\nimport { InlineImage } from \"./InlineImage.js\";\nimport { FileLink } from \"./FileLink.js\";\n\ninterface CodeBlockProps {\n language: string;\n code: string;\n}\n\nfunction CodeBlock({ language, code }: CodeBlockProps) {\n const [html, setHtml] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n void highlightToHtml(code, language).then((result) => {\n if (!cancelled) setHtml(result);\n });\n return () => {\n cancelled = true;\n };\n }, [code, language]);\n\n if (html) {\n // Shiki's output is generated HTML from a trusted local highlighter (no user HTML is ever\n // injected) — the only risk is `code`, which Shiki escapes internally before tokenizing.\n return <div className={styles.prose} dangerouslySetInnerHTML={{ __html: html }} />;\n }\n return (\n <pre>\n <code>{code}</code>\n </pre>\n );\n}\n\ntype MarkdownCodeProps = ComponentPropsWithoutRef<\"code\"> & { className?: string };\n\nfunction CodeRenderer({ className, children, ...rest }: MarkdownCodeProps) {\n const match = /language-(\\w+)/.exec(className ?? \"\");\n const isBlock = Boolean(match);\n const code = String(children).replace(/\\n$/, \"\");\n if (isBlock && match) {\n return <CodeBlock language={match[1] ?? \"plaintext\"} code={code} />;\n }\n return (\n <code className={styles.inlineCode} {...rest}>\n {children}\n </code>\n );\n}\n\nexport interface MarkdownProps {\n text: string;\n assetBase?: string | null;\n owningPaneId?: string | null;\n workspaceCwd?: string | null;\n}\n\n/** Renders assistant/tool markdown text. Memoized — text is immutable once a turn finalizes. */\nexport const Markdown = memo(function Markdown({\n text,\n assetBase = null,\n owningPaneId = null,\n workspaceCwd = null,\n}: MarkdownProps) {\n return (\n <div className={styles.prose}>\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n components={{\n code: CodeRenderer,\n img: (props) => (\n <InlineImage\n {...props}\n assetBase={assetBase}\n owningPaneId={owningPaneId}\n workspaceCwd={workspaceCwd}\n />\n ),\n a: (props) => (\n <FileLink\n {...props}\n assetBase={assetBase}\n owningPaneId={owningPaneId}\n workspaceCwd={workspaceCwd}\n />\n ),\n }}\n >\n {text}\n </ReactMarkdown>\n </div>\n );\n});\n"],"names":["THEME","highlighterPromise","loadedLangs","getHighlighter","createHighlighter","ensureLang","highlighter","lang","highlightToHtml","code","resolved","SCHEME_RE","percentDecode","str","resolveHrefCandidate","href","base","homeDir","trimmed","stripped","candidate","normalizeCwd","resolveWorkspacePath","normalized","collapseDotSegments","REMOTE_SCHEMES","classifyImageSrc","src","schemeMatch","detectViewerKind","selectInlineImageView","classification","imageState","alt","fallbackText","resolveFileOpenTarget","assetBase","owningPaneId","workspaceCwd","loadInlineImage","path","download","onStateChange","cancelled","acquireInlineImage","entry","error","releaseInlineImage","useInlineImage","client","useConnectionStore","s","daemon","state","setState","useState","useEffect","p","transferFor","InlineImage","memo","useHomeDir","useMemo","view","jsx","styles","Spinner","target","handleClick","openFileTab","pathDragStartHandler","classifyFileLinkSrc","FileLink","children","event","CodeBlock","language","html","setHtml","result","CodeRenderer","className","rest","match","isBlock","Markdown","text","ReactMarkdown","remarkGfm","props"],"mappings":"uRAgDA,MAAMA,EAAQ,cAEd,IAAIC,EAAkD,KACtD,MAAMC,EAAc,IAAI,IAAY,CAAC,WAAW,CAAC,EAEjD,SAASC,GAAuC,CAC9C,OAAKF,IACHA,EAAqBG,EAAkB,CAAE,OAAQ,CAACJ,CAAK,EAAG,MAAO,CAAC,WAAW,EAAG,GAE3EC,CAC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AA,IAACL,EAAA,CACE,GAAG8B,EACJ,UAAArD,EACA,aAAAC,EACA,aAAAC,CAAA,CAAA,EAGJ,EAAImD,GACFzB,EAAAA,IAACQ,EAAA,CACE,GAAGiB,EACJ,UAAArD,EACA,aAAAC,EACA,aAAAC,CAAA,CAAA,CACF,EAIH,SAAAgD,CAAA,CAAA,EAEL,CAEJ,CAAC"}
1
+ {"version":3,"file":"markdown-DRKdD_IM.js","sources":["../../../src/timeline/highlight.ts","../../../src/timeline/href-resolution.ts","../../../src/timeline/image-src.ts","../../../src/timeline/inline-image-view.ts","../../../src/timeline/file-open-target.ts","../../../src/hooks/use-inline-image.ts","../../../src/timeline/InlineImage.tsx","../../../src/timeline/file-link-src.ts","../../../src/timeline/FileLink.tsx","../../../src/timeline/markdown.tsx"],"sourcesContent":["/**\n * Shiki wrapper + lang-from-path map. Replaces the POC's CDN `highlight.js`\n * (POC_TO_APP_PLAN_UI.md §2, §4.8). Grammars/themes are loaded lazily and cached — the\n * highlighter is not paid for until a code block/file view actually renders.\n */\n\nimport { createHighlighter, type Highlighter } from \"shiki\";\n\n/** POC `getLangFromPath` extension → language map, ported verbatim. */\nconst EXT_TO_LANG: Record<string, string> = {\n js: \"javascript\",\n ts: \"typescript\",\n jsx: \"javascript\",\n tsx: \"typescript\",\n py: \"python\",\n rb: \"ruby\",\n rs: \"rust\",\n go: \"go\",\n java: \"java\",\n c: \"c\",\n cpp: \"cpp\",\n h: \"c\",\n hpp: \"cpp\",\n cs: \"csharp\",\n html: \"html\",\n css: \"css\",\n scss: \"scss\",\n json: \"json\",\n yaml: \"yaml\",\n yml: \"yaml\",\n toml: \"toml\",\n xml: \"xml\",\n md: \"markdown\",\n sh: \"bash\",\n bash: \"bash\",\n sql: \"sql\",\n swift: \"swift\",\n kt: \"kotlin\",\n dart: \"dart\",\n vue: \"xml\",\n svelte: \"xml\",\n};\n\nexport function langFromPath(path: string): string {\n const ext = path.split(\".\").pop()?.toLowerCase() ?? \"\";\n return EXT_TO_LANG[ext] ?? \"plaintext\";\n}\n\nconst THEME = \"github-dark\";\n\nlet highlighterPromise: Promise<Highlighter> | null = null;\nconst loadedLangs = new Set<string>([\"plaintext\"]);\n\nfunction getHighlighter(): Promise<Highlighter> {\n if (!highlighterPromise) {\n highlighterPromise = createHighlighter({ themes: [THEME], langs: [\"plaintext\"] });\n }\n return highlighterPromise;\n}\n\nasync function ensureLang(highlighter: Highlighter, lang: string): Promise<string> {\n if (loadedLangs.has(lang)) return lang;\n try {\n await highlighter.loadLanguage(lang as never);\n loadedLangs.add(lang);\n return lang;\n } catch {\n return \"plaintext\"; // unknown grammar to Shiki — fall back rather than throw\n }\n}\n\n/** Highlight `code` for `lang` (or a path via `langFromPath`) to sanitized HTML. */\nexport async function highlightToHtml(code: string, lang: string): Promise<string> {\n const highlighter = await getHighlighter();\n const resolved = await ensureLang(highlighter, lang);\n return highlighter.codeToHtml(code, { lang: resolved, theme: THEME });\n}\n","/**\n * Shared href/src candidate resolution — used by both classifyImageSrc and classifyFileLinkSrc.\n *\n * Handles the common steps: strip fragments/query, detect schemes, expand ~/relative paths,\n * normalize, and percent-decode. Returns a resolved local candidate (absolute, normalized,\n * percent-decoded) or null if external/unresolvable.\n */\n\nimport { normalizeCwd } from \"@pi-studio-ui/features/sessions/workspace-grouping.js\";\nimport { collapseDotSegments, resolveWorkspacePath } from \"@pi-studio-ui/lib/paths.js\";\n\n/** Matches a leading `scheme:` (e.g. `http:`, `file:`, `mailto:`) — not a Windows drive letter\n * (`C:\\...`) or a bare `:` with no scheme name. */\nconst SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\n\n/**\n * Try to percent-decode a string using decodeURIComponent. On malformed sequences (e.g. `%E0%`),\n * return the original string unchanged rather than throwing.\n */\nfunction percentDecode(str: string): string {\n try {\n return decodeURIComponent(str);\n } catch {\n // Malformed percent sequence; return unchanged\n return str;\n }\n}\n\n/**\n * Shared resolution step for markdown hrefs/srcs. Strips fragments/query, detects schemes,\n * expands tilde and relatives, normalizes and percent-decodes the result.\n *\n * Returns a resolved local candidate (absolute path, normalized, percent-decoded) or null\n * if the input is external (has a scheme) or unresolvable (no base for a relative path, etc).\n *\n * @param href The raw markdown href/src\n * @param base The asset base (absolute, tilde-normalized) or null\n * @param homeDir The home directory or null\n * @returns The resolved candidate or null\n */\nexport function resolveHrefCandidate(\n href: string,\n base: string | null,\n homeDir: string | null,\n): string | null {\n const trimmed = href.trim();\n if (!trimmed) return null;\n\n // Strip `#fragment` and `?query` before classifying\n const stripped = trimmed.split(/[?#]/, 1)[0]!;\n if (!stripped) return null;\n\n // Detect explicit schemes (http:, file:, etc). If found, it's external — return null.\n const schemeMatch = SCHEME_RE.exec(stripped);\n if (schemeMatch) {\n return null; // Has a scheme; external\n }\n\n // Resolve the candidate: absolute, tilde-prefixed, or relative\n let candidate: string | null;\n if (stripped.startsWith(\"/\")) {\n candidate = stripped;\n } else if (stripped === \"~\" || stripped.startsWith(\"~/\")) {\n candidate = homeDir ? normalizeCwd(stripped, homeDir) : null;\n } else {\n // Relative path\n candidate = resolveWorkspacePath(stripped, base ?? \"\");\n }\n\n if (!candidate) return null;\n\n // Normalize (collapse ./ and ../ segments) and percent-decode\n const normalized = collapseDotSegments(candidate);\n return percentDecode(normalized);\n}\n","/**\n * Markdown image source classification (features/inline-image-rendering.md § Public Contract →\n * Markdown image source classification, § Asset base). The single gate every `![](src)` in a\n * rendered chat message passes through before any network request is even considered — deciding\n * remote (render directly), local (fetch via the daemon's file-transfer path, task-003), or\n * unresolvable (render as plain fallback text, never attempt a request).\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\n\nimport { detectViewerKind } from \"@pi-studio-ui/features/files/viewer-registry.js\";\nimport { resolveHrefCandidate } from \"./href-resolution.js\";\n\nexport type ImageSrcClassification =\n | { kind: \"remote\" }\n | { kind: \"local\"; path: string }\n | { kind: \"unresolvable\" };\n\nconst REMOTE_SCHEMES: Record<string, true> = {\n \"http:\": true,\n \"https:\": true,\n \"data:\": true,\n \"blob:\": true,\n};\n\n/** Matches a leading `scheme:` (e.g. `http:`, `file:`, `mailto:`) — not a Windows drive letter\n * (`C:\\...`) or a bare `:` with no scheme name. */\nconst SCHEME_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):/;\n\n/**\n * Classifies a markdown image `src`. `base` is the asset base (absolute, tilde-normalized) or\n * `null` when unknown; `homeDir` may be `null` when the daemon's home directory hasn't been\n * learned yet. Order matters — this mirrors the scope's classification table exactly:\n *\n * 1. empty/whitespace → unresolvable\n * 2. `http:`/`https:`/`data:`/`blob:` → remote\n * 3. any other `scheme:` prefix (including `file:`) → unresolvable\n * 4. `/…` → candidate local path as-is\n * 5. `~`/`~/…` → expand against `homeDir` (unknown home dir → unresolvable)\n * 6. `./…`, `../…`, bare relative → resolve against `base` (no base → unresolvable)\n * 7. final gate: the candidate must be an image per `detectViewerKind`, else unresolvable\n */\nexport function classifyImageSrc(\n src: string,\n base: string | null,\n homeDir: string | null,\n): ImageSrcClassification {\n const trimmed = src.trim();\n if (!trimmed) return { kind: \"unresolvable\" };\n\n // Markdown may carry a title/version via `#fragment`/`?query`; strip both before classifying so\n // a trailing `?` never defeats the extension gate below.\n const stripped = trimmed.split(/[?#]/, 1)[0]!;\n if (!stripped) return { kind: \"unresolvable\" };\n\n const schemeMatch = SCHEME_RE.exec(stripped);\n if (schemeMatch) {\n const scheme = `${schemeMatch[1]!.toLowerCase()}:`;\n return scheme in REMOTE_SCHEMES ? { kind: \"remote\" } : { kind: \"unresolvable\" };\n }\n\n // Use the shared resolution step: resolves path, applies normalization + percent-decoding\n const candidate = resolveHrefCandidate(src, base, homeDir);\n if (!candidate) return { kind: \"unresolvable\" };\n\n // Image-specific gate: must be an image extension\n if (detectViewerKind(candidate) !== \"image\") return { kind: \"unresolvable\" };\n return { kind: \"local\", path: candidate };\n}\n","/**\n * Pure, testable logic for rendering inline images — extracted from the component\n * so tests can verify branch logic without JSX rendering (mirror of molecule-reload.ts,\n * text-viewer-state.ts; see AGENTS.md testing conventions).\n *\n * Returns a discriminated union describing what to render: the component switches\n * on it to decide remote passthrough, skeleton, ready image, or text fallback.\n */\n\nimport type { ImageSrcClassification } from \"./image-src.js\";\nimport type { InlineImageState } from \"@pi-studio-ui/hooks/use-inline-image.js\";\n\nexport type InlineImageView =\n | { kind: \"remote\"; src: string; alt?: string }\n | { kind: \"unresolvable\"; fallbackText: string }\n | { kind: \"loading\" }\n | { kind: \"ready\"; objectUrl: string; alt?: string; path: string }\n | { kind: \"error\"; fallbackText: string };\n\n/**\n * Decides what to render for an inline image given its classification and loading state.\n * Pure: no hooks, no store access — all state passed in as arguments.\n */\nexport function selectInlineImageView(\n classification: ImageSrcClassification,\n imageState: InlineImageState,\n src: string | undefined,\n alt: string | undefined,\n): InlineImageView {\n if (classification.kind === \"remote\") {\n return { kind: \"remote\", src: src || \"\", alt };\n }\n\n if (classification.kind === \"unresolvable\") {\n const fallbackText = alt || src || \"(image)\";\n return { kind: \"unresolvable\", fallbackText };\n }\n\n // classification.kind === \"local\"\n if (imageState.status === \"loading\" || imageState.status === \"idle\") {\n return { kind: \"loading\" };\n }\n\n if (imageState.status === \"ready\") {\n return { kind: \"ready\", objectUrl: imageState.objectUrl, alt, path: classification.path };\n }\n\n // imageState.status === \"error\"\n const fallbackText = alt || classification.path || \"(image)\";\n return { kind: \"error\", fallbackText };\n}\n","/**\n * Resolves the `openFileTab` workspace-cwd/target-pane arguments shared by `FileLink` and\n * `InlineImage`'s converged click-to-open dispatch (features/file-link-rendering.md §\n * Click-to-open pane targeting, features/inline-image-rendering.md § Click-to-open, amended).\n *\n * The owning chat tab's real `workspaceCwd` always wins — `assetBase || \"~\"` is only a fallback\n * for markdown surfaces rendered outside any tab, where no owning tab exists to name; the chat\n * render path always threads a real `workspaceCwd` (task-002) and never hits the fallback.\n * `owningPaneId`'s `null` (no owning pane yet known, e.g. a tab not yet placed by restore)\n * converts to `undefined`, matching `openFileTab`'s `targetPaneId: string | undefined` contract —\n * `undefined` falls back to whichever pane is currently focused.\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\nexport function resolveFileOpenTarget(\n assetBase: string | null,\n owningPaneId: string | null,\n workspaceCwd: string | null,\n): { workspaceCwd: string; targetPaneId: string | undefined } {\n return {\n workspaceCwd: workspaceCwd ?? (assetBase || \"~\"),\n targetPaneId: owningPaneId ?? undefined,\n };\n}\n","/**\n * `use-inline-image` — fetches (via the shared ref-counted `inline-image-cache`) and hands back\n * an object URL for an inline chat image (features/inline-image-rendering.md § Inline image fetch\n * + cache). Consumed by the markdown `img` node override (task-004) once a `classifyImageSrc`\n * result is `local`.\n *\n * Deliberately NOT a TanStack Query hook, and therefore no `rpcKeys` entry: the whole point of\n * `inline-image-cache.ts` is a retention policy (revoke only on LRU eviction, never on unmount)\n * that Query's cache cannot express. Do not \"fix\" this into a `useQuery` — see that module's\n * header for why.\n *\n * `loadInlineImage` is the actual effect body, extracted for direct unit testing without\n * rendering — this package has no jsdom/React-Testing-Library environment (`AGENTS.md`'s testing\n * convention; mirrors `use-file-watch.ts`'s `watchFile` extraction).\n */\n\nimport { useEffect, useState } from \"react\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { acquireInlineImage, releaseInlineImage } from \"@pi-studio-ui/lib/inline-image-cache.js\";\nimport { transferFor } from \"./file-transfer-instance.js\";\n\nexport type InlineImageState =\n | { status: \"idle\" } // no client yet, or path is null\n | { status: \"loading\" }\n | { status: \"ready\"; objectUrl: string }\n | { status: \"error\"; message: string };\n\n/**\n * Runs one effect cycle: `download === null` (no live connection, or no path) is the idle case —\n * nothing to acquire, nothing to clean up. Otherwise acquires `path`, reports the loading →\n * ready/error transition via `onStateChange`, and returns a cleanup that releases the path and\n * ignores a resolution that lands after it (the `cancelled` flag pattern used across the existing\n * hooks, e.g. `use-checkout-status.ts`).\n */\nexport function loadInlineImage(\n path: string | null,\n download: ((path: string) => Promise<{ bytes: Uint8Array; mimeType?: string }>) | null,\n onStateChange: (state: InlineImageState) => void,\n): (() => void) | void {\n if (!path || !download) {\n onStateChange({ status: \"idle\" });\n return;\n }\n\n let cancelled = false;\n onStateChange({ status: \"loading\" });\n\n acquireInlineImage(path, download)\n .then((entry) => {\n if (!cancelled) onStateChange({ status: \"ready\", objectUrl: entry.objectUrl });\n })\n .catch((error: unknown) => {\n if (!cancelled) {\n onStateChange({\n status: \"error\",\n message: error instanceof Error ? error.message : String(error),\n });\n }\n });\n\n return () => {\n cancelled = true;\n releaseInlineImage(path);\n };\n}\n\nexport function useInlineImage(path: string | null): InlineImageState {\n const client = useConnectionStore((s) => s.client);\n const daemon = useConnectionStore((s) => s.daemon);\n const [state, setState] = useState<InlineImageState>({ status: \"idle\" });\n\n useEffect(() => {\n const download = client && daemon ? (p: string) => transferFor(daemon).download(p) : null;\n return loadInlineImage(path, download, setState);\n }, [client, daemon, path]);\n\n return state;\n}\n","/**\n * `![alt](src)` renderer for finalized assistant markdown (features/inline-image-rendering.md §\n * Behavior & Algorithms → Render pipeline). Handles remote passthrough, local file fetch via\n * useInlineImage (task-003), classification (task-002), and click-to-open file tab.\n *\n * Props are optional (react-markdown may omit them) and must be handled defensively.\n */\n\nimport { memo, useMemo } from \"react\";\nimport { classifyImageSrc } from \"./image-src.js\";\nimport { selectInlineImageView } from \"./inline-image-view.js\";\nimport { resolveFileOpenTarget } from \"./file-open-target.js\";\nimport { useInlineImage } from \"@pi-studio-ui/hooks/use-inline-image.js\";\nimport { useHomeDir } from \"@pi-studio-ui/hooks/use-home-dir.js\";\nimport { openFileTab } from \"@pi-studio-ui/features/files/open-file-tab.js\";\nimport { pathDragStartHandler } from \"@pi-studio-ui/features/workspace/external-drag.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport styles from \"./markdown.module.css\";\n\nexport interface InlineImageProps {\n src?: string;\n alt?: string;\n assetBase: string | null;\n owningPaneId?: string | null;\n workspaceCwd?: string | null;\n}\n\nexport const InlineImage = memo(function InlineImage({\n src,\n alt,\n assetBase,\n owningPaneId,\n workspaceCwd,\n}: InlineImageProps) {\n const homeDir = useHomeDir();\n\n // Classify the source once at render time.\n const classification = useMemo(\n () => classifyImageSrc(src || \"\", assetBase, homeDir),\n [src, assetBase, homeDir],\n );\n\n // For local images, fetch and track state.\n const imageState = useInlineImage(classification.kind === \"local\" ? classification.path : null);\n\n // Decide what to render.\n const view = selectInlineImageView(classification, imageState, src, alt);\n\n // Remote images: pass through unchanged (what react-markdown's default would do).\n if (view.kind === \"remote\") {\n return <img src={view.src} alt={view.alt} className={styles.inlineImage} />;\n }\n\n // Unresolvable or error: render text fallback in inline monospace.\n if (view.kind === \"unresolvable\" || view.kind === \"error\") {\n return <code className={styles.inlineImageFallback}>{view.fallbackText}</code>;\n }\n\n // Loading or idle: skeleton.\n if (view.kind === \"loading\") {\n return (\n <div className={styles.inlineImageSkeleton}>\n <Spinner size=\"sm\" />\n </div>\n );\n }\n\n // Ready: render the fetched image with click-to-open handler, converged onto the same\n // `openFileTab` dispatch the Files tree and `FileLink` use — puts the pane-targeting fix\n // (owning tab's real `workspaceCwd`, `owningPaneId`) in exactly one place for both features.\n const target = resolveFileOpenTarget(assetBase, owningPaneId ?? null, workspaceCwd ?? null);\n const handleClick = () => {\n openFileTab(view.path, target.workspaceCwd, target.targetPaneId);\n };\n\n return (\n <img\n src={view.objectUrl}\n alt={view.alt}\n className={styles.inlineImage}\n title={view.path}\n draggable\n onDragStart={pathDragStartHandler(view.path)}\n onClick={handleClick}\n style={{ cursor: \"pointer\" }}\n />\n );\n});\n","/**\n * Markdown file link source classification (features/file-link-rendering.md § Public Contract →\n * Markdown link source classification). Decides whether a markdown link `[label](href)` should\n * open a local file (intercepted by the client) or navigate as a regular link.\n *\n * Two-way classification simpler than the image classifier's three-way one:\n * - `local`: resolves to a local filesystem path → intercept, open as a file\n * - `external`: anything else → pass through as a regular navigating anchor\n *\n * Pure: no store/hook/network imports, so this file needs no React or client mocks to test.\n */\n\nimport { resolveHrefCandidate } from \"./href-resolution.js\";\n\nexport type FileLinkClassification = { kind: \"local\"; path: string } | { kind: \"external\" };\n\n/**\n * Classifies a markdown link `href`. `base` is the asset base (absolute, tilde-normalized) or\n * `null` when unknown; `homeDir` may be `null` when the daemon's home directory hasn't been\n * learned yet. Order matters — this mirrors the scope's classification table exactly:\n *\n * 1. empty/whitespace → external\n * 2. fragment-only (`#section`) → external (in-page anchor must not be intercepted)\n * 3. path+fragment (`README.md#usage`) → fragment stripped by resolver, remainder classifies\n * 4. `http:`/`https:` scheme → external\n * 5. any other `scheme:` prefix (incl. `file:`) → external\n * 6. `/…` → local, path used as-is\n * 7. `~`/`~/…` → local, `~` expanded (unknown home dir → external)\n * 8. `./…`, `../…`, bare relative → local, joined against `base` (no base → external)\n * 9. No extension gate (unlike images) — any resolved local path qualifies, including directories\n */\nexport function classifyFileLinkSrc(\n href: string,\n base: string | null,\n homeDir: string | null,\n): FileLinkClassification {\n const trimmed = href.trim();\n if (!trimmed) return { kind: \"external\" };\n\n // Fragment-only check: if the href contains only `#`, it's an in-page anchor\n if (trimmed.startsWith(\"#\")) return { kind: \"external\" };\n\n // Use the shared resolution step: strips fragments/query, resolves paths, normalizes + decodes\n const candidate = resolveHrefCandidate(href, base, homeDir);\n\n // If resolved successfully, it's a local file link; otherwise external\n if (candidate) {\n return { kind: \"local\", path: candidate };\n }\n return { kind: \"external\" };\n}\n","/**\n * `[label](href)` renderer for finalized assistant markdown (features/file-link-rendering.md §\n * Render pipeline, § Click-to-open pane targeting, § Drag-to-split). `classifyFileLinkSrc`'s\n * `external` result renders an ordinary, unmodified anchor — never intercepted, so in-page anchors\n * and real links keep working exactly as the browser's default. A `local` result renders an\n * actionable, draggable anchor: click prevents navigation and dispatches through the same\n * `openFileTab` primitive the Files tree and its context menu already use, targeted at the owning\n * chat tab's pane — the converged click-to-open dispatch `InlineImage` also uses\n * (features/inline-image-rendering.md § Click-to-open, amended); drag carries the identical\n * `EXTERNAL_DRAG_MIME.path` payload a Files-tree row drag carries, so dropping it onto a pane's\n * edge splits and opens it there, with zero drop-side changes needed.\n */\n\nimport type { ReactNode } from \"react\";\nimport { classifyFileLinkSrc } from \"./file-link-src.js\";\nimport { resolveFileOpenTarget } from \"./file-open-target.js\";\nimport { useHomeDir } from \"@pi-studio-ui/hooks/use-home-dir.js\";\nimport { openFileTab } from \"@pi-studio-ui/features/files/open-file-tab.js\";\nimport { pathDragStartHandler } from \"@pi-studio-ui/features/workspace/external-drag.js\";\n\nexport interface FileLinkProps {\n href?: string;\n children?: ReactNode;\n assetBase: string | null;\n owningPaneId: string | null;\n workspaceCwd: string | null;\n}\n\nexport function FileLink({ href, children, assetBase, owningPaneId, workspaceCwd }: FileLinkProps) {\n const homeDir = useHomeDir();\n const classification = classifyFileLinkSrc(href ?? \"\", assetBase, homeDir);\n\n if (classification.kind === \"external\") {\n return <a href={href}>{children}</a>;\n }\n\n const path = classification.path;\n const target = resolveFileOpenTarget(assetBase, owningPaneId, workspaceCwd);\n return (\n <a\n href={href}\n draggable\n onDragStart={pathDragStartHandler(path)}\n onClick={(event) => {\n event.preventDefault();\n openFileTab(path, target.workspaceCwd, target.targetPaneId);\n }}\n >\n {children}\n </a>\n );\n}\n","/**\n * react-markdown + remark-gfm rendering, replacing the POC's CDN `marked` + `innerHTML`\n * (POC_TO_APP_PLAN_UI.md §4.8). Sanitized by default — react-markdown never injects raw HTML.\n * Fenced code blocks highlight asynchronously via Shiki (`highlight.ts`).\n */\n\nimport { memo, useEffect, useState, type ComponentPropsWithoutRef } from \"react\";\nimport ReactMarkdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport { highlightToHtml } from \"./highlight.js\";\nimport styles from \"./markdown.module.css\";\nimport { InlineImage } from \"./InlineImage.js\";\nimport { FileLink } from \"./FileLink.js\";\n\ninterface CodeBlockProps {\n language: string;\n code: string;\n}\n\nfunction CodeBlock({ language, code }: CodeBlockProps) {\n const [html, setHtml] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n void highlightToHtml(code, language).then((result) => {\n if (!cancelled) setHtml(result);\n });\n return () => {\n cancelled = true;\n };\n }, [code, language]);\n\n if (html) {\n // Shiki's output is generated HTML from a trusted local highlighter (no user HTML is ever\n // injected) — the only risk is `code`, which Shiki escapes internally before tokenizing.\n return <div className={styles.prose} dangerouslySetInnerHTML={{ __html: html }} />;\n }\n return (\n <pre>\n <code>{code}</code>\n </pre>\n );\n}\n\ntype MarkdownCodeProps = ComponentPropsWithoutRef<\"code\"> & { className?: string };\n\nfunction CodeRenderer({ className, children, ...rest }: MarkdownCodeProps) {\n const match = /language-(\\w+)/.exec(className ?? \"\");\n const isBlock = Boolean(match);\n const code = String(children).replace(/\\n$/, \"\");\n if (isBlock && match) {\n return <CodeBlock language={match[1] ?? \"plaintext\"} code={code} />;\n }\n return (\n <code className={styles.inlineCode} {...rest}>\n {children}\n </code>\n );\n}\n\nexport interface MarkdownProps {\n text: string;\n assetBase?: string | null;\n owningPaneId?: string | null;\n workspaceCwd?: string | null;\n}\n\n/** Renders assistant/tool markdown text. Memoized — text is immutable once a turn finalizes. */\nexport const Markdown = memo(function Markdown({\n text,\n assetBase = null,\n owningPaneId = null,\n workspaceCwd = null,\n}: MarkdownProps) {\n return (\n <div className={styles.prose}>\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n components={{\n code: CodeRenderer,\n img: (props) => (\n <InlineImage\n {...props}\n assetBase={assetBase}\n owningPaneId={owningPaneId}\n workspaceCwd={workspaceCwd}\n />\n ),\n a: (props) => (\n <FileLink\n {...props}\n assetBase={assetBase}\n owningPaneId={owningPaneId}\n workspaceCwd={workspaceCwd}\n />\n ),\n }}\n >\n {text}\n </ReactMarkdown>\n </div>\n );\n});\n"],"names":["THEME","highlighterPromise","loadedLangs","getHighlighter","createHighlighter","ensureLang","highlighter","lang","highlightToHtml","code","resolved","SCHEME_RE","percentDecode","str","resolveHrefCandidate","href","base","homeDir","trimmed","stripped","candidate","normalizeCwd","resolveWorkspacePath","normalized","collapseDotSegments","REMOTE_SCHEMES","classifyImageSrc","src","schemeMatch","detectViewerKind","selectInlineImageView","classification","imageState","alt","fallbackText","resolveFileOpenTarget","assetBase","owningPaneId","workspaceCwd","loadInlineImage","path","download","onStateChange","cancelled","acquireInlineImage","entry","error","releaseInlineImage","useInlineImage","client","useConnectionStore","s","daemon","state","setState","useState","useEffect","p","transferFor","InlineImage","memo","useHomeDir","useMemo","view","jsx","styles","Spinner","target","handleClick","openFileTab","pathDragStartHandler","classifyFileLinkSrc","FileLink","children","event","CodeBlock","language","html","setHtml","result","CodeRenderer","className","rest","match","isBlock","Markdown","text","ReactMarkdown","remarkGfm","props"],"mappings":"uRAgDA,MAAMA,EAAQ,cAEd,IAAIC,EAAkD,KACtD,MAAMC,EAAc,IAAI,IAAY,CAAC,WAAW,CAAC,EAEjD,SAASC,GAAuC,CAC9C,OAAKF,IACHA,EAAqBG,EAAkB,CAAE,OAAQ,CAACJ,CAAK,EAAG,MAAO,CAAC,WAAW,EAAG,GAE3EC,CACT,CAEA,eAAeI,EAAWC,EAA0BC,EAA+B,CACjF,GAAIL,EAAY,IAAIK,CAAI,EAAG,OAAOA,EAClC,GAAI,CACF,aAAMD,EAAY,aAAaC,CAAa,EAC5CL,EAAY,IAAIK,CAAI,EACbA,CACT,MAAQ,CACN,MAAO,WACT,CACF,CAGA,eAAsBC,EAAgBC,EAAcF,EAA+B,CACjF,MAAMD,EAAc,MAAMH,EAAA,EACpBO,EAAW,MAAML,EAAWC,EAAaC,CAAI,EACnD,OAAOD,EAAY,WAAWG,EAAM,CAAE,KAAMC,EAAU,MAAOV,EAAO,CACtE,oOC/DMW,EAAY,8BAMlB,SAASC,EAAcC,EAAqB,CAC1C,GAAI,CACF,OAAO,mBAAmBA,CAAG,CAC/B,MAAQ,CAEN,OAAOA,CACT,CACF,CAcO,SAASC,EACdC,EACAC,EACAC,EACe,CACf,MAAMC,EAAUH,EAAK,KAAA,EACrB,GAAI,CAACG,EAAS,OAAO,KAGrB,MAAMC,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ASgB,GAAa,CAAE,UAAAC,EAAW,SAAAR,EAAU,GAAGS,GAA2B,CACzE,MAAMC,EAAQ,iBAAiB,KAAKF,GAAa,EAAE,EAC7CG,EAAU,EAAQD,EAClB1E,EAAO,OAAOgE,CAAQ,EAAE,QAAQ,MAAO,EAAE,EAC/C,OAAIW,GAAWD,QACLR,GAAA,CAAU,SAAUQ,EAAM,CAAC,GAAK,YAAa,KAAA1E,EAAY,QAGhE,OAAA,CAAK,UAAWwD,EAAO,WAAa,GAAGiB,EACrC,SAAAT,EACH,CAEJ,CAUO,MAAMY,GAAWzB,EAAAA,KAAK,SAAkB,CAC7C,KAAA0B,EACA,UAAAlD,EAAY,KACZ,aAAAC,EAAe,KACf,aAAAC,EAAe,IACjB,EAAkB,CAChB,OACE0B,EAAAA,IAAC,MAAA,CAAI,UAAWC,EAAO,MACrB,SAAAD,EAAAA,IAACuB,EAAA,CACC,cAAe,CAACC,CAAS,EACzB,WAAY,CACV,KAAMR,GACN,IAAMS,GACJzB,EAAAA,IAACL,EAAA,CACE,GAAG8B,EACJ,UAAArD,EACA,aAAAC,EACA,aAAAC,CAAA,CAAA,EAGJ,EAAImD,GACFzB,EAAAA,IAACQ,EAAA,CACE,GAAGiB,EACJ,UAAArD,EACA,aAAAC,EACA,aAAAC,CAAA,CAAA,CACF,EAIH,SAAAgD,CAAA,CAAA,EAEL,CAEJ,CAAC"}
@@ -1,2 +1,2 @@
1
- import{r as a}from"./vendor-react-CWo7Do4s.js";import{u as f}from"./vendor-query-BGIh-vlp.js";import{a as s,q as m,r as y}from"./index-DM5KSYdn.js";function p(o,u=!0){var i;const l=s(e=>e.client),n=s(e=>e.daemon),c=f({queryKey:y.fileDownload(o),queryFn:async()=>{if(!l||!n)throw new Error("not connected");const e=await m(n).download(o),t=new Blob([Uint8Array.from(e.bytes)],{type:e.mimeType||"application/octet-stream"});return{objectUrl:URL.createObjectURL(t),mimeType:e.mimeType,fileName:e.fileName}},enabled:!!l&&!!n&&!!o&&u,staleTime:1/0,gcTime:0}),r=a.useRef(null);return a.useEffect(()=>{var t;const e=((t=c.data)==null?void 0:t.objectUrl)??null;e&&r.current&&r.current!==e&&URL.revokeObjectURL(r.current),r.current=e},[(i=c.data)==null?void 0:i.objectUrl]),a.useEffect(()=>()=>{r.current&&URL.revokeObjectURL(r.current)},[]),c}export{p as u};
2
- //# sourceMappingURL=use-file-download-BOCZENOG.js.map
1
+ import{r as a}from"./vendor-react-CWo7Do4s.js";import{u as f}from"./vendor-query-BGIh-vlp.js";import{a as s,q as m,r as y}from"./index-DonKPQN3.js";function p(o,u=!0){var i;const l=s(e=>e.client),n=s(e=>e.daemon),c=f({queryKey:y.fileDownload(o),queryFn:async()=>{if(!l||!n)throw new Error("not connected");const e=await m(n).download(o),t=new Blob([Uint8Array.from(e.bytes)],{type:e.mimeType||"application/octet-stream"});return{objectUrl:URL.createObjectURL(t),mimeType:e.mimeType,fileName:e.fileName}},enabled:!!l&&!!n&&!!o&&u,staleTime:1/0,gcTime:0}),r=a.useRef(null);return a.useEffect(()=>{var t;const e=((t=c.data)==null?void 0:t.objectUrl)??null;e&&r.current&&r.current!==e&&URL.revokeObjectURL(r.current),r.current=e},[(i=c.data)==null?void 0:i.objectUrl]),a.useEffect(()=>()=>{r.current&&URL.revokeObjectURL(r.current)},[]),c}export{p as u};
2
+ //# sourceMappingURL=use-file-download-C2Lrmbfe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-file-download-BOCZENOG.js","sources":["../../../src/hooks/use-file-download.ts"],"sourcesContent":["/**\n * `use-file-download` — TanStack Query wrapper over the binary file-transfer download path\n * (`file_download_token_request` → `file_download_request` → chunked `Begin`/`Chunk`/`End`\n * binary frames), for viewers that need raw bytes rather than the UTF-8 preview\n * `file_read_request` returns (images, video — POC_TO_APP_PLAN_UI.md §4.5 follow-up: modular\n * file preview). Resolves to an object URL, revoked once superseded by a new one or once this\n * consumer unmounts.\n */\n\nimport { useEffect, useRef } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { rpcKeys } from \"@pi-studio-ui/lib/connection/rpc-keys.js\";\nimport { transferFor } from \"./file-transfer-instance.js\";\n\nexport interface FileDownload {\n objectUrl: string;\n mimeType?: string;\n fileName?: string;\n}\n\nexport function useFileDownload(path: string, enabled = true) {\n const client = useConnectionStore((s) => s.client);\n const daemon = useConnectionStore((s) => s.daemon);\n\n const query = useQuery({\n queryKey: rpcKeys.fileDownload(path),\n queryFn: async (): Promise<FileDownload> => {\n if (!client || !daemon) throw new Error(\"not connected\");\n const file = await transferFor(daemon).download(path);\n // `Blob`'s DOM typings require an `ArrayBuffer`-backed view; the assembled `Uint8Array`'s\n // `ArrayBufferLike` backing (a decode-time implementation detail) doesn't satisfy that on\n // its own, so copy into a plain `ArrayBuffer`-backed `Uint8Array` first.\n const blob = new Blob([Uint8Array.from(file.bytes)], {\n type: file.mimeType || \"application/octet-stream\",\n });\n return {\n objectUrl: URL.createObjectURL(blob),\n mimeType: file.mimeType,\n fileName: file.fileName,\n };\n },\n enabled: Boolean(client) && Boolean(daemon) && Boolean(path) && enabled,\n // Object URLs are process-local, non-serializable browser resources — never persist them or\n // silently refetch behind this hook's back (that would leak the previous blob's URL).\n staleTime: Infinity,\n gcTime: 0,\n });\n\n // Revoke the previous object URL once a new one supersedes it, and the current one on unmount\n // — TanStack Query's cache has no notion that this value owns a browser resource to release.\n const urlRef = useRef<string | null>(null);\n useEffect(() => {\n const nextUrl = query.data?.objectUrl ?? null;\n if (nextUrl && urlRef.current && urlRef.current !== nextUrl) {\n URL.revokeObjectURL(urlRef.current);\n }\n urlRef.current = nextUrl;\n }, [query.data?.objectUrl]);\n\n useEffect(() => {\n return () => {\n if (urlRef.current) URL.revokeObjectURL(urlRef.current);\n };\n }, []);\n\n return query;\n}\n"],"names":["useFileDownload","path","enabled","client","useConnectionStore","s","daemon","query","useQuery","rpcKeys","file","transferFor","blob","urlRef","useRef","useEffect","nextUrl","_a"],"mappings":"oJAqBO,SAASA,EAAgBC,EAAcC,EAAU,GAAM,OAC5D,MAAMC,EAASC,EAAoBC,GAAMA,EAAE,MAAM,EAC3CC,EAASF,EAAoBC,GAAMA,EAAE,MAAM,EAE3CE,EAAQC,EAAS,CACrB,SAAUC,EAAQ,aAAaR,CAAI,EACnC,QAAS,SAAmC,CAC1C,GAAI,CAACE,GAAU,CAACG,EAAQ,MAAM,IAAI,MAAM,eAAe,EACvD,MAAMI,EAAO,MAAMC,EAAYL,CAAM,EAAE,SAASL,CAAI,EAI9CW,EAAO,IAAI,KAAK,CAAC,WAAW,KAAKF,EAAK,KAAK,CAAC,EAAG,CACnD,KAAMA,EAAK,UAAY,0BAAA,CACxB,EACD,MAAO,CACL,UAAW,IAAI,gBAAgBE,CAAI,EACnC,SAAUF,EAAK,SACf,SAAUA,EAAK,QAAA,CAEnB,EACA,QAAS,EAAQP,GAAW,EAAQG,GAAW,EAAQL,GAASC,EAGhE,UAAW,IACX,OAAQ,CAAA,CACT,EAIKW,EAASC,EAAAA,OAAsB,IAAI,EACzCC,OAAAA,EAAAA,UAAU,IAAM,OACd,MAAMC,IAAUC,EAAAV,EAAM,OAAN,YAAAU,EAAY,YAAa,KACrCD,GAAWH,EAAO,SAAWA,EAAO,UAAYG,GAClD,IAAI,gBAAgBH,EAAO,OAAO,EAEpCA,EAAO,QAAUG,CACnB,EAAG,EAACC,EAAAV,EAAM,OAAN,YAAAU,EAAY,SAAS,CAAC,EAE1BF,EAAAA,UAAU,IACD,IAAM,CACPF,EAAO,SAAS,IAAI,gBAAgBA,EAAO,OAAO,CACxD,EACC,CAAA,CAAE,EAEEN,CACT"}
1
+ {"version":3,"file":"use-file-download-C2Lrmbfe.js","sources":["../../../src/hooks/use-file-download.ts"],"sourcesContent":["/**\n * `use-file-download` — TanStack Query wrapper over the binary file-transfer download path\n * (`file_download_token_request` → `file_download_request` → chunked `Begin`/`Chunk`/`End`\n * binary frames), for viewers that need raw bytes rather than the UTF-8 preview\n * `file_read_request` returns (images, video — POC_TO_APP_PLAN_UI.md §4.5 follow-up: modular\n * file preview). Resolves to an object URL, revoked once superseded by a new one or once this\n * consumer unmounts.\n */\n\nimport { useEffect, useRef } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { rpcKeys } from \"@pi-studio-ui/lib/connection/rpc-keys.js\";\nimport { transferFor } from \"./file-transfer-instance.js\";\n\nexport interface FileDownload {\n objectUrl: string;\n mimeType?: string;\n fileName?: string;\n}\n\nexport function useFileDownload(path: string, enabled = true) {\n const client = useConnectionStore((s) => s.client);\n const daemon = useConnectionStore((s) => s.daemon);\n\n const query = useQuery({\n queryKey: rpcKeys.fileDownload(path),\n queryFn: async (): Promise<FileDownload> => {\n if (!client || !daemon) throw new Error(\"not connected\");\n const file = await transferFor(daemon).download(path);\n // `Blob`'s DOM typings require an `ArrayBuffer`-backed view; the assembled `Uint8Array`'s\n // `ArrayBufferLike` backing (a decode-time implementation detail) doesn't satisfy that on\n // its own, so copy into a plain `ArrayBuffer`-backed `Uint8Array` first.\n const blob = new Blob([Uint8Array.from(file.bytes)], {\n type: file.mimeType || \"application/octet-stream\",\n });\n return {\n objectUrl: URL.createObjectURL(blob),\n mimeType: file.mimeType,\n fileName: file.fileName,\n };\n },\n enabled: Boolean(client) && Boolean(daemon) && Boolean(path) && enabled,\n // Object URLs are process-local, non-serializable browser resources — never persist them or\n // silently refetch behind this hook's back (that would leak the previous blob's URL).\n staleTime: Infinity,\n gcTime: 0,\n });\n\n // Revoke the previous object URL once a new one supersedes it, and the current one on unmount\n // — TanStack Query's cache has no notion that this value owns a browser resource to release.\n const urlRef = useRef<string | null>(null);\n useEffect(() => {\n const nextUrl = query.data?.objectUrl ?? null;\n if (nextUrl && urlRef.current && urlRef.current !== nextUrl) {\n URL.revokeObjectURL(urlRef.current);\n }\n urlRef.current = nextUrl;\n }, [query.data?.objectUrl]);\n\n useEffect(() => {\n return () => {\n if (urlRef.current) URL.revokeObjectURL(urlRef.current);\n };\n }, []);\n\n return query;\n}\n"],"names":["useFileDownload","path","enabled","client","useConnectionStore","s","daemon","query","useQuery","rpcKeys","file","transferFor","blob","urlRef","useRef","useEffect","nextUrl","_a"],"mappings":"oJAqBO,SAASA,EAAgBC,EAAcC,EAAU,GAAM,OAC5D,MAAMC,EAASC,EAAoBC,GAAMA,EAAE,MAAM,EAC3CC,EAASF,EAAoBC,GAAMA,EAAE,MAAM,EAE3CE,EAAQC,EAAS,CACrB,SAAUC,EAAQ,aAAaR,CAAI,EACnC,QAAS,SAAmC,CAC1C,GAAI,CAACE,GAAU,CAACG,EAAQ,MAAM,IAAI,MAAM,eAAe,EACvD,MAAMI,EAAO,MAAMC,EAAYL,CAAM,EAAE,SAASL,CAAI,EAI9CW,EAAO,IAAI,KAAK,CAAC,WAAW,KAAKF,EAAK,KAAK,CAAC,EAAG,CACnD,KAAMA,EAAK,UAAY,0BAAA,CACxB,EACD,MAAO,CACL,UAAW,IAAI,gBAAgBE,CAAI,EACnC,SAAUF,EAAK,SACf,SAAUA,EAAK,QAAA,CAEnB,EACA,QAAS,EAAQP,GAAW,EAAQG,GAAW,EAAQL,GAASC,EAGhE,UAAW,IACX,OAAQ,CAAA,CACT,EAIKW,EAASC,EAAAA,OAAsB,IAAI,EACzCC,OAAAA,EAAAA,UAAU,IAAM,OACd,MAAMC,IAAUC,EAAAV,EAAM,OAAN,YAAAU,EAAY,YAAa,KACrCD,GAAWH,EAAO,SAAWA,EAAO,UAAYG,GAClD,IAAI,gBAAgBH,EAAO,OAAO,EAEpCA,EAAO,QAAUG,CACnB,EAAG,EAACC,EAAAV,EAAM,OAAN,YAAAU,EAAY,SAAS,CAAC,EAE1BF,EAAAA,UAAU,IACD,IAAM,CACPF,EAAO,SAAS,IAAI,gBAAgBA,EAAO,OAAO,CACxD,EACC,CAAA,CAAE,EAEEN,CACT"}
@@ -1,2 +1,2 @@
1
- import{r as a}from"./vendor-react-CWo7Do4s.js";import{a as w}from"./index-DM5KSYdn.js";function b(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="file_changed"&&"path"in e&&typeof e.path=="string"}const l=new WeakMap;function p(e,t,i){let s=l.get(e);s||(s=new Map,l.set(e,s));let o=s.get(t);if(!o){const r={count:0,resolvedPath:null,listeners:new Set,dispose:()=>{}},f=e.connection.onSessionMessage(c=>{const n=c;if(!b(n)||n.path!==t&&n.path!==r.resolvedPath)return;const d=Date.now();for(const h of r.listeners)h(d)});e.connection.request("file_watch_subscribe",{path:t}).then(c=>{const n=c;if((n==null?void 0:n.ok)===!1){console.warn(`watchFile: ${n.error??"subscribe failed"} for "${t}"`);return}typeof(n==null?void 0:n.path)=="string"&&(r.resolvedPath=n.path)}).catch(()=>{}),r.dispose=()=>{f(),e.connection.request("file_watch_unsubscribe",{path:t}).catch(()=>{})},o=r,s.set(t,o)}o.count++,o.listeners.add(i);let u=!1;return()=>{if(u)return;u=!0;const r=s.get(t);r&&(r.listeners.delete(i),r.count--,r.count===0&&(s.delete(t),r.dispose()))}}function v(e){const t=w(o=>o.client),[i,s]=a.useState(null);return a.useEffect(()=>{if(!(!t||!e))return p(t,e,s)},[t,e]),{changedAt:i}}export{v as u};
2
- //# sourceMappingURL=use-file-watch-CWtZGJOx.js.map
1
+ import{r as a}from"./vendor-react-CWo7Do4s.js";import{a as w}from"./index-DonKPQN3.js";function b(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="file_changed"&&"path"in e&&typeof e.path=="string"}const l=new WeakMap;function p(e,t,i){let s=l.get(e);s||(s=new Map,l.set(e,s));let o=s.get(t);if(!o){const r={count:0,resolvedPath:null,listeners:new Set,dispose:()=>{}},f=e.connection.onSessionMessage(c=>{const n=c;if(!b(n)||n.path!==t&&n.path!==r.resolvedPath)return;const d=Date.now();for(const h of r.listeners)h(d)});e.connection.request("file_watch_subscribe",{path:t}).then(c=>{const n=c;if((n==null?void 0:n.ok)===!1){console.warn(`watchFile: ${n.error??"subscribe failed"} for "${t}"`);return}typeof(n==null?void 0:n.path)=="string"&&(r.resolvedPath=n.path)}).catch(()=>{}),r.dispose=()=>{f(),e.connection.request("file_watch_unsubscribe",{path:t}).catch(()=>{})},o=r,s.set(t,o)}o.count++,o.listeners.add(i);let u=!1;return()=>{if(u)return;u=!0;const r=s.get(t);r&&(r.listeners.delete(i),r.count--,r.count===0&&(s.delete(t),r.dispose()))}}function v(e){const t=w(o=>o.client),[i,s]=a.useState(null);return a.useEffect(()=>{if(!(!t||!e))return p(t,e,s)},[t,e]),{changedAt:i}}export{v as u};
2
+ //# sourceMappingURL=use-file-watch-skGpUUS7.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-file-watch-CWtZGJOx.js","sources":["../../../src/hooks/use-file-watch.ts"],"sourcesContent":["/**\n * `use-file-watch` — subscribes to live daemon `file_changed` pushes for a path (task-006's\n * `FileWatchService`), structurally mirroring `use-checkout-status.ts`: subscribe on mount/path\n * change via `file_watch_subscribe`, route matching pushes through `onSessionMessage`, and on\n * cleanup detach the message handler AND send `file_watch_unsubscribe` for the path being left —\n * `use-checkout-status.ts`'s own header comment calls out that leaving either half undone is the\n * leak this pattern exists to avoid.\n *\n * The actual subscribe/route/cleanup wiring lives in `watchFile`, a plain function with no React\n * dependency (mirrors `molecule-source.ts`/`molecule-reload.ts`'s \"extract the testable core\"\n * convention) — this repo has no DOM test environment set up, so it is the seam\n * `use-file-watch.test.ts` exercises directly with a fake client rather than mounting the hook.\n *\n * A `null` path (an empty \"+\"-menu molecule tab, or the absence of a client) subscribes nothing.\n *\n * `watchFile` ref-counts subscriptions per `(client, path)` in a module-level registry (mirrors\n * `file-transfer-instance.ts`'s `WeakMap<DaemonClient, …>` shared-instance convention): more than\n * one component can watch the same file (a file tab and a diff tab on the same path) and share\n * ONE daemon watch, rather than the second `file_watch_unsubscribe` killing it for both — the\n * daemon's `SessionSubscriptions.add` disposes any existing entry for the same resolved-path key.\n * The entry also remembers the RESOLVED path echoed back by `file_watch_subscribe_response.path`\n * (the daemon expands a leading `~` server-side before pushing `file_changed`), and matches a\n * push against either the requested spelling or that resolved path.\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { PiStudioClient } from \"@av-pi-studio/client\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\n\ninterface FileChangedMessage {\n type: \"file_changed\";\n path: string;\n}\n\nfunction isFileChangedMessage(msg: unknown): msg is FileChangedMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"file_changed\" &&\n \"path\" in msg &&\n typeof msg.path === \"string\"\n );\n}\n\ninterface FileWatchSubscribeResponse {\n ok?: boolean;\n error?: string;\n path?: string;\n}\n\ninterface WatchEntry {\n count: number;\n /** Resolved path echoed by `file_watch_subscribe_response.path`; `null` until it arrives. */\n resolvedPath: string | null;\n listeners: Set<(changedAt: number) => void>;\n dispose: () => void;\n}\n\nconst watchesByClient = new WeakMap<Pick<PiStudioClient, \"connection\">, Map<string, WatchEntry>>();\n\n/** Subscribes `path` on `client.connection`, calls `onChanged` for every matching `file_changed`\n * push, and returns a cleanup function that detaches the handler AND sends\n * `file_watch_unsubscribe` for `path` once the LAST subscriber for that `(client, path)` pair\n * releases it. Framework-agnostic on purpose — see module header. */\nexport function watchFile(\n client: Pick<PiStudioClient, \"connection\">,\n path: string,\n onChanged: (changedAt: number) => void,\n): () => void {\n let entries = watchesByClient.get(client);\n if (!entries) {\n entries = new Map<string, WatchEntry>();\n watchesByClient.set(client, entries);\n }\n\n let entry = entries.get(path);\n if (!entry) {\n const created: WatchEntry = {\n count: 0,\n resolvedPath: null,\n listeners: new Set(),\n dispose: () => {},\n };\n\n const unsubscribeMessages = client.connection.onSessionMessage((msg) => {\n const raw: unknown = msg;\n if (!isFileChangedMessage(raw)) return;\n if (raw.path !== path && raw.path !== created.resolvedPath) return;\n const changedAt = Date.now();\n for (const listener of created.listeners) listener(changedAt);\n });\n\n void client.connection\n .request(\"file_watch_subscribe\", { path })\n .then((res) => {\n const response = res as FileWatchSubscribeResponse;\n if (response?.ok === false) {\n console.warn(`watchFile: ${response.error ?? \"subscribe failed\"} for \"${path}\"`);\n return;\n }\n if (typeof response?.path === \"string\") {\n created.resolvedPath = response.path;\n }\n })\n .catch(() => {});\n\n created.dispose = () => {\n unsubscribeMessages();\n void client.connection.request(\"file_watch_unsubscribe\", { path }).catch(() => {});\n };\n\n entry = created;\n entries.set(path, entry);\n }\n\n entry.count++;\n entry.listeners.add(onChanged);\n\n let released = false;\n return () => {\n if (released) return; // Idempotent: a second call must never double-release.\n released = true;\n const current = entries!.get(path);\n if (!current) return;\n current.listeners.delete(onChanged);\n current.count--;\n if (current.count === 0) {\n entries!.delete(path);\n current.dispose();\n }\n };\n}\n\nexport interface UseFileWatchResult {\n /** Monotonic timestamp of the last `file_changed` push for this path; `null` if none yet. */\n changedAt: number | null;\n}\n\nexport function useFileWatch(path: string | null): UseFileWatchResult {\n const client = useConnectionStore((s) => s.client);\n const [changedAt, setChangedAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (!client || !path) return;\n return watchFile(client, path, setChangedAt);\n }, [client, path]);\n\n return { changedAt };\n}\n"],"names":["isFileChangedMessage","msg","watchesByClient","watchFile","client","path","onChanged","entries","entry","created","unsubscribeMessages","raw","changedAt","listener","res","response","released","current","useFileWatch","useConnectionStore","s","setChangedAt","useState","useEffect"],"mappings":"uFAkCA,SAASA,EAAqBC,EAAyC,CACrE,OACE,OAAOA,GAAQ,UACfA,IAAQ,MACR,SAAUA,GACVA,EAAI,OAAS,gBACb,SAAUA,GACV,OAAOA,EAAI,MAAS,QAExB,CAgBA,MAAMC,MAAsB,QAMrB,SAASC,EACdC,EACAC,EACAC,EACY,CACZ,IAAIC,EAAUL,EAAgB,IAAIE,CAAM,EACnCG,IACHA,MAAc,IACdL,EAAgB,IAAIE,EAAQG,CAAO,GAGrC,IAAIC,EAAQD,EAAQ,IAAIF,CAAI,EAC5B,GAAI,CAACG,EAAO,CACV,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AAwB,IAAI,EAE9DC,OAAAA,EAAAA,UAAU,IAAM,CACd,GAAI,GAACnB,GAAU,CAACC,GAChB,OAAOF,EAAUC,EAAQC,EAAMgB,CAAY,CAC7C,EAAG,CAACjB,EAAQC,CAAI,CAAC,EAEV,CAAE,UAAAO,CAAA,CACX"}
1
+ {"version":3,"file":"use-file-watch-skGpUUS7.js","sources":["../../../src/hooks/use-file-watch.ts"],"sourcesContent":["/**\n * `use-file-watch` — subscribes to live daemon `file_changed` pushes for a path (task-006's\n * `FileWatchService`), structurally mirroring `use-checkout-status.ts`: subscribe on mount/path\n * change via `file_watch_subscribe`, route matching pushes through `onSessionMessage`, and on\n * cleanup detach the message handler AND send `file_watch_unsubscribe` for the path being left —\n * `use-checkout-status.ts`'s own header comment calls out that leaving either half undone is the\n * leak this pattern exists to avoid.\n *\n * The actual subscribe/route/cleanup wiring lives in `watchFile`, a plain function with no React\n * dependency (mirrors `molecule-source.ts`/`molecule-reload.ts`'s \"extract the testable core\"\n * convention) — this repo has no DOM test environment set up, so it is the seam\n * `use-file-watch.test.ts` exercises directly with a fake client rather than mounting the hook.\n *\n * A `null` path (an empty \"+\"-menu molecule tab, or the absence of a client) subscribes nothing.\n *\n * `watchFile` ref-counts subscriptions per `(client, path)` in a module-level registry (mirrors\n * `file-transfer-instance.ts`'s `WeakMap<DaemonClient, …>` shared-instance convention): more than\n * one component can watch the same file (a file tab and a diff tab on the same path) and share\n * ONE daemon watch, rather than the second `file_watch_unsubscribe` killing it for both — the\n * daemon's `SessionSubscriptions.add` disposes any existing entry for the same resolved-path key.\n * The entry also remembers the RESOLVED path echoed back by `file_watch_subscribe_response.path`\n * (the daemon expands a leading `~` server-side before pushing `file_changed`), and matches a\n * push against either the requested spelling or that resolved path.\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { PiStudioClient } from \"@av-pi-studio/client\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\n\ninterface FileChangedMessage {\n type: \"file_changed\";\n path: string;\n}\n\nfunction isFileChangedMessage(msg: unknown): msg is FileChangedMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"file_changed\" &&\n \"path\" in msg &&\n typeof msg.path === \"string\"\n );\n}\n\ninterface FileWatchSubscribeResponse {\n ok?: boolean;\n error?: string;\n path?: string;\n}\n\ninterface WatchEntry {\n count: number;\n /** Resolved path echoed by `file_watch_subscribe_response.path`; `null` until it arrives. */\n resolvedPath: string | null;\n listeners: Set<(changedAt: number) => void>;\n dispose: () => void;\n}\n\nconst watchesByClient = new WeakMap<Pick<PiStudioClient, \"connection\">, Map<string, WatchEntry>>();\n\n/** Subscribes `path` on `client.connection`, calls `onChanged` for every matching `file_changed`\n * push, and returns a cleanup function that detaches the handler AND sends\n * `file_watch_unsubscribe` for `path` once the LAST subscriber for that `(client, path)` pair\n * releases it. Framework-agnostic on purpose — see module header. */\nexport function watchFile(\n client: Pick<PiStudioClient, \"connection\">,\n path: string,\n onChanged: (changedAt: number) => void,\n): () => void {\n let entries = watchesByClient.get(client);\n if (!entries) {\n entries = new Map<string, WatchEntry>();\n watchesByClient.set(client, entries);\n }\n\n let entry = entries.get(path);\n if (!entry) {\n const created: WatchEntry = {\n count: 0,\n resolvedPath: null,\n listeners: new Set(),\n dispose: () => {},\n };\n\n const unsubscribeMessages = client.connection.onSessionMessage((msg) => {\n const raw: unknown = msg;\n if (!isFileChangedMessage(raw)) return;\n if (raw.path !== path && raw.path !== created.resolvedPath) return;\n const changedAt = Date.now();\n for (const listener of created.listeners) listener(changedAt);\n });\n\n void client.connection\n .request(\"file_watch_subscribe\", { path })\n .then((res) => {\n const response = res as FileWatchSubscribeResponse;\n if (response?.ok === false) {\n console.warn(`watchFile: ${response.error ?? \"subscribe failed\"} for \"${path}\"`);\n return;\n }\n if (typeof response?.path === \"string\") {\n created.resolvedPath = response.path;\n }\n })\n .catch(() => {});\n\n created.dispose = () => {\n unsubscribeMessages();\n void client.connection.request(\"file_watch_unsubscribe\", { path }).catch(() => {});\n };\n\n entry = created;\n entries.set(path, entry);\n }\n\n entry.count++;\n entry.listeners.add(onChanged);\n\n let released = false;\n return () => {\n if (released) return; // Idempotent: a second call must never double-release.\n released = true;\n const current = entries!.get(path);\n if (!current) return;\n current.listeners.delete(onChanged);\n current.count--;\n if (current.count === 0) {\n entries!.delete(path);\n current.dispose();\n }\n };\n}\n\nexport interface UseFileWatchResult {\n /** Monotonic timestamp of the last `file_changed` push for this path; `null` if none yet. */\n changedAt: number | null;\n}\n\nexport function useFileWatch(path: string | null): UseFileWatchResult {\n const client = useConnectionStore((s) => s.client);\n const [changedAt, setChangedAt] = useState<number | null>(null);\n\n useEffect(() => {\n if (!client || !path) return;\n return watchFile(client, path, setChangedAt);\n }, [client, path]);\n\n return { changedAt };\n}\n"],"names":["isFileChangedMessage","msg","watchesByClient","watchFile","client","path","onChanged","entries","entry","created","unsubscribeMessages","raw","changedAt","listener","res","response","released","current","useFileWatch","useConnectionStore","s","setChangedAt","useState","useEffect"],"mappings":"uFAkCA,SAASA,EAAqBC,EAAyC,CACrE,OACE,OAAOA,GAAQ,UACfA,IAAQ,MACR,SAAUA,GACVA,EAAI,OAAS,gBACb,SAAUA,GACV,OAAOA,EAAI,MAAS,QAExB,CAgBA,MAAMC,MAAsB,QAMrB,SAASC,EACdC,EACAC,EACAC,EACY,CACZ,IAAIC,EAAUL,EAAgB,IAAIE,CAAM,EACnCG,IACHA,MAAc,IACdL,EAAgB,IAAIE,EAAQG,CAAO,GAGrC,IAAIC,EAAQD,EAAQ,IAAIF,CAAI,EAC5B,GAAI,CAACG,EAAO,CACV,MAAMC,EAAsB,CAC1B,MAAO,EACP,aAAc,KACd,cAAe,IACf,QAAS,IAAM,CAAC,CAAA,EAGZC,EAAsBN,EAAO,WAAW,iBAAkBH,GAAQ,CACtE,MAAMU,EAAeV,EAErB,GADI,CAACD,EAAqBW,CAAG,GACzBA,EAAI,OAASN,GAAQM,EAAI,OAASF,EAAQ,aAAc,O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8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>Pi-Studio</title>
7
- <script type="module" crossorigin src="/assets/index-DM5KSYdn.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-DonKPQN3.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-CWo7Do4s.js">
9
9
  <link rel="modulepreload" crossorigin href="/assets/vendor-query-BGIh-vlp.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/vendor-markdown-YvkQLm_s.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/web-client",
3
- "version": "0.0.69",
3
+ "version": "0.0.71",
4
4
  "files": [
5
5
  "dist"
6
6
  ],
@@ -14,8 +14,8 @@
14
14
  "clean": "rm -rf dist *.tsbuildinfo"
15
15
  },
16
16
  "dependencies": {
17
- "@av-pi-studio/client": "^0.0.69",
18
- "@av-pi-studio/protocol": "^0.0.69",
17
+ "@av-pi-studio/client": "^0.0.71",
18
+ "@av-pi-studio/protocol": "^0.0.71",
19
19
  "@codemirror/language": "^6.12.4",
20
20
  "@codemirror/language-data": "^6.5.2",
21
21
  "@codemirror/state": "^6.7.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"TerminalPanel-BHj10l7-.js","sources":["../../../../client/src/terminal-stream-router.ts","../../../src/features/terminal/terminal-size.ts","../../../src/features/terminal/TerminalPanel.tsx"],"sourcesContent":["import { encodeTerminalFrame, type TerminalFrame } from \"@av-pi-studio/protocol\";\n\nimport type { DaemonClient } from \"./daemon-client.js\";\n\n/**\n * Client-side demux of binary terminal frames to per-slot subscribers, plus outbound input/resize\n * encoding (architecture/client-app-runtime.md § Router; features/terminals.md § Binary stream\n * protocol).\n *\n * Inbound `Output`/`Snapshot`/`Restore` frames are dispatched to the subscriber registered for that\n * `slot`. Outbound `Input`/`Resize` are encoded with the right opcode + slot and sent on the data\n * path.\n */\n\nexport interface TerminalSlotSubscriber {\n /** Live terminal output bytes. */\n onOutput?: (data: Uint8Array) => void;\n /** Full-screen snapshot bytes (sent on (re)subscribe). */\n onSnapshot?: (data: Uint8Array) => void;\n /** Restore snapshot bytes (reflowable/mode-gated). */\n onRestore?: (data: Uint8Array) => void;\n}\n\nexport class TerminalStreamRouter {\n private readonly subscribers = new Map<number, TerminalSlotSubscriber>();\n private detach: (() => void) | null = null;\n\n constructor(private readonly daemon: DaemonClient) {}\n\n /** Begin routing inbound terminal frames. Idempotent. */\n start(): void {\n if (this.detach) return;\n this.detach = this.daemon.onTerminalFrame((frame) => this.dispatch(frame));\n }\n\n /** Stop routing inbound frames (subscribers retained). */\n stop(): void {\n this.detach?.();\n this.detach = null;\n }\n\n /** Register (or replace) the subscriber for a slot. Returns an unsubscribe fn. */\n subscribeSlot(slot: number, subscriber: TerminalSlotSubscriber): () => void {\n this.subscribers.set(slot, subscriber);\n return () => {\n if (this.subscribers.get(slot) === subscriber) this.subscribers.delete(slot);\n };\n }\n\n /** True iff a subscriber is registered for the slot. */\n hasSlot(slot: number): boolean {\n return this.subscribers.has(slot);\n }\n\n // ─── Outbound ─────────────────────────────────────────────────────────────\n\n /** Send raw input bytes to a slot's PTY (opcode `Input = 0x02`). */\n sendInput(slot: number, data: Uint8Array): void {\n this.daemon.sendBinary(encodeTerminalFrame({ opcode: \"Input\", slot, data }));\n }\n\n /** Send a resize (opcode `Resize = 0x03`, JSON `{ rows, cols }` payload). */\n sendResize(slot: number, rows: number, cols: number): void {\n this.daemon.sendBinary(encodeTerminalFrame({ opcode: \"Resize\", slot, rows, cols }));\n }\n\n // ─── Inbound dispatch ───────────────────────────────────────────────────────\n\n private dispatch(frame: TerminalFrame): void {\n const subscriber = this.subscribers.get(frame.slot);\n if (!subscriber) return; // no subscriber for this slot — drop\n switch (frame.opcode) {\n case \"Output\":\n subscriber.onOutput?.(frame.data);\n return;\n case \"Snapshot\":\n subscriber.onSnapshot?.(frame.data);\n return;\n case \"Restore\":\n subscriber.onRestore?.(frame.data);\n return;\n default:\n // Input/Resize are outbound-only; ignore if echoed back.\n return;\n }\n }\n}\n","/**\n * Terminal PTY size-claim decisions (`clean-room-scope/features/terminals.md` § PTY size\n * ownership). Pure and DOM-free so the ownership gate is unit-testable under the repo's Node-only\n * vitest environment — `TerminalPanel.tsx` is the only caller.\n *\n * The model separates two things an earlier revision conflated into one `lastClaimed` ref, which is\n * what made restored terminals unfixable-by-resize:\n *\n * - **Knowledge** — `believed`: the grid this client thinks the PTY currently has (from a\n * create-time echo, or from the last size it successfully sent). Only ever used to dedupe.\n * - **Permission** — `isSizeAuthority` in `TerminalPanel.tsx`: whether this panel is the one\n * rendering the terminal in the foreground right now.\n *\n * Conflating them meant \"I have never sent a size\" (`believed === null`, always true for a\n * *restored* terminal, whose PTY predates this client) was read as \"I am not allowed to send one\",\n * so a restored terminal ignored every divider drag and window resize forever.\n */\n\nexport interface Grid {\n cols: number;\n rows: number;\n}\n\n// Mirrors `@xterm/addon-fit`'s own `MINIMUM_COLS`/`MINIMUM_ROWS` (`FitAddon.ts:22-23`) — a grid\n// below this is not a real proposal, it is what `proposeDimensions()` returns while the panel is\n// still settling.\nconst MIN_COLS = 2;\nconst MIN_ROWS = 1;\n\n/** A proposal is usable only if both dimensions are finite integers ≥ the emulator minimum. */\nexport function isMeasurable(proposed: Partial<Grid> | undefined | null): proposed is Grid {\n if (proposed == null) return false;\n const { cols, rows } = proposed;\n return (\n typeof cols === \"number\" &&\n Number.isInteger(cols) &&\n cols >= MIN_COLS &&\n typeof rows === \"number\" &&\n Number.isInteger(rows) &&\n rows >= MIN_ROWS\n );\n}\n\nexport function sameGrid(a: Grid | null, b: Grid | null): boolean {\n if (a === null || b === null) return a === b;\n return a.cols === b.cols && a.rows === b.rows;\n}\n\n/**\n * Whether a measured grid is worth sending as a Resize frame, given what this client believes the\n * PTY's grid already is. Pure dedupe + validity: it answers \"would this frame change anything?\",\n * never \"am I allowed to send it?\" — permission is the caller's `isSizeAuthority` gate.\n *\n * `believed === null` (a restored terminal, whose PTY this client never sized) counts as differing:\n * an unknown remote size is exactly the case that most needs reconciling, since the PTY is\n * typically still at the 80×24 spawn default while the panel renders far wider.\n */\nexport function shouldClaimSize(next: Grid | null, believed: Grid | null): next is Grid {\n if (!isMeasurable(next)) return false;\n return !sameGrid(next, believed);\n}\n","/**\n * TerminalPanel — @xterm/xterm mount + binary-frame streaming via `TerminalStreamRouter`\n * (POC `initTerminalPanel`, POC_TO_APP_PLAN_UI.md §4.6). Strict upgrade over the POC's 800ms\n * `capture_terminal_request` poll: the daemon pushes `Output`/`Snapshot`/`Restore` binary frames\n * directly over the one shared `DaemonClient` connection, demuxed by slot.\n *\n * Slot lifecycle: created once via `create_terminal_request`, then persisted onto the tab's\n * `TerminalTabData.slot` via `useTabStore.getState().updateData` so switching away and back to\n * this tab (kept mounted-but-hidden by `TabPanelHost`) never recreates the terminal. `TabPanelHost`\n * only unmounts a tab's panel when the tab leaves the store's `tabs[]` (i.e. real tab close, never\n * a tab switch) — this component's true-unmount effect below relies on exactly that invariant to\n * send `kill_terminal_request`, terminating the PTY server-side instead of leaking it forever.\n *\n * Mount vs. subscribe are two separate effects (sprint-052/task-001): the emulator (xterm + fit +\n * `onData`/`onResize`) mounts as soon as the container exists, independent of the slot, so\n * `onResize` is attached before the first `fitAddon.fit()` ever runs — closing the window where\n * xterm's one size-changing fit of the panel's life used to fire with no listener. The stream\n * subscription is keyed on `[client, slot]` instead, so a reconnect (new `client`) re-subscribes\n * without tearing down and rebuilding the emulator, preserving scrollback across it.\n *\n * PTY sizing (`terminals.md` § PTY size ownership) is a single seam, `claimSize`, behind two\n * independent gates: `isSizeAuthority` (permission — is this panel the visible renderer, in the\n * active workspace, as its pane's active tab?) and `shouldClaimSize` (validity + dedupe against\n * `believedSizeRef`, what we think the PTY currently is). Keeping knowledge and permission separate\n * is load-bearing: a *restored* terminal's PTY predates this client, so it believes nothing, and an\n * earlier revision that treated \"never sent a size\" as \"not allowed to send one\" left every\n * restored terminal ignoring resizes for its entire life. Every claim funnels through `onResize`\n * (real grid changes) or a `performRefit` reconcile (covers a panel that measured 0×0 while hidden\n * and would otherwise fit to an unchanged grid and stay silent).\n */\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { Terminal } from \"@xterm/xterm\";\nimport { FitAddon } from \"@xterm/addon-fit\";\nimport \"@xterm/xterm/css/xterm.css\";\nimport type { DaemonClient } from \"@av-pi-studio/client\";\nimport { TerminalStreamRouter } from \"@av-pi-studio/client\";\nimport { useConnectionStore } from \"@pi-studio-ui/lib/connection/connection-store.js\";\nimport { useIsTabVisible, useTabStore } from \"@pi-studio-ui/stores/tab-store.js\";\nimport type { Tab, TerminalTabData } from \"@pi-studio-ui/stores/tab-store.js\";\nimport { isPaneActiveTab, useLayoutStore } from \"@pi-studio-ui/stores/layout-store.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { baseFontSize } from \"@pi-studio-ui/theme/tokens.js\";\nimport { isMeasurable, shouldClaimSize, type Grid } from \"./terminal-size.js\";\nimport styles from \"./TerminalPanel.module.css\";\n\nexport interface TerminalPanelProps {\n tab: Tab;\n}\n\n/** `cols`/`rows` echo the PTY's real size. Optional for the same reason as the subscribe echo\n * below: an older daemon may omit them, and a `{cols: undefined}` belief would never match a real\n * measurement, so every later fit would re-send a resize the PTY already has. */\ninterface CreateTerminalResponse {\n terminal: { slot: number; cols?: number; rows?: number };\n}\n\n/** `cols`/`rows` echo the PTY's real size; both optional so an older daemon that omits them is\n * handled without a version check (the client falls back to what it asked for). */\ninterface SubscribeTerminalResponse {\n cols?: number;\n rows?: number;\n}\n\n/** Status surface for the attach overlay (feature-panels-ui.md § Terminal pane → States). */\ninterface TerminalStatus {\n isAttaching: boolean;\n error: string | null;\n}\n\n/** Input typed before a slot exists is queued here, bounded, and flushed once the subscription\n * attaches successfully (feature-panels-ui.md § Input/keys). Cleared (not flushed) on a\n * subscribe error — a failed attach has nowhere correct to send queued bytes.\n *\n * Bounded in **bytes**, not chunks: one chunk is one `onData` payload, which for a paste is the\n * whole clipboard. A chunk-count cap would let 256 multi-megabyte pastes sit in memory. */\nconst MAX_PENDING_INPUT_BYTES = 64 * 1024;\n\nconst textEncoder = new TextEncoder();\n\n// One TerminalStreamRouter per daemon connection — multiple terminal tabs share it rather than\n// each opening its own frame demuxer over the same socket.\nconst routerByDaemon = new WeakMap<DaemonClient, TerminalStreamRouter>();\n\nfunction routerFor(daemon: DaemonClient): TerminalStreamRouter {\n let router = routerByDaemon.get(daemon);\n if (!router) {\n router = new TerminalStreamRouter(daemon);\n router.start();\n routerByDaemon.set(daemon, router);\n }\n return router;\n}\n\n/**\n * Whether this panel is the client's **size authority** for its PTY: it is on screen right now, in\n * the workspace the user is looking at, as its own pane's visible tab. Only an authority may send a\n * Resize frame (`terminals.md` § PTY size ownership — \"a passive observer never resizes what it is\n * only watching\"; a background tab or a tab in a non-active workspace is exactly that).\n *\n * Deliberately NOT gated on `focusedPaneId` (nor on real DOM focus). Pane focus is which pane\n * receives keystrokes; it is not what makes a rendered grid authoritative. Gating on it meant the\n * frame's fate depended on transient focus state at the exact moment a resize landed — a split with\n * a non-terminal tab, a workspace switch, or a restore each moved focus elsewhere while this\n * terminal was still the thing visibly rendering, so its real size went unreported and the shell\n * kept painting to a stale width (wrong grid, background color stopping short of the rendered\n * columns, mangled wrapping). Visibility is stable and is what the user is actually looking at.\n *\n * Reads live store state (`.getState()`, not a subscribed value) so a decision made synchronously\n * inside a native event handler or an rAF callback — either of which can run before React has\n * re-rendered this component — never sees a stale answer.\n */\nfunction isSizeAuthority(tabId: string): boolean {\n const tabState = useTabStore.getState();\n const tab = tabState.tabs.find((t) => t.id === tabId);\n if (!tab || tab.workspaceCwd !== tabState.activeWorkspaceCwd) return false;\n return isPaneActiveTab(useLayoutStore.getState().layouts[tab.workspaceCwd], tabId);\n}\n\n/** Dark palette matching the app's github-dark-ish default theme (theme/variants.ts \"dark\"). */\nconst TERMINAL_THEME = {\n background: \"#181b1a\",\n foreground: \"#fafafa\",\n cursor: \"#a2b4d7\",\n cursorAccent: \"#181b1a\",\n selectionBackground: \"rgba(255,255,255,0.18)\",\n black: \"#18181b\",\n red: \"#ef4444\",\n green: \"#22c55e\",\n yellow: \"#f59e0b\",\n blue: \"#3b82f6\",\n magenta: \"#a855f7\",\n cyan: \"#14b8a6\",\n white: \"#d4d4d8\",\n brightBlack: \"#52525b\",\n brightRed: \"#f87171\",\n brightGreen: \"#4ade80\",\n brightYellow: \"#fbbf24\",\n brightBlue: \"#60a5fa\",\n brightMagenta: \"#c084fc\",\n brightCyan: \"#2dd4bf\",\n brightWhite: \"#fafafa\",\n};\n\nexport function TerminalPanel({ tab }: TerminalPanelProps) {\n const data = tab.data as TerminalTabData;\n const client = useConnectionStore((s) => s.client);\n // Per-pane, not `=== activeTabId`: with splits this terminal can be on screen in one pane while\n // another pane holds the workspace-active tab, and it must refit when it appears either way.\n const isVisible = useIsTabVisible(tab.id);\n\n const containerRef = useRef<HTMLDivElement | null>(null);\n const terminalRef = useRef<Terminal | null>(null);\n const fitAddonRef = useRef<FitAddon | null>(null);\n const slotRef = useRef<number | null>(data.slot);\n // Current stream router for the slot's subscription — set by the subscription effect, read by\n // the emulator's onData/onResize handlers (which cannot close over it: they are attached once,\n // in the mount effect, and must keep working across a reconnect that swaps the router).\n const routerRef = useRef<TerminalStreamRouter | null>(null);\n const pendingInputRef = useRef<Uint8Array[]>([]);\n // Running total of `pendingInputRef`'s byte lengths, so the bound is checked without re-summing\n // the queue on every keystroke.\n const pendingInputBytesRef = useRef(0);\n // What this client believes the PTY's grid currently is — from `create_terminal_request`'s echo,\n // or from the last size it successfully sent. Used ONLY to dedupe (`shouldClaimSize`); it is\n // deliberately not a permission flag. `null` just means \"unknown\", which is the normal state of\n // a *restored* terminal whose PTY predates this client, and is precisely the case that most\n // needs a resize (that PTY is usually still at its 80×24 spawn default).\n const believedSizeRef = useRef<Grid | null>(null);\n // Set by the mount effect once `claimSize` exists, cleared on its cleanup, so the separate\n // visibility effect below can reuse the one claim path instead of duplicating its logic.\n const claimSizeRef = useRef<((next: Grid | null) => void) | null>(null);\n // Coalesced-refit scheduler state (sprint-052/task-004): `refitTimerRef` is the ~60ms trailing\n // debounce so a continuous gesture (divider drag, window resize) settles before fitting;\n // `refitRafRef` aligns the actual `fit()` to a paint frame; `isFittingRef` is the re-entrancy\n // guard so a `fit()` the scheduler performs cannot itself schedule another refit through the\n // `ResizeObserver` it may perturb. All three are refs, not effect-local state, because both the\n // emulator effect's `ResizeObserver` and the separate visibility effect below must share one\n // scheduler.\n const refitTimerRef = useRef<number | null>(null);\n const refitRafRef = useRef<number | null>(null);\n const isFittingRef = useRef(false);\n // Mirrors `use-checkout-status.ts`'s convention: kept in sync every render so the unmount-only\n // kill effect below always sends the CURRENT client, never a stale mount-time closure (e.g.\n // after a reconnect swaps in a new `PiStudioClient` instance).\n const clientRef = useRef(client);\n clientRef.current = client;\n\n const [slot, setSlot] = useState<number | null>(data.slot);\n const [status, setStatus] = useState<TerminalStatus>({ isAttaching: true, error: null });\n\n /**\n * Measure the panel's current grid and offer it to `claimSize`. The one shape every reconcile\n * point shares (post-fit, on focus, post-attach), so the measure→validate→claim sequence exists\n * once instead of three times drifting apart. Safe to call at any time: `claimSize` gates on\n * authority and dedupes, and an unmeasurable panel (hidden, 0×0) resolves to `null` and no-ops.\n */\n const measureAndClaim = () => {\n const proposed = fitAddonRef.current?.proposeDimensions();\n claimSizeRef.current?.(isMeasurable(proposed) ? proposed : null);\n };\n\n // Performs the coalesced fit, then reconciles. Not memoized — it closes over nothing but refs, so\n // a fresh function identity every render is harmless; whichever render's closure a pending\n // timer/rAF captured behaves identically to the current one.\n const performRefit = () => {\n refitRafRef.current = null;\n isFittingRef.current = true;\n fitAddonRef.current?.fit();\n // `fit()` alone is not enough to guarantee a claim. It only fires `onResize` when the grid\n // *changes*, so a panel that attached while hidden — measured 0×0, kept its constructor grid —\n // can become visible, fit to that same grid, and emit nothing, leaving the PTY at whatever it\n // was. Reconciling here covers that.\n measureAndClaim();\n // Hold the guard for one more frame: a `fit()`-induced box perturbation (if any) is reported\n // by `ResizeObserver` asynchronously, and has reliably arrived by the next frame.\n requestAnimationFrame(() => {\n isFittingRef.current = false;\n });\n };\n\n const requestRefit = () => {\n if (refitTimerRef.current !== null) window.clearTimeout(refitTimerRef.current);\n refitTimerRef.current = window.setTimeout(() => {\n refitTimerRef.current = null;\n if (refitRafRef.current !== null) return; // already scheduled this frame\n refitRafRef.current = requestAnimationFrame(performRefit);\n }, 60);\n };\n\n // ─── Emulator mount: independent of the slot ───────────────────────────────────────────────\n // Constructs xterm + FitAddon as soon as the container exists, attaches `onData`/`onResize`\n // BEFORE the first `fit()` — this is the root-cause fix (sprint-052): the one size-changing fit\n // of the panel's life used to fire before any resize listener existed, so no `Resize` frame was\n // ever sent and the PTY stayed at the 80×24 default forever. `onData`/`onResize` read the\n // current slot/router from refs (not a closure) because this effect has an empty deps array and\n // outlives every slot/client change; `claimSize` below is the size-claim logic behind\n // `sendResize` this ordering fix exists to make deliverable at all.\n useEffect(() => {\n // Captured once: the cleanup below must detach from the same element it attached to, and reading\n // the ref again at teardown would be reading it after React may have already nulled it.\n const container = containerRef.current;\n if (!container) return;\n\n const terminal = new Terminal({\n cursorBlink: true,\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace\",\n // An absolute px number, not a CSS var: xterm measures a cell from the computed style of its\n // own element and cannot resolve a var it was never given. The root font-size is left at the\n // browser default, so a rung's px value renders 1:1. (xterm 5.x renders to the DOM by\n // default — canvas/WebGL are addons this app does not load.)\n fontSize: baseFontSize.sm,\n scrollback: 5000,\n theme: TERMINAL_THEME,\n allowProposedApi: true,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.open(container);\n\n // The one and only place a `Resize` frame originates (`terminals.md` § PTY size ownership).\n // Two independent gates, which an earlier revision wrongly fused into a single \"have I claimed\n // before?\" flag: `isSizeAuthority` is *permission* (am I the visible renderer?), and\n // `shouldClaimSize` is *validity + dedupe* against what we believe the PTY already is. A\n // restored terminal believes nothing, so its first real measurement always reports — which is\n // the whole point: its PTY is still at the 80×24 spawn default.\n const claimSize = (next: Grid | null) => {\n if (!isSizeAuthority(tab.id)) return;\n const currentSlot = slotRef.current;\n const router = routerRef.current;\n if (currentSlot === null || !router) return;\n if (!shouldClaimSize(next, believedSizeRef.current)) return;\n believedSizeRef.current = next;\n router.sendResize(currentSlot, next.rows, next.cols);\n };\n\n const dataDisposable = terminal.onData((chunk) => {\n const currentSlot = slotRef.current;\n const router = routerRef.current;\n if (currentSlot === null || !router) {\n // Pre-slot keystroke: queue it (bounded) rather than dropping it silently — the\n // subscription effect flushes this once it attaches successfully.\n const bytes = textEncoder.encode(chunk);\n if (pendingInputBytesRef.current + bytes.length <= MAX_PENDING_INPUT_BYTES) {\n pendingInputRef.current.push(bytes);\n pendingInputBytesRef.current += bytes.length;\n }\n return;\n }\n router.sendInput(currentSlot, textEncoder.encode(chunk));\n });\n // Every genuine grid change funnels through here: `FitAddon.fit()` only calls\n // `terminal.resize()` when the dimensions actually change, so this fires for window resizes,\n // divider drags, splits/collapses and font changes, but not for a refit that lands on the same\n // grid. `claimSize`'s authority gate is what keeps a background/other-workspace panel silent.\n const resizeDisposable = terminal.onResize(({ cols, rows }) => {\n claimSize({ cols, rows });\n });\n // Focus is not what confers authority (see `isSizeAuthority`), but it is a good moment to\n // reconcile: a click means the user is about to type, and a mismatched PTY width is what\n // mangles the line editor. `focusin`, not `focus`, because `focus` does not bubble and xterm\n // moves real focus to its own internal textarea.\n const handleFocus = () => {\n fitAddon.fit();\n measureAndClaim();\n };\n container.addEventListener(\"focusin\", handleFocus);\n\n // First fit runs AFTER both handlers are wired — see the effect comment above.\n fitAddon.fit();\n\n terminalRef.current = terminal;\n fitAddonRef.current = fitAddon;\n claimSizeRef.current = claimSize;\n\n // Coalesced (task-004): the observer only requests a refit; `requestRefit`'s trailing debounce\n // + rAF alignment is what actually calls `fit()`, so a continuous gesture (divider drag,\n // window resize) produces one fit()+claim at rest instead of one per intermediate frame,\n // eliminating the flicker/SIGWINCH-storm a synchronous fit-per-callback used to cause. Two\n // guards on top: `isFittingRef` skips an echo from our own scheduled fit() (see\n // `performRefit`), and a zero-size entry (hidden panel) is skipped without even debouncing —\n // reading it off the entry avoids forcing an extra layout `getBoundingClientRect()` would.\n const resizeObserver = new ResizeObserver((entries) => {\n if (isFittingRef.current) return;\n const entry = entries[0];\n if (entry && (entry.contentRect.width === 0 || entry.contentRect.height === 0)) return;\n requestRefit();\n });\n resizeObserver.observe(container);\n\n return () => {\n resizeObserver.disconnect();\n if (refitTimerRef.current !== null) window.clearTimeout(refitTimerRef.current);\n if (refitRafRef.current !== null) cancelAnimationFrame(refitRafRef.current);\n container.removeEventListener(\"focusin\", handleFocus);\n dataDisposable.dispose();\n resizeDisposable.dispose();\n terminal.dispose();\n terminalRef.current = null;\n fitAddonRef.current = null;\n claimSizeRef.current = null;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // ─── Slot lifecycle: create once, persist onto the tab so re-opening reuses it ─────────────\n // React StrictMode double-invokes effects in dev: mount → cleanup → remount, synchronously,\n // on the SAME component instance (refs/state persist across all three phases — this is not\n // three separate mounts). Two things must hold across that: (1) the request fires exactly\n // once, and (2) whether to APPLY the eventual response is decided by whether the component is\n // mounted at RESPONSE time, not by a flag captured at REQUEST time.\n //\n // `requestStartedRef` gives (1): set the instant the request fires and never reset, so the\n // phantom-mount's cleanup-then-remount sees it's already in flight and never fires a second\n // `create_terminal_request` (this is what previously spawned two real PTYs from one Ctrl+T).\n //\n // `isMountedRef` gives (2): flipped true at the START of every effect invocation and false in\n // every cleanup, so it always reflects the LATEST phase. StrictMode's remount happens\n // synchronously, before the request's promise can possibly settle, so by response time\n // `isMountedRef.current` is back to `true` for a StrictMode phantom (correctly applies the\n // slot) — but stays `false` for a genuine fast real close (correctly kills the orphaned PTY\n // instead of leaking it or, as the previous buggy version did, killing a terminal that was\n // never actually torn down).\n const isMountedRef = useRef(false);\n const requestStartedRef = useRef(false);\n useEffect(() => {\n isMountedRef.current = true;\n if (!client || slotRef.current !== null || requestStartedRef.current) {\n return () => {\n isMountedRef.current = false;\n };\n }\n requestStartedRef.current = true;\n\n const cwd = data.cwd || \"~\";\n const proposed = fitAddonRef.current?.proposeDimensions();\n const grid: Grid | null = isMeasurable(proposed) ? proposed : null;\n\n void client.connection\n .request<CreateTerminalResponse>(\"create_terminal_request\", {\n workspaceId: \"\",\n cwd,\n ...(grid ? { cols: grid.cols, rows: grid.rows } : {}),\n })\n .then((res) => {\n const created = res.terminal.slot;\n if (!isMountedRef.current) {\n // A real close happened with no remount after it — kill the PTY that finished\n // spawning after the tab was already gone, instead of leaking it.\n void client.connection\n .request(\"kill_terminal_request\", { slot: created })\n .catch(() => {});\n return;\n }\n slotRef.current = created;\n setSlot(created);\n useTabStore.getState().updateData(tab.id, { slot: created });\n // Record the daemon's echo, not our request: if it clamped or defaulted, our belief must\n // match what the PTY really is or the first dedupe check would wrongly suppress a needed\n // resize. Recorded even when we couldn't measure — the echo is then the 80×24 spawn default,\n // and knowing that beats believing nothing, since the panel's first real measurement will\n // differ and correctly report. An older daemon that echoes nothing leaves the belief `null`\n // (\"unknown\"), which is handled everywhere; seeding `{cols: undefined}` would not be.\n const echoed = { cols: res.terminal.cols, rows: res.terminal.rows };\n believedSizeRef.current = isMeasurable(echoed) ? echoed : null;\n })\n .catch((err: unknown) => {\n if (!isMountedRef.current) return;\n setStatus({ isAttaching: false, error: err instanceof Error ? err.message : String(err) });\n })\n .finally(() => {\n // Reset only after the promise settles — by then StrictMode's synchronous\n // mount→cleanup→remount window has long passed, so this can never reopen the\n // double-fire race. It DOES allow a legitimate retry (e.g. `client` changed because of\n // a reconnect after the first attempt failed) instead of leaving the tab stuck forever.\n requestStartedRef.current = false;\n });\n\n return () => {\n isMountedRef.current = false;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, tab.id]);\n\n // ─── True unmount only: kill the PTY server-side ───────────────────────────────────────────\n // Runs its cleanup exactly once, when this component itself unmounts (real tab close, per\n // `TabPanelHost`'s \"hidden but alive\" model — a tab switch never unmounts). An empty deps array\n // means React never re-runs the effect body itself; only the cleanup fires, and only on\n // unmount, so this never races the slot-creation effect above or double-kills on a client\n // change. Without this, every closed terminal tab leaked its PTY process forever.\n //\n // For a REATTACH (this tab opened with a non-null `data.slot` from the very first render —\n // `use-terminal-restore.ts`, or the create-effect above once it has resolved) `slotRef.current`\n // is non-null from the start, so StrictMode's synchronous mount→cleanup→remount phantom cycle\n // would fire this cleanup and kill the PTY immediately on mount — unlike a freshly created\n // terminal, where `slotRef.current` is still `null` during that same phantom window (see the\n // create-effect's own comment) and so never hits this path. Deferred via `setTimeout`, exactly\n // like the create-effect's response handler: by the time it fires, StrictMode's remount has\n // already flipped `isMountedRef` back to `true` if this was a phantom unmount, so the kill is\n // skipped; a genuine close never remounts, so `isMountedRef` stays `false` and the kill proceeds.\n useEffect(() => {\n return () => {\n const currentSlot = slotRef.current;\n if (currentSlot === null) return;\n setTimeout(() => {\n if (isMountedRef.current) return; // StrictMode remounted synchronously — not a real close\n void clientRef.current?.connection\n .request(\"kill_terminal_request\", { slot: currentSlot })\n .catch(() => {});\n }, 0);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // ─── Stream subscription: keyed on [client, slot], independent of the emulator ─────────────\n // Split from the emulator mount so a reconnect (new `client`) re-subscribes without tearing\n // down and rebuilding xterm, which used to lose all scrollback on every reconnect.\n useEffect(() => {\n if (!client || slot === null) return;\n\n setStatus({ isAttaching: true, error: null });\n\n const router = routerFor(client.connection);\n routerRef.current = router;\n\n // `reset()`, not `clear()`: `clear()` only empties the viewport/scrollback, leaving the\n // emulator's modes (alt-screen, DECSTBM scroll margins, charset selection, wraparound/origin\n // modes, cursor visibility) carried over from whatever the previous stream left behind — a\n // snapshot replayed into stale modes renders confined to the wrong scroll region or with the\n // wrong charset (sprint-052/task-005; `terminals.md` § Restore / snapshot, tier 1). `reset()`\n // clears modes too, so the replay always lands on a clean slate. Shared by both handlers so\n // they cannot diverge — `onRestore` (tier 2, sprint-053) needs the identical treatment.\n const replay = (chunk: Uint8Array) => {\n terminalRef.current?.reset();\n terminalRef.current?.write(chunk);\n };\n const unsubscribeSlot = router.subscribeSlot(slot, {\n onOutput: (chunk) => terminalRef.current?.write(chunk),\n onSnapshot: replay,\n onRestore: replay,\n });\n\n let cancelled = false;\n // Send our measured grid WITH the subscribe request, not after it. The daemon resizes the PTY\n // before emitting the Snapshot, so a full-screen app (htop, vim) repaints at our width instead\n // of us replaying its 80-column byte stream into a much wider emulator and rendering scrambled\n // text. A client-side resize after attach is fundamentally too late: the snapshot is emitted\n // synchronously inside the daemon's subscribe, so those bytes are already on the wire.\n // Only send an authoritative measurement: a hidden panel measures 0×0 (`isMeasurable` false),\n // and it must not claim — its `performRefit` reconcile covers it once it becomes visible.\n const attachProposal = fitAddonRef.current?.proposeDimensions();\n const attachGrid: Grid | null =\n isMeasurable(attachProposal) && isSizeAuthority(tab.id) ? attachProposal : null;\n void client.connection\n .request<SubscribeTerminalResponse>(\"subscribe_terminal_request\", {\n slot,\n ...(attachGrid ? { cols: attachGrid.cols, rows: attachGrid.rows } : {}),\n })\n .then((res) => {\n if (cancelled) return;\n setStatus({ isAttaching: false, error: null });\n // Flush input queued while no slot/router existed yet (feature-panels-ui.md §\n // Input/keys: \"bounded pending queue flushed once attached + error-free\").\n const pending = pendingInputRef.current;\n pendingInputRef.current = [];\n pendingInputBytesRef.current = 0;\n for (const bytes of pending) router.sendInput(slot, bytes);\n // Seed belief from the daemon's echo of the PTY's real size — including the case where we\n // sent nothing, which is how a hidden panel learns what it is attached to instead of\n // guessing. Falls back to what we asked for if an older daemon doesn't echo, and to `null`\n // (\"unknown\") if we asked for nothing either.\n const echoed = { cols: res?.cols, rows: res?.rows };\n believedSizeRef.current = isMeasurable(echoed) ? echoed : attachGrid;\n // Reconcile anything that changed while the request was in flight (the pane could have been\n // resized, or this panel could have just become the authority). Deduped against the belief\n // just seeded, so it is a no-op in the common case.\n measureAndClaim();\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n // A failed attach has nowhere correct to send queued bytes — drop rather than flush.\n pendingInputRef.current = [];\n pendingInputBytesRef.current = 0;\n setStatus({ isAttaching: false, error: err instanceof Error ? err.message : String(err) });\n });\n\n return () => {\n cancelled = true;\n unsubscribeSlot();\n routerRef.current = null;\n void client.connection.request(\"unsubscribe_terminal_request\", { slot }).catch(() => {});\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, slot]);\n\n // ─── Re-fit whenever this tab becomes visible ─────────────────────────────────────────────\n // The `ResizeObserver` above catches divider drags and window resizes on its own (it observes\n // this panel's own box, which is what `TabPanelHost` sizes per pane); this covers the\n // hidden → visible transition, where the box was 0×0 while `display:none`. Routed through\n // `requestRefit` rather than fitting directly so it shares the same coalescing — a tab switch\n // during/adjacent to a layout gesture doesn't add a second immediate fit. No explicit claim\n // here: the refit's `fit()` fires `onResize` if the grid really changed, and that is the one\n // claim path. This is what makes a workspace switch self-correcting — the newly visible panel\n // becomes the size authority and its first non-zero measurement reports itself.\n useEffect(() => {\n if (!isVisible) return;\n requestRefit();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isVisible]);\n\n return (\n <div className={styles.wrap}>\n <div ref={containerRef} className={styles.terminal} />\n {status.error ? (\n <div className={styles.statusOverlay}>Terminal error: {status.error}</div>\n ) : status.isAttaching ? (\n <div className={styles.statusOverlay}>\n <Spinner size=\"sm\" /> Starting terminal…\n </div>\n ) : null}\n </div>\n );\n}\n"],"names":["TerminalStreamRouter","daemon","__publicField","frame","_a","slot","subscriber","data","encodeTerminalFrame","rows","cols","_b","_c","MIN_COLS","MIN_ROWS","isMeasurable","proposed","sameGrid","a","b","shouldClaimSize","next","believed","MAX_PENDING_INPUT_BYTES","textEncoder","routerByDaemon","routerFor","router","isSizeAuthority","tabId","tabState","useTabStore","tab","t","isPaneActiveTab","useLayoutStore","TERMINAL_THEME","TerminalPanel","client","useConnectionStore","s","isVisible","useIsTabVisible","containerRef","useRef","terminalRef","fitAddonRef","slotRef","routerRef","pendingInputRef","pendingInputBytesRef","believedSizeRef","claimSizeRef","refitTimerRef","refitRafRef","isFittingRef","clientRef","setSlot","useState","status","setStatus","measureAndClaim","performRefit","requestRefit","useEffect","container","terminal","Terminal","baseFontSize","fitAddon","FitAddon","claimSize","currentSlot","dataDisposable","chunk","bytes","resizeDisposable","handleFocus","resizeObserver","entries","entry","isMountedRef","requestStartedRef","cwd","grid","res","created","echoed","err","replay","unsubscribeSlot","cancelled","attachProposal","attachGrid","pending","jsxs","styles","jsx","Spinner"],"mappings":"umBAuBO,MAAMA,EAAqB,CAIhC,YAA6BC,EAAsB,CAHlCC,EAAA,uBAAkB,KAC3BA,EAAA,cAA8B,MAET,KAAA,OAAAD,CAAuB,CAGpD,OAAc,CACR,KAAK,SACT,KAAK,OAAS,KAAK,OAAO,gBAAiBE,GAAU,KAAK,SAASA,CAAK,CAAC,EAC3E,CAGA,MAAa,QACXC,EAAA,KAAK,SAAL,MAAAA,EAAA,WACA,KAAK,OAAS,IAChB,CAGA,cAAcC,EAAcC,EAAgD,CAC1E,YAAK,YAAY,IAAID,EAAMC,CAAU,EAC9B,IAAM,CACP,KAAK,YAAY,IAAID,CAAI,IAAMC,GAAY,KAAK,YAAY,OAAOD,CAAI,CAC7E,CACF,CAGA,QAAQA,EAAuB,CAC7B,OAAO,KAAK,YAAY,IAAIA,CAAI,CAClC,CAKA,UAAUA,EAAcE,EAAwB,CAC9C,KAAK,OAAO,WAAWC,EAAoB,CAAE,OAAQ,QAAS,KAAAH,EAAM,KAAAE,CAAA,CAAM,CAAC,CAC7E,CAGA,WAAWF,EAAcI,EAAcC,EAAoB,CACzD,KAAK,OAAO,WAAWF,EAAoB,CAAE,OAAQ,SAAU,KAAAH,EAAM,KAAAI,EAAM,KAAAC,CAAA,CAAM,CAAC,CACpF,CAIQ,SAASP,EAA4B,WAC3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