@av-pi-studio/web-client 0.0.73 → 0.0.74

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 (32) hide show
  1. package/dist/web/assets/{BinaryFallbackViewer-C7jh_fjO.js → BinaryFallbackViewer-B1PBcT3N.js} +2 -2
  2. package/dist/web/assets/{BinaryFallbackViewer-C7jh_fjO.js.map → BinaryFallbackViewer-B1PBcT3N.js.map} +1 -1
  3. package/dist/web/assets/{ChatPanel-DlHBIYiO.js → ChatPanel-DuiC5ipg.js} +2 -2
  4. package/dist/web/assets/{ChatPanel-DlHBIYiO.js.map → ChatPanel-DuiC5ipg.js.map} +1 -1
  5. package/dist/web/assets/{CodeView-DejUdSHl.js → CodeView-_wBYU-zK.js} +2 -2
  6. package/dist/web/assets/{CodeView-DejUdSHl.js.map → CodeView-_wBYU-zK.js.map} +1 -1
  7. package/dist/web/assets/{FilePanel-DtAGc7Lw.js → FilePanel-CqiLosrb.js} +2 -2
  8. package/dist/web/assets/{FilePanel-DtAGc7Lw.js.map → FilePanel-CqiLosrb.js.map} +1 -1
  9. package/dist/web/assets/{ImageViewer-YLGH2uig.js → ImageViewer-WToUsK2Y.js} +2 -2
  10. package/dist/web/assets/{ImageViewer-YLGH2uig.js.map → ImageViewer-WToUsK2Y.js.map} +1 -1
  11. package/dist/web/assets/{MarkdownFileViewer-C_4HZa34.js → MarkdownFileViewer-Do69vE6s.js} +2 -2
  12. package/dist/web/assets/{MarkdownFileViewer-C_4HZa34.js.map → MarkdownFileViewer-Do69vE6s.js.map} +1 -1
  13. package/dist/web/assets/{MoleculeViewerPanel-CNaBH6ND.js → MoleculeViewerPanel-CKaIka-k.js} +2 -2
  14. package/dist/web/assets/{MoleculeViewerPanel-CNaBH6ND.js.map → MoleculeViewerPanel-CKaIka-k.js.map} +1 -1
  15. package/dist/web/assets/{TerminalPanel-aflKubq7.js → TerminalPanel-B7ujFxCG.js} +2 -2
  16. package/dist/web/assets/{TerminalPanel-aflKubq7.js.map → TerminalPanel-B7ujFxCG.js.map} +1 -1
  17. package/dist/web/assets/{TextViewer-DBXXTsTN.js → TextViewer-CJGwYjCh.js} +2 -2
  18. package/dist/web/assets/{TextViewer-DBXXTsTN.js.map → TextViewer-CJGwYjCh.js.map} +1 -1
  19. package/dist/web/assets/{VideoViewer-XGCQzxEz.js → VideoViewer-CYXPkYLV.js} +2 -2
  20. package/dist/web/assets/{VideoViewer-XGCQzxEz.js.map → VideoViewer-CYXPkYLV.js.map} +1 -1
  21. package/dist/web/assets/index-Cz7AgOgN.js +18 -0
  22. package/dist/web/assets/index-Cz7AgOgN.js.map +1 -0
  23. package/dist/web/assets/{markdown-DGGFhmLR.js → markdown-q0cxuHgm.js} +2 -2
  24. package/dist/web/assets/{markdown-DGGFhmLR.js.map → markdown-q0cxuHgm.js.map} +1 -1
  25. package/dist/web/assets/{use-file-download-RWF-ZBv9.js → use-file-download-BCG_kqpD.js} +2 -2
  26. package/dist/web/assets/{use-file-download-RWF-ZBv9.js.map → use-file-download-BCG_kqpD.js.map} +1 -1
  27. package/dist/web/assets/{use-file-watch-B-wXmE8p.js → use-file-watch-CZgwolg7.js} +2 -2
  28. package/dist/web/assets/{use-file-watch-B-wXmE8p.js.map → use-file-watch-CZgwolg7.js.map} +1 -1
  29. package/dist/web/index.html +1 -1
  30. package/package.json +3 -3
  31. package/dist/web/assets/index-CVbpa3Qk.js +0 -18
  32. package/dist/web/assets/index-CVbpa3Qk.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"TerminalPanel-aflKubq7.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 (`swe/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,CAC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AAUtB,EAAMsE,CAAK,EAKzD,MAAMY,EAAS,CAAE,KAAMF,GAAA,YAAAA,EAAK,KAAM,KAAMA,GAAA,YAAAA,EAAK,IAAA,EAC7ClC,EAAgB,QAAUpC,EAAawE,CAAM,EAAIA,EAASM,EAI1DhC,EAAA,CACF,CAAC,EACA,MAAO2B,GAAiB,CACnBG,IAEJ1C,EAAgB,QAAU,CAAA,EAC1BC,EAAqB,QAAU,EAC/BU,EAAU,CAAE,YAAa,GAAO,MAAO4B,aAAe,MAAQA,EAAI,QAAU,OAAOA,CAAG,CAAA,CAAG,EAC3F,CAAC,EAEI,IAAM,CACXG,EAAY,GACZD,EAAA,EACA1C,EAAU,QAAU,KACfV,EAAO,WAAW,QAAQ,+BAAgC,CAAE,KAAAjC,CAAA,CAAM,EAAE,MAAM,IAAM,CAAC,CAAC,CACzF,CAEF,EAAG,CAACiC,EAAQjC,CAAI,CAAC,EAWjB2D,EAAAA,UAAU,IAAM,CACTvB,GACLsB,EAAA,CAEF,EAAG,CAACtB,CAAS,CAAC,EAGZsD,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,KACrB,SAAA,CAAAC,EAAAA,IAAC,MAAA,CAAI,IAAKtD,EAAc,UAAWqD,EAAO,SAAU,EACnDrC,EAAO,MACNoC,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAO,cAAe,SAAA,CAAA,mBAAiBrC,EAAO,KAAA,EAAM,EAClEA,EAAO,mBACR,MAAA,CAAI,UAAWqC,EAAO,cACrB,SAAA,CAAAC,EAAAA,IAACC,GAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,qBAAA,CAAA,CACvB,EACE,IAAA,EACN,CAEJ"}
1
+ {"version":3,"file":"TerminalPanel-B7ujFxCG.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 (`swe/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,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-CVbpa3Qk.js";import{u as S,F as _,C as y}from"./CodeView-DejUdSHl.js";import{u as U}from"./vendor-query-NxjRJKdp.js";import{u as p}from"./use-file-download-RWF-ZBv9.js";import"./vendor-BLc7PaxD.js";import"./vendor-markdown-DtEbK_xy.js";import"./vendor-highlight-CJuJYF7f.js";import"./vendor-icons-DDiHMdgo.js";import"./vendor-overlays-Ki1AFMsh.js";import"./vendor-dnd-Bvh3agTi.js";function B(n){const{enabled:s,download:e,decode:o}=n;return{isLoading:s&&(e.isLoading||e.hasObjectUrl&&o.isLoading),isError:e.isError||o.isError,error:e.isError?e.error:o.error,data:o.data}}function F(n,s=!0){var a;const e=p(n,s),o=(a=e.data)==null?void 0:a.objectUrl,t=U({queryKey:k.fileText(n,o??null),queryFn:async()=>({content:await(await fetch(o)).text()}),enabled:s&&!!o});return B({enabled:s,download:{isLoading:e.isLoading,isError:e.isError,error:e.error,hasObjectUrl:!!o},decode:{isLoading:t.isLoading,isError:t.isError,error:t.error,data:t.data}})}function N(n){const{maxDisplayBytes:s,inline:e,streamed:o,download:t}=n;if(e.isLoading)return{kind:"loading"};if(e.tooLarge){const{size:a}=e.tooLarge;return a>s?{kind:"too-large",size:a,maxDisplayBytes:s,downloading:t.requested&&t.isLoading,downloadUrl:t.objectUrl,downloadName:t.fileName}:o.isLoading?{kind:"streaming",size:a}:o.isError?{kind:"stream-error",size:a,message:o.errorMessage??"stream failed"}:o.content!==null?{kind:"streamed",size:a,content:o.content}:{kind:"loading"}}return e.isError?{kind:"error",message:e.errorMessage??"unknown error"}:e.content!==null?{kind:"inline",content:e.content}:{kind:"loading"}}const D="_note_1g5yz_1",M="_body_1g5yz_9",T="_tooLarge_1g5yz_13",m={note:D,body:M,tooLarge:T},E=30*1024*1024;function l(n){return`${(n/(1024*1024)).toFixed(1)} MB`}function Q({path:n}){var f,x,j,L;const s=S(n),e=s.error instanceof _?s.error:null,o=e!==null&&e.size<=E,t=F(n,o),[a,g]=b.useState(!1),c=p(n,a),i=N({maxDisplayBytes:E,inline:{isLoading:s.isLoading,isError:s.isError,tooLarge:e?{size:e.size}:null,errorMessage:s.error instanceof Error?s.error.message:null,content:((f=s.data)==null?void 0:f.content)??null},streamed:{isLoading:t.isLoading,isError:t.isError,errorMessage:t.error instanceof Error?t.error.message:null,content:((x=t.data)==null?void 0:x.content)??null},download:{requested:a,isLoading:c.isLoading,objectUrl:((j=c.data)==null?void 0:j.objectUrl)??null,fileName:((L=c.data)==null?void 0:L.fileName)??null}});switch(i.kind){case"loading":return r.jsxs(d,{children:[r.jsx(u,{size:"sm"})," Loading..."]});case"inline":return r.jsx(y,{path:n,content:i.content});case"streaming":return r.jsxs(d,{children:[r.jsx(u,{size:"sm"})," Streaming ",l(i.size)," file..."]});case"stream-error":return r.jsxs(d,{children:["Error: ",i.message]});case"streamed":return r.jsxs(h,{children:[r.jsxs("div",{className:m.note,children:[l(i.size)," file streamed"]}),r.jsx("div",{className:m.body,children:r.jsx(y,{path:n,content:i.content})})]});case"too-large":{const z=n.split("/").pop()||n;return r.jsx(d,{children:r.jsxs("div",{className:m.tooLarge,children:[r.jsxs("div",{children:[l(i.size)," — too large to display (display ceiling is"," ",l(i.maxDisplayBytes),")."]}),i.downloading?r.jsx(u,{size:"sm"}):i.downloadUrl?r.jsx("a",{href:i.downloadUrl,download:i.downloadName||z,children:r.jsx(w,{size:"sm",children:"Save file"})}):r.jsx(w,{size:"sm",onClick:()=>g(!0),children:"Download"})]})})}case"error":return r.jsxs(d,{children:["Error: ",i.message]})}}export{E as MAX_DISPLAY_BYTES,Q as TextViewer};
2
- //# sourceMappingURL=TextViewer-DBXXTsTN.js.map
1
+ import{r as b,j as r}from"./vendor-react-Uv3j2inr.js";import{r as k,E as d,S as u,B as w,P as h}from"./index-Cz7AgOgN.js";import{u as S,F as _,C as y}from"./CodeView-_wBYU-zK.js";import{u as U}from"./vendor-query-NxjRJKdp.js";import{u as p}from"./use-file-download-BCG_kqpD.js";import"./vendor-BLc7PaxD.js";import"./vendor-markdown-DtEbK_xy.js";import"./vendor-highlight-CJuJYF7f.js";import"./vendor-icons-DDiHMdgo.js";import"./vendor-overlays-Ki1AFMsh.js";import"./vendor-dnd-Bvh3agTi.js";function B(n){const{enabled:s,download:e,decode:o}=n;return{isLoading:s&&(e.isLoading||e.hasObjectUrl&&o.isLoading),isError:e.isError||o.isError,error:e.isError?e.error:o.error,data:o.data}}function F(n,s=!0){var a;const e=p(n,s),o=(a=e.data)==null?void 0:a.objectUrl,t=U({queryKey:k.fileText(n,o??null),queryFn:async()=>({content:await(await fetch(o)).text()}),enabled:s&&!!o});return B({enabled:s,download:{isLoading:e.isLoading,isError:e.isError,error:e.error,hasObjectUrl:!!o},decode:{isLoading:t.isLoading,isError:t.isError,error:t.error,data:t.data}})}function N(n){const{maxDisplayBytes:s,inline:e,streamed:o,download:t}=n;if(e.isLoading)return{kind:"loading"};if(e.tooLarge){const{size:a}=e.tooLarge;return a>s?{kind:"too-large",size:a,maxDisplayBytes:s,downloading:t.requested&&t.isLoading,downloadUrl:t.objectUrl,downloadName:t.fileName}:o.isLoading?{kind:"streaming",size:a}:o.isError?{kind:"stream-error",size:a,message:o.errorMessage??"stream failed"}:o.content!==null?{kind:"streamed",size:a,content:o.content}:{kind:"loading"}}return e.isError?{kind:"error",message:e.errorMessage??"unknown error"}:e.content!==null?{kind:"inline",content:e.content}:{kind:"loading"}}const D="_note_1g5yz_1",M="_body_1g5yz_9",T="_tooLarge_1g5yz_13",m={note:D,body:M,tooLarge:T},E=30*1024*1024;function l(n){return`${(n/(1024*1024)).toFixed(1)} MB`}function Q({path:n}){var f,x,j,L;const s=S(n),e=s.error instanceof _?s.error:null,o=e!==null&&e.size<=E,t=F(n,o),[a,g]=b.useState(!1),c=p(n,a),i=N({maxDisplayBytes:E,inline:{isLoading:s.isLoading,isError:s.isError,tooLarge:e?{size:e.size}:null,errorMessage:s.error instanceof Error?s.error.message:null,content:((f=s.data)==null?void 0:f.content)??null},streamed:{isLoading:t.isLoading,isError:t.isError,errorMessage:t.error instanceof Error?t.error.message:null,content:((x=t.data)==null?void 0:x.content)??null},download:{requested:a,isLoading:c.isLoading,objectUrl:((j=c.data)==null?void 0:j.objectUrl)??null,fileName:((L=c.data)==null?void 0:L.fileName)??null}});switch(i.kind){case"loading":return r.jsxs(d,{children:[r.jsx(u,{size:"sm"})," Loading..."]});case"inline":return r.jsx(y,{path:n,content:i.content});case"streaming":return r.jsxs(d,{children:[r.jsx(u,{size:"sm"})," Streaming ",l(i.size)," file..."]});case"stream-error":return r.jsxs(d,{children:["Error: ",i.message]});case"streamed":return r.jsxs(h,{children:[r.jsxs("div",{className:m.note,children:[l(i.size)," file streamed"]}),r.jsx("div",{className:m.body,children:r.jsx(y,{path:n,content:i.content})})]});case"too-large":{const z=n.split("/").pop()||n;return r.jsx(d,{children:r.jsxs("div",{className:m.tooLarge,children:[r.jsxs("div",{children:[l(i.size)," — too large to display (display ceiling is"," ",l(i.maxDisplayBytes),")."]}),i.downloading?r.jsx(u,{size:"sm"}):i.downloadUrl?r.jsx("a",{href:i.downloadUrl,download:i.downloadName||z,children:r.jsx(w,{size:"sm",children:"Save file"})}):r.jsx(w,{size:"sm",onClick:()=>g(!0),children:"Download"})]})})}case"error":return r.jsxs(d,{children:["Error: ",i.message]})}}export{E as MAX_DISPLAY_BYTES,Q as TextViewer};
2
+ //# sourceMappingURL=TextViewer-CJGwYjCh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"TextViewer-DBXXTsTN.js","sources":["../../../src/hooks/file-text-state.ts","../../../src/hooks/use-file-text.ts","../../../src/features/files/text-viewer-state.ts","../../../src/features/files/TextViewer.tsx"],"sourcesContent":["/**\n * Pure query-state merge for `use-file-text` (task-009), kept DOM/React-free so the\n * loading/error/data composition across the two dependent queries it wraps (download → decode)\n * is unit-testable directly, without `renderHook` (no jsdom test environment in this repo).\n */\n\nexport interface FileTextResult {\n content: string;\n}\n\nexport interface FileTextMergeInputs {\n enabled: boolean;\n download: { isLoading: boolean; isError: boolean; error: unknown; hasObjectUrl: boolean };\n decode: {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n };\n}\n\nexport interface FileTextQueryState {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n}\n\nexport function mergeFileTextState(input: FileTextMergeInputs): FileTextQueryState {\n const { enabled, download, decode } = input;\n return {\n isLoading: enabled && (download.isLoading || (download.hasObjectUrl && decode.isLoading)),\n isError: download.isError || decode.isError,\n error: download.isError ? download.error : decode.error,\n data: decode.data,\n };\n}\n","/**\n * `use-file-text` — tier-2 fallback for `TextViewer` (task-009): decodes a file's bytes to UTF-8\n * text via the already-uncapped chunked binary download path (`useFileDownload` →\n * `file_download_token_request`/`file_download_request`), for files over `file_read_request`'s\n * inline cap (`MAX_INLINE_FILE_READ_BYTES`, `packages/server/src/files/limits.ts`). Same\n * transport the molecule viewer uses for its own (binary-safe) source — no new RPC, no new\n * transport, just a text decode over the resulting blob.\n *\n * Note the daemon asymmetry documented on `useFileDownload`'s own RPCs: the download path is\n * registered only in the production bootstrap (`bootstrap.ts`), not `dev-bootstrap.ts`. Under\n * `npm run dev:daemon` a file above the inline cap fails this fetch rather than rendering — that\n * surfaces as the normal error state below, which is the intended behavior (see task-009 notes).\n *\n * The loading/error/data merge across the two dependent queries (download → decode) is the pure,\n * DOM-free `mergeFileTextState` (`file-text-state.ts`) — this hook is a thin wrapper feeding it\n * live query state.\n */\n\nimport { useQuery } from \"@tanstack/react-query\";\nimport { rpcKeys } from \"@pi-studio-ui/lib/connection/rpc-keys.js\";\nimport { useFileDownload } from \"./use-file-download.js\";\nimport { mergeFileTextState, type FileTextResult } from \"./file-text-state.js\";\n\nexport type { FileTextResult };\n\nexport function useFileText(path: string, enabled = true) {\n const download = useFileDownload(path, enabled);\n const objectUrl = download.data?.objectUrl;\n\n const decode = useQuery({\n queryKey: rpcKeys.fileText(path, objectUrl ?? null),\n queryFn: async (): Promise<FileTextResult> => {\n const content = await (await fetch(objectUrl as string)).text();\n return { content };\n },\n enabled: enabled && Boolean(objectUrl),\n });\n\n return mergeFileTextState({\n enabled,\n download: {\n isLoading: download.isLoading,\n isError: download.isError,\n error: download.error,\n hasObjectUrl: Boolean(objectUrl),\n },\n decode: {\n isLoading: decode.isLoading,\n isError: decode.isError,\n error: decode.error,\n data: decode.data,\n },\n });\n}\n","/**\n * Pure tier-selection logic for `TextViewer` (task-009), kept in its own DOM-free module so the\n * three-state branch (inline / streamed / download-only) is unit-testable without mounting\n * CodeMirror or React — mirrors `molecule-reload.ts`'s `shouldApplyRefresh` extraction for the\n * same reason: this repo has no jsdom test environment configured anywhere.\n */\n\nexport type TextViewerState =\n | { kind: \"loading\" }\n | { kind: \"inline\"; content: string }\n | { kind: \"streaming\"; size: number }\n | { kind: \"streamed\"; size: number; content: string }\n | { kind: \"stream-error\"; size: number; message: string }\n | {\n kind: \"too-large\";\n size: number;\n maxDisplayBytes: number;\n downloading: boolean;\n downloadUrl: string | null;\n downloadName: string | null;\n }\n | { kind: \"error\"; message: string };\n\nexport interface TextViewerInputs {\n maxDisplayBytes: number;\n inline: {\n isLoading: boolean;\n isError: boolean;\n /** `{ size }` when the failure was specifically `FileTooLargeError`; `null` for a generic\n * read failure (network/permission/etc). */\n tooLarge: { size: number } | null;\n errorMessage: string | null;\n content: string | null;\n };\n streamed: {\n isLoading: boolean;\n isError: boolean;\n errorMessage: string | null;\n content: string | null;\n };\n download: {\n requested: boolean;\n isLoading: boolean;\n objectUrl: string | null;\n fileName: string | null;\n };\n}\n\n/** Selects exactly one `TextViewerState` from the current query states. Pure — no hooks, no I/O. */\nexport function selectTextViewerState(input: TextViewerInputs): TextViewerState {\n const { maxDisplayBytes, inline, streamed, download } = input;\n\n if (inline.isLoading) return { kind: \"loading\" };\n\n if (inline.tooLarge) {\n const { size } = inline.tooLarge;\n if (size > maxDisplayBytes) {\n return {\n kind: \"too-large\",\n size,\n maxDisplayBytes,\n downloading: download.requested && download.isLoading,\n downloadUrl: download.objectUrl,\n downloadName: download.fileName,\n };\n }\n if (streamed.isLoading) return { kind: \"streaming\", size };\n if (streamed.isError) {\n return { kind: \"stream-error\", size, message: streamed.errorMessage ?? \"stream failed\" };\n }\n if (streamed.content !== null) return { kind: \"streamed\", size, content: streamed.content };\n return { kind: \"loading\" };\n }\n\n if (inline.isError) {\n return { kind: \"error\", message: inline.errorMessage ?? \"unknown error\" };\n }\n\n if (inline.content !== null) return { kind: \"inline\", content: inline.content };\n return { kind: \"loading\" };\n}\n","/**\n * TextViewer — the default viewer for source/text files: fetches the UTF-8 preview via\n * `useFileRead` and renders it through `CodeView` (line gutter + Shiki highlighting). Registered\n * in `viewer-registry.ts` as the fallback for any file not claimed by a more specific viewer.\n *\n * Three size tiers (task-009 — raising `file_read_request`'s old 512 KiB ceiling):\n * 1. `size <= MAX_INLINE_FILE_READ_BYTES` (server-side, 5 MiB) — the `useFileRead` JSON round\n * trip above, unchanged.\n * 2. `MAX_INLINE_FILE_READ_BYTES < size <= MAX_DISPLAY_BYTES` (30 MiB) — transparently refetch via\n * the uncapped chunked binary download path (`use-file-text.ts`) and render the same\n * `CodeView`, with a muted note that the file was streamed rather than read inline.\n * 3. `size > MAX_DISPLAY_BYTES` — a terminal state: no render attempt, just the size, why, and a\n * download action (`BinaryFallbackViewer`'s existing on-demand download pattern).\n *\n * Which tier applies is the pure, DOM-free `selectTextViewerState` (`text-viewer-state.ts`) — this\n * component is a thin switch-render over it.\n */\n\nimport { useState } from \"react\";\nimport { Button } from \"@pi-studio-ui/components/primitives/Button.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { Panel } from \"@pi-studio-ui/components/primitives/Panel.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.js\";\nimport { useFileRead, FileTooLargeError } from \"@pi-studio-ui/hooks/use-file-read.js\";\nimport { useFileText } from \"@pi-studio-ui/hooks/use-file-text.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport { CodeView } from \"./CodeView.js\";\nimport { selectTextViewerState } from \"./text-viewer-state.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport textStyles from \"./TextViewer.module.css\";\n\n/** Display ceiling above the inline cap. `CodeView`'s CodeMirror instance enables\n * `EditorView.lineWrapping`, which makes it measure line heights across the whole document —\n * well past interactive above this size, so files this large get a terminal download-only state\n * instead of an attempted render. Deliberately not configurable (task-009 notes). */\nexport const MAX_DISPLAY_BYTES = 30 * 1024 * 1024;\n\nfunction formatMegabytes(bytes: number): string {\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function TextViewer({ path }: ViewerProps) {\n const inline = useFileRead(path);\n const tooLarge = inline.error instanceof FileTooLargeError ? inline.error : null;\n const displayable = tooLarge !== null && tooLarge.size <= MAX_DISPLAY_BYTES;\n\n const streamed = useFileText(path, displayable);\n const [downloadRequested, setDownloadRequested] = useState(false);\n const download = useFileDownload(path, downloadRequested);\n\n const state = selectTextViewerState({\n maxDisplayBytes: MAX_DISPLAY_BYTES,\n inline: {\n isLoading: inline.isLoading,\n isError: inline.isError,\n tooLarge: tooLarge ? { size: tooLarge.size } : null,\n errorMessage: inline.error instanceof Error ? inline.error.message : null,\n content: inline.data?.content ?? null,\n },\n streamed: {\n isLoading: streamed.isLoading,\n isError: streamed.isError,\n errorMessage: streamed.error instanceof Error ? streamed.error.message : null,\n content: streamed.data?.content ?? null,\n },\n download: {\n requested: downloadRequested,\n isLoading: download.isLoading,\n objectUrl: download.data?.objectUrl ?? null,\n fileName: download.data?.fileName ?? null,\n },\n });\n\n switch (state.kind) {\n case \"loading\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Loading...\n </EmptyState>\n );\n case \"inline\":\n return <CodeView path={path} content={state.content} />;\n case \"streaming\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Streaming {formatMegabytes(state.size)} file...\n </EmptyState>\n );\n case \"stream-error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n case \"streamed\":\n return (\n <Panel>\n <div className={textStyles.note}>{formatMegabytes(state.size)} file streamed</div>\n <div className={textStyles.body}>\n <CodeView path={path} content={state.content} />\n </div>\n </Panel>\n );\n case \"too-large\": {\n const name = path.split(\"/\").pop() || path;\n return (\n <EmptyState>\n <div className={textStyles.tooLarge}>\n <div>\n {formatMegabytes(state.size)} — too large to display (display ceiling is{\" \"}\n {formatMegabytes(state.maxDisplayBytes)}).\n </div>\n {state.downloading ? (\n <Spinner size=\"sm\" />\n ) : state.downloadUrl ? (\n <a href={state.downloadUrl} download={state.downloadName || name}>\n <Button size=\"sm\">Save file</Button>\n </a>\n ) : (\n <Button size=\"sm\" onClick={() => setDownloadRequested(true)}>\n Download\n </Button>\n )}\n </div>\n </EmptyState>\n );\n }\n case \"error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n }\n}\n"],"names":["mergeFileTextState","input","enabled","download","decode","useFileText","path","useFileDownload","objectUrl","_a","useQuery","rpcKeys","selectTextViewerState","maxDisplayBytes","inline","streamed","size","MAX_DISPLAY_BYTES","formatMegabytes","bytes","TextViewer","useFileRead","tooLarge","FileTooLargeError","displayable","downloadRequested","setDownloadRequested","useState","state","_b","_c","_d","EmptyState","jsx","Spinner","CodeView","Panel","jsxs","textStyles","name","Button"],"mappings":"0eA4BO,SAASA,EAAmBC,EAAgD,CACjF,KAAM,CAAE,QAAAC,EAAS,SAAAC,EAAU,OAAAC,CAAA,EAAWH,EACtC,MAAO,CACL,UAAWC,IAAYC,EAAS,WAAcA,EAAS,cAAgBC,EAAO,WAC9E,QAASD,EAAS,SAAWC,EAAO,QACpC,MAAOD,EAAS,QAAUA,EAAS,MAAQC,EAAO,MAClD,KAAMA,EAAO,IAAA,CAEjB,CCXO,SAASC,EAAYC,EAAcJ,EAAU,GAAM,OACxD,MAAMC,EAAWI,EAAgBD,EAAMJ,CAAO,EACxCM,GAAYC,EAAAN,EAAS,OAAT,YAAAM,EAAe,UAE3BL,EAASM,EAAS,CACtB,SAAUC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AAI,EAAE,UAAA,EAC/D,EAEJ,IAAK,eACH,cAAQI,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,EAC3C,IAAK,WACH,cACGQ,EAAA,CACC,SAAA,CAAAC,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,KAAO,SAAA,CAAApB,EAAgBU,EAAM,IAAI,EAAE,gBAAA,EAAc,EAC5EK,EAAAA,IAAC,MAAA,CAAI,UAAWK,EAAW,KACzB,SAAAL,EAAAA,IAACE,EAAA,CAAS,KAAA7B,EAAY,QAASsB,EAAM,OAAA,CAAS,CAAA,CAChD,CAAA,EACF,EAEJ,IAAK,YAAa,CAChB,MAAMW,EAAOjC,EAAK,MAAM,GAAG,EAAE,OAASA,EACtC,aACG0B,EAAA,CACC,SAAAK,EAAAA,KAAC,MAAA,CAAI,UAAWC,EAAW,SACzB,SAAA,CAAAD,OAAC,MAAA,CACE,SAAA,CAAAnB,EAAgBU,EAAM,IAAI,EAAE,8CAA4C,IACxEV,EAAgBU,EAAM,eAAe,EAAE,IAAA,EAC1C,EACCA,EAAM,YACLK,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EACjBN,EAAM,kBACP,IAAA,CAAE,KAAMA,EAAM,YAAa,SAAUA,EAAM,cAAgBW,EAC1D,SAAAN,MAACO,EAAA,CAAO,KAAK,KAAK,SAAA,WAAA,CAAS,EAC7B,EAEAP,EAAAA,IAACO,EAAA,CAAO,KAAK,KAAK,QAAS,IAAMd,EAAqB,EAAI,EAAG,SAAA,UAAA,CAE7D,CAAA,CAAA,CAEJ,CAAA,CACF,CAEJ,CACA,IAAK,QACH,cAAQM,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,CAAA,CAE/C"}
1
+ {"version":3,"file":"TextViewer-CJGwYjCh.js","sources":["../../../src/hooks/file-text-state.ts","../../../src/hooks/use-file-text.ts","../../../src/features/files/text-viewer-state.ts","../../../src/features/files/TextViewer.tsx"],"sourcesContent":["/**\n * Pure query-state merge for `use-file-text` (task-009), kept DOM/React-free so the\n * loading/error/data composition across the two dependent queries it wraps (download → decode)\n * is unit-testable directly, without `renderHook` (no jsdom test environment in this repo).\n */\n\nexport interface FileTextResult {\n content: string;\n}\n\nexport interface FileTextMergeInputs {\n enabled: boolean;\n download: { isLoading: boolean; isError: boolean; error: unknown; hasObjectUrl: boolean };\n decode: {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n };\n}\n\nexport interface FileTextQueryState {\n isLoading: boolean;\n isError: boolean;\n error: unknown;\n data: FileTextResult | undefined;\n}\n\nexport function mergeFileTextState(input: FileTextMergeInputs): FileTextQueryState {\n const { enabled, download, decode } = input;\n return {\n isLoading: enabled && (download.isLoading || (download.hasObjectUrl && decode.isLoading)),\n isError: download.isError || decode.isError,\n error: download.isError ? download.error : decode.error,\n data: decode.data,\n };\n}\n","/**\n * `use-file-text` — tier-2 fallback for `TextViewer` (task-009): decodes a file's bytes to UTF-8\n * text via the already-uncapped chunked binary download path (`useFileDownload` →\n * `file_download_token_request`/`file_download_request`), for files over `file_read_request`'s\n * inline cap (`MAX_INLINE_FILE_READ_BYTES`, `packages/server/src/files/limits.ts`). Same\n * transport the molecule viewer uses for its own (binary-safe) source — no new RPC, no new\n * transport, just a text decode over the resulting blob.\n *\n * Note the daemon asymmetry documented on `useFileDownload`'s own RPCs: the download path is\n * registered only in the production bootstrap (`bootstrap.ts`), not `dev-bootstrap.ts`. Under\n * `npm run dev:daemon` a file above the inline cap fails this fetch rather than rendering — that\n * surfaces as the normal error state below, which is the intended behavior (see task-009 notes).\n *\n * The loading/error/data merge across the two dependent queries (download → decode) is the pure,\n * DOM-free `mergeFileTextState` (`file-text-state.ts`) — this hook is a thin wrapper feeding it\n * live query state.\n */\n\nimport { useQuery } from \"@tanstack/react-query\";\nimport { rpcKeys } from \"@pi-studio-ui/lib/connection/rpc-keys.js\";\nimport { useFileDownload } from \"./use-file-download.js\";\nimport { mergeFileTextState, type FileTextResult } from \"./file-text-state.js\";\n\nexport type { FileTextResult };\n\nexport function useFileText(path: string, enabled = true) {\n const download = useFileDownload(path, enabled);\n const objectUrl = download.data?.objectUrl;\n\n const decode = useQuery({\n queryKey: rpcKeys.fileText(path, objectUrl ?? null),\n queryFn: async (): Promise<FileTextResult> => {\n const content = await (await fetch(objectUrl as string)).text();\n return { content };\n },\n enabled: enabled && Boolean(objectUrl),\n });\n\n return mergeFileTextState({\n enabled,\n download: {\n isLoading: download.isLoading,\n isError: download.isError,\n error: download.error,\n hasObjectUrl: Boolean(objectUrl),\n },\n decode: {\n isLoading: decode.isLoading,\n isError: decode.isError,\n error: decode.error,\n data: decode.data,\n },\n });\n}\n","/**\n * Pure tier-selection logic for `TextViewer` (task-009), kept in its own DOM-free module so the\n * three-state branch (inline / streamed / download-only) is unit-testable without mounting\n * CodeMirror or React — mirrors `molecule-reload.ts`'s `shouldApplyRefresh` extraction for the\n * same reason: this repo has no jsdom test environment configured anywhere.\n */\n\nexport type TextViewerState =\n | { kind: \"loading\" }\n | { kind: \"inline\"; content: string }\n | { kind: \"streaming\"; size: number }\n | { kind: \"streamed\"; size: number; content: string }\n | { kind: \"stream-error\"; size: number; message: string }\n | {\n kind: \"too-large\";\n size: number;\n maxDisplayBytes: number;\n downloading: boolean;\n downloadUrl: string | null;\n downloadName: string | null;\n }\n | { kind: \"error\"; message: string };\n\nexport interface TextViewerInputs {\n maxDisplayBytes: number;\n inline: {\n isLoading: boolean;\n isError: boolean;\n /** `{ size }` when the failure was specifically `FileTooLargeError`; `null` for a generic\n * read failure (network/permission/etc). */\n tooLarge: { size: number } | null;\n errorMessage: string | null;\n content: string | null;\n };\n streamed: {\n isLoading: boolean;\n isError: boolean;\n errorMessage: string | null;\n content: string | null;\n };\n download: {\n requested: boolean;\n isLoading: boolean;\n objectUrl: string | null;\n fileName: string | null;\n };\n}\n\n/** Selects exactly one `TextViewerState` from the current query states. Pure — no hooks, no I/O. */\nexport function selectTextViewerState(input: TextViewerInputs): TextViewerState {\n const { maxDisplayBytes, inline, streamed, download } = input;\n\n if (inline.isLoading) return { kind: \"loading\" };\n\n if (inline.tooLarge) {\n const { size } = inline.tooLarge;\n if (size > maxDisplayBytes) {\n return {\n kind: \"too-large\",\n size,\n maxDisplayBytes,\n downloading: download.requested && download.isLoading,\n downloadUrl: download.objectUrl,\n downloadName: download.fileName,\n };\n }\n if (streamed.isLoading) return { kind: \"streaming\", size };\n if (streamed.isError) {\n return { kind: \"stream-error\", size, message: streamed.errorMessage ?? \"stream failed\" };\n }\n if (streamed.content !== null) return { kind: \"streamed\", size, content: streamed.content };\n return { kind: \"loading\" };\n }\n\n if (inline.isError) {\n return { kind: \"error\", message: inline.errorMessage ?? \"unknown error\" };\n }\n\n if (inline.content !== null) return { kind: \"inline\", content: inline.content };\n return { kind: \"loading\" };\n}\n","/**\n * TextViewer — the default viewer for source/text files: fetches the UTF-8 preview via\n * `useFileRead` and renders it through `CodeView` (line gutter + Shiki highlighting). Registered\n * in `viewer-registry.ts` as the fallback for any file not claimed by a more specific viewer.\n *\n * Three size tiers (task-009 — raising `file_read_request`'s old 512 KiB ceiling):\n * 1. `size <= MAX_INLINE_FILE_READ_BYTES` (server-side, 5 MiB) — the `useFileRead` JSON round\n * trip above, unchanged.\n * 2. `MAX_INLINE_FILE_READ_BYTES < size <= MAX_DISPLAY_BYTES` (30 MiB) — transparently refetch via\n * the uncapped chunked binary download path (`use-file-text.ts`) and render the same\n * `CodeView`, with a muted note that the file was streamed rather than read inline.\n * 3. `size > MAX_DISPLAY_BYTES` — a terminal state: no render attempt, just the size, why, and a\n * download action (`BinaryFallbackViewer`'s existing on-demand download pattern).\n *\n * Which tier applies is the pure, DOM-free `selectTextViewerState` (`text-viewer-state.ts`) — this\n * component is a thin switch-render over it.\n */\n\nimport { useState } from \"react\";\nimport { Button } from \"@pi-studio-ui/components/primitives/Button.js\";\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { Panel } from \"@pi-studio-ui/components/primitives/Panel.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.js\";\nimport { useFileRead, FileTooLargeError } from \"@pi-studio-ui/hooks/use-file-read.js\";\nimport { useFileText } from \"@pi-studio-ui/hooks/use-file-text.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport { CodeView } from \"./CodeView.js\";\nimport { selectTextViewerState } from \"./text-viewer-state.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport textStyles from \"./TextViewer.module.css\";\n\n/** Display ceiling above the inline cap. `CodeView`'s CodeMirror instance enables\n * `EditorView.lineWrapping`, which makes it measure line heights across the whole document —\n * well past interactive above this size, so files this large get a terminal download-only state\n * instead of an attempted render. Deliberately not configurable (task-009 notes). */\nexport const MAX_DISPLAY_BYTES = 30 * 1024 * 1024;\n\nfunction formatMegabytes(bytes: number): string {\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function TextViewer({ path }: ViewerProps) {\n const inline = useFileRead(path);\n const tooLarge = inline.error instanceof FileTooLargeError ? inline.error : null;\n const displayable = tooLarge !== null && tooLarge.size <= MAX_DISPLAY_BYTES;\n\n const streamed = useFileText(path, displayable);\n const [downloadRequested, setDownloadRequested] = useState(false);\n const download = useFileDownload(path, downloadRequested);\n\n const state = selectTextViewerState({\n maxDisplayBytes: MAX_DISPLAY_BYTES,\n inline: {\n isLoading: inline.isLoading,\n isError: inline.isError,\n tooLarge: tooLarge ? { size: tooLarge.size } : null,\n errorMessage: inline.error instanceof Error ? inline.error.message : null,\n content: inline.data?.content ?? null,\n },\n streamed: {\n isLoading: streamed.isLoading,\n isError: streamed.isError,\n errorMessage: streamed.error instanceof Error ? streamed.error.message : null,\n content: streamed.data?.content ?? null,\n },\n download: {\n requested: downloadRequested,\n isLoading: download.isLoading,\n objectUrl: download.data?.objectUrl ?? null,\n fileName: download.data?.fileName ?? null,\n },\n });\n\n switch (state.kind) {\n case \"loading\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Loading...\n </EmptyState>\n );\n case \"inline\":\n return <CodeView path={path} content={state.content} />;\n case \"streaming\":\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Streaming {formatMegabytes(state.size)} file...\n </EmptyState>\n );\n case \"stream-error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n case \"streamed\":\n return (\n <Panel>\n <div className={textStyles.note}>{formatMegabytes(state.size)} file streamed</div>\n <div className={textStyles.body}>\n <CodeView path={path} content={state.content} />\n </div>\n </Panel>\n );\n case \"too-large\": {\n const name = path.split(\"/\").pop() || path;\n return (\n <EmptyState>\n <div className={textStyles.tooLarge}>\n <div>\n {formatMegabytes(state.size)} — too large to display (display ceiling is{\" \"}\n {formatMegabytes(state.maxDisplayBytes)}).\n </div>\n {state.downloading ? (\n <Spinner size=\"sm\" />\n ) : state.downloadUrl ? (\n <a href={state.downloadUrl} download={state.downloadName || name}>\n <Button size=\"sm\">Save file</Button>\n </a>\n ) : (\n <Button size=\"sm\" onClick={() => setDownloadRequested(true)}>\n Download\n </Button>\n )}\n </div>\n </EmptyState>\n );\n }\n case \"error\":\n return <EmptyState>Error: {state.message}</EmptyState>;\n }\n}\n"],"names":["mergeFileTextState","input","enabled","download","decode","useFileText","path","useFileDownload","objectUrl","_a","useQuery","rpcKeys","selectTextViewerState","maxDisplayBytes","inline","streamed","size","MAX_DISPLAY_BYTES","formatMegabytes","bytes","TextViewer","useFileRead","tooLarge","FileTooLargeError","displayable","downloadRequested","setDownloadRequested","useState","state","_b","_c","_d","EmptyState","jsx","Spinner","CodeView","Panel","jsxs","textStyles","name","Button"],"mappings":"0eA4BO,SAASA,EAAmBC,EAAgD,CACjF,KAAM,CAAE,QAAAC,EAAS,SAAAC,EAAU,OAAAC,CAAA,EAAWH,EACtC,MAAO,CACL,UAAWC,IAAYC,EAAS,WAAcA,EAAS,cAAgBC,EAAO,WAC9E,QAASD,EAAS,SAAWC,EAAO,QACpC,MAAOD,EAA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ACA,IAAK,QACH,cAAQM,EAAA,CAAW,SAAA,CAAA,UAAQJ,EAAM,OAAA,EAAQ,CAAA,CAE/C"}
@@ -1,2 +1,2 @@
1
- import{j as o}from"./vendor-react-Uv3j2inr.js";import{E as e,S as t}from"./index-CVbpa3Qk.js";import{u as n}from"./use-file-download-RWF-ZBv9.js";import"./vendor-query-NxjRJKdp.js";import"./vendor-BLc7PaxD.js";import"./vendor-markdown-DtEbK_xy.js";import"./vendor-highlight-CJuJYF7f.js";import"./vendor-icons-DDiHMdgo.js";import"./vendor-overlays-Ki1AFMsh.js";import"./vendor-dnd-Bvh3agTi.js";const a="_wrap_gy3e6_1",m="_video_gy3e6_10",i={wrap:a,video:m};function E({path:s}){const r=n(s);return r.isLoading?o.jsxs(e,{children:[o.jsx(t,{size:"sm"})," Loading video..."]}):r.isError?o.jsxs(e,{children:["Error: ",r.error instanceof Error?r.error.message:"unknown error"]}):r.data?o.jsx("div",{className:i.wrap,children:o.jsx("video",{className:i.video,src:r.data.objectUrl,controls:!0})}):null}export{E as VideoViewer};
2
- //# sourceMappingURL=VideoViewer-XGCQzxEz.js.map
1
+ import{j as o}from"./vendor-react-Uv3j2inr.js";import{E as e,S as t}from"./index-Cz7AgOgN.js";import{u as n}from"./use-file-download-BCG_kqpD.js";import"./vendor-query-NxjRJKdp.js";import"./vendor-BLc7PaxD.js";import"./vendor-markdown-DtEbK_xy.js";import"./vendor-highlight-CJuJYF7f.js";import"./vendor-icons-DDiHMdgo.js";import"./vendor-overlays-Ki1AFMsh.js";import"./vendor-dnd-Bvh3agTi.js";const a="_wrap_gy3e6_1",m="_video_gy3e6_10",i={wrap:a,video:m};function E({path:s}){const r=n(s);return r.isLoading?o.jsxs(e,{children:[o.jsx(t,{size:"sm"})," Loading video..."]}):r.isError?o.jsxs(e,{children:["Error: ",r.error instanceof Error?r.error.message:"unknown error"]}):r.data?o.jsx("div",{className:i.wrap,children:o.jsx("video",{className:i.video,src:r.data.objectUrl,controls:!0})}):null}export{E as VideoViewer};
2
+ //# sourceMappingURL=VideoViewer-CYXPkYLV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"VideoViewer-XGCQzxEz.js","sources":["../../../src/features/files/VideoViewer.tsx"],"sourcesContent":["/**\n * VideoViewer — renders a binary video file via the file-transfer binary download\n * (`useFileDownload`) into a native `<video>` element (POC_TO_APP_PLAN_UI.md §4.5 follow-up:\n * modular file preview).\n */\n\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport styles from \"./VideoViewer.module.css\";\n\nexport function VideoViewer({ path }: ViewerProps) {\n const query = useFileDownload(path);\n\n if (query.isLoading) {\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Loading video...\n </EmptyState>\n );\n }\n if (query.isError) {\n return (\n <EmptyState>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </EmptyState>\n );\n }\n if (!query.data) return null;\n\n return (\n <div className={styles.wrap}>\n {/* eslint-disable-next-line jsx-a11y/media-has-caption -- arbitrary local file, no caption track available */}\n <video className={styles.video} src={query.data.objectUrl} controls />\n </div>\n );\n}\n"],"names":["VideoViewer","path","query","useFileDownload","EmptyState","jsx","Spinner","styles"],"mappings":"wcAYO,SAASA,EAAY,CAAE,KAAAC,GAAqB,CACjD,MAAMC,EAAQC,EAAgBF,CAAI,EAElC,OAAIC,EAAM,iBAELE,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,mBAAA,EACvB,EAGAJ,EAAM,eAELE,EAAA,CAAW,SAAA,CAAA,UACFF,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,WAGR,MAAA,CAAI,UAAWK,EAAO,KAErB,eAAC,QAAA,CAAM,UAAWA,EAAO,MAAO,IAAKL,EAAM,KAAK,UAAW,SAAQ,GAAC,EACtE,EANsB,IAQ1B"}
1
+ {"version":3,"file":"VideoViewer-CYXPkYLV.js","sources":["../../../src/features/files/VideoViewer.tsx"],"sourcesContent":["/**\n * VideoViewer — renders a binary video file via the file-transfer binary download\n * (`useFileDownload`) into a native `<video>` element (POC_TO_APP_PLAN_UI.md §4.5 follow-up:\n * modular file preview).\n */\n\nimport { Spinner } from \"@pi-studio-ui/components/primitives/Spinner.js\";\nimport { EmptyState } from \"@pi-studio-ui/components/primitives/EmptyState.js\";\nimport { useFileDownload } from \"@pi-studio-ui/hooks/use-file-download.js\";\nimport type { ViewerProps } from \"./viewer-registry.js\";\nimport styles from \"./VideoViewer.module.css\";\n\nexport function VideoViewer({ path }: ViewerProps) {\n const query = useFileDownload(path);\n\n if (query.isLoading) {\n return (\n <EmptyState>\n <Spinner size=\"sm\" /> Loading video...\n </EmptyState>\n );\n }\n if (query.isError) {\n return (\n <EmptyState>\n Error: {query.error instanceof Error ? query.error.message : \"unknown error\"}\n </EmptyState>\n );\n }\n if (!query.data) return null;\n\n return (\n <div className={styles.wrap}>\n {/* eslint-disable-next-line jsx-a11y/media-has-caption -- arbitrary local file, no caption track available */}\n <video className={styles.video} src={query.data.objectUrl} controls />\n </div>\n );\n}\n"],"names":["VideoViewer","path","query","useFileDownload","EmptyState","jsx","Spinner","styles"],"mappings":"wcAYO,SAASA,EAAY,CAAE,KAAAC,GAAqB,CACjD,MAAMC,EAAQC,EAAgBF,CAAI,EAElC,OAAIC,EAAM,iBAELE,EAAA,CACC,SAAA,CAAAC,EAAAA,IAACC,EAAA,CAAQ,KAAK,IAAA,CAAK,EAAE,mBAAA,EACvB,EAGAJ,EAAM,eAELE,EAAA,CAAW,SAAA,CAAA,UACFF,EAAM,iBAAiB,MAAQA,EAAM,MAAM,QAAU,eAAA,EAC/D,EAGCA,EAAM,WAGR,MAAA,CAAI,UAAWK,EAAO,KAErB,eAAC,QAAA,CAAM,UAAWA,EAAO,MAAO,IAAKL,EAAM,KAAK,UAAW,SAAQ,GAAC,EACtE,EANsB,IAQ1B"}