Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(preview): in-app browser preview panel

Aiden Bai52c77c1ec4c1
diff --git a/app-preview-browser-plan.md b/app-preview-browser-plan.md
index 078c1cc93..b6675daf8 100644
--- a/app-preview-browser-plan.md
+++ b/app-preview-browser-plan.md
@@ -143,7 +143,7 @@ export function selectActiveRightPanel(
- Remove the local `planSidebarOpen` state (`:688`).
- Replace `setPlanSidebarOpen(true)` callsites with `rightPanelStore.open(activeThreadRef, "plan")`.
- Replace `closePlanSidebar` with `rightPanelStore.close(activeThreadRef)`.
-- Existing `planSidebarDismissedForTurnRef`/`planSidebarOpenOnNextThreadRef` logic stays local — it only governs whether to *call* `open()`/`close()` on turn change.
+- Existing `planSidebarDismissedForTurnRef`/`planSidebarOpenOnNextThreadRef` logic stays local — it only governs whether to _call_ `open()`/`close()` on turn change.
### Render arbitration
@@ -176,49 +176,49 @@ const useSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
### NEW files
-| File | Purpose |
-|---|---|
-| `packages/contracts/src/preview.ts` | Effect/Schema schemas: inputs, snapshot, events, errors |
-| `packages/contracts/src/preview.test.ts` | Schema round‑trip tests |
-| `apps/server/src/preview/Services/Manager.ts` | `PreviewManager` Service tag + interface |
-| `apps/server/src/preview/Layers/Manager.ts` | Implementation: in‑memory map + event subject |
-| `apps/server/src/preview/Layers/Manager.test.ts` | Lifecycle, snapshot, event ordering |
-| `apps/desktop/src/preview-view-manager.ts` | Plain‑Node Electron port of ami's BrowserManager (subset) |
-| `apps/desktop/src/preview-preload.ts` | Webview preload (no‑op v1) |
-| `apps/web/src/previewStateStore.ts` | Per‑thread zustand store (mirrors `terminalStateStore.ts`) |
-| `apps/web/src/previewStateStore.test.ts` | Reducer tests |
-| `apps/web/src/rightPanelStore.ts` | Right‑panel arbiter |
-| `apps/web/src/rightPanelStore.test.ts` | Arbiter tests |
-| `apps/web/src/components/preview/PreviewPanel.tsx` | Right‑panel entry (wraps `PreviewPanelShell`) |
-| `apps/web/src/components/preview/PreviewPanelShell.tsx` | Shell mirroring `DiffPanelShell` (`mode: "inline"\|"sheet"\|"sidebar"`) |
-| `apps/web/src/components/preview/PreviewView.tsx` | Chrome bar (URL/back/fwd/refresh) + `<PreviewWebview>` |
-| `apps/web/src/components/preview/PreviewWebview.tsx` | Electron `<webview>` host; null on web build |
-| `apps/web/src/components/preview/PreviewEmptyState.tsx` | Pre‑URL empty state |
-| `apps/web/src/components/preview/PreviewUnsupportedToast.ts` | `"Preview is only available in the desktop app"` toast |
+| File | Purpose |
+| ------------------------------------------------------------ | ----------------------------------------------------------------------- |
+| `packages/contracts/src/preview.ts` | Effect/Schema schemas: inputs, snapshot, events, errors |
+| `packages/contracts/src/preview.test.ts` | Schema round‑trip tests |
+| `apps/server/src/preview/Services/Manager.ts` | `PreviewManager` Service tag + interface |
+| `apps/server/src/preview/Layers/Manager.ts` | Implementation: in‑memory map + event subject |
+| `apps/server/src/preview/Layers/Manager.test.ts` | Lifecycle, snapshot, event ordering |
+| `apps/desktop/src/preview-view-manager.ts` | Plain‑Node Electron port of ami's BrowserManager (subset) |
+| `apps/desktop/src/preview-preload.ts` | Webview preload (no‑op v1) |
+| `apps/web/src/previewStateStore.ts` | Per‑thread zustand store (mirrors `terminalStateStore.ts`) |
+| `apps/web/src/previewStateStore.test.ts` | Reducer tests |
+| `apps/web/src/rightPanelStore.ts` | Right‑panel arbiter |
+| `apps/web/src/rightPanelStore.test.ts` | Arbiter tests |
+| `apps/web/src/components/preview/PreviewPanel.tsx` | Right‑panel entry (wraps `PreviewPanelShell`) |
+| `apps/web/src/components/preview/PreviewPanelShell.tsx` | Shell mirroring `DiffPanelShell` (`mode: "inline"\|"sheet"\|"sidebar"`) |
+| `apps/web/src/components/preview/PreviewView.tsx` | Chrome bar (URL/back/fwd/refresh) + `<PreviewWebview>` |
+| `apps/web/src/components/preview/PreviewWebview.tsx` | Electron `<webview>` host; null on web build |
+| `apps/web/src/components/preview/PreviewEmptyState.tsx` | Pre‑URL empty state |
+| `apps/web/src/components/preview/PreviewUnsupportedToast.ts` | `"Preview is only available in the desktop app"` toast |
### MODIFIED files
-| File | Change |
-|---|---|
-| `packages/contracts/src/keybindings.ts` | Add `preview.toggle`, `preview.refresh`, `preview.focusUrl` to `STATIC_KEYBINDING_COMMANDS`; add `previewFocus`, `previewOpen` to context keys |
-| `packages/contracts/src/project.ts` | Add `previewUrl?: string` and `autoOpenPreview?: boolean` to `ProjectScript` schema |
-| `packages/contracts/src/server.ts` | Extend `EnvironmentApi` with `preview` namespace |
-| `packages/contracts/src/index.ts` | Re‑export new types |
-| `apps/server/src/keybindings.ts` | Add defaults: `mod+shift+j` → `preview.toggle`, `mod+shift+r` → `preview.refresh` (when `previewFocus`) |
-| `apps/server/src/ws.ts` | Route `preview.open`, `preview.navigate`, `preview.refresh`, `preview.close`, `preview.list`, `preview.onEvent` |
-| `apps/server/src/orchestration/runtimeLayer.ts` (or equivalent) | Provide `PreviewManager.Default` |
-| `apps/web/src/environmentApi.ts` | Wire `preview` slot in `createEnvironmentApi` |
-| `apps/web/src/keybindings.ts` | Add `isPreviewToggleShortcut`, `isPreviewRefreshShortcut` helpers |
-| `apps/web/src/routes/_chat.tsx` | Handle `preview.toggle` in global shortcut handler |
-| `apps/web/src/components/ChatView.tsx` | Replace local `planSidebarOpen` with `rightPanelStore`; render `PreviewPanel` |
-| `apps/web/src/components/ThreadTerminalDrawer.tsx` | At terminal link activation, when `match.kind === "url"` and link looks like a dev URL, show context menu with "Open in preview" / "Open in browser"; pass through to `localApi.preview.openTab(...)` when chosen |
-| `apps/web/src/components/ProjectScriptsControl.tsx` | Add `previewUrl` + `autoOpenPreview` form fields in the Add/Edit dialog |
-| `apps/web/src/projectScripts.ts` | Carry the new fields through `commandForProjectScript` / serialization |
-| `apps/web/src/types.ts` | Add `PreviewSession` mirror types (or re‑export from contracts) |
-| `apps/web/src/lib/desktopBridge.d.ts` (or wherever bridge types live) | Add `preview` namespace shape |
-| `apps/desktop/src/main.ts` | Register `preview:*` IPC handlers; instantiate `previewViewManager`; wire `mainWindow` injection |
-| `apps/desktop/src/preload.ts` | Expose `desktopBridge.preview.*` |
-| `KEYBINDINGS.md` | Document new commands and `previewFocus`/`previewOpen` `when` keys |
+| File | Change |
+| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `packages/contracts/src/keybindings.ts` | Add `preview.toggle`, `preview.refresh`, `preview.focusUrl` to `STATIC_KEYBINDING_COMMANDS`; add `previewFocus`, `previewOpen` to context keys |
+| `packages/contracts/src/project.ts` | Add `previewUrl?: string` and `autoOpenPreview?: boolean` to `ProjectScript` schema |
+| `packages/contracts/src/server.ts` | Extend `EnvironmentApi` with `preview` namespace |
+| `packages/contracts/src/index.ts` | Re‑export new types |
+| `apps/server/src/keybindings.ts` | Add defaults: `mod+shift+j` → `preview.toggle`, `mod+shift+r` → `preview.refresh` (when `previewFocus`) |
+| `apps/server/src/ws.ts` | Route `preview.open`, `preview.navigate`, `preview.refresh`, `preview.close`, `preview.list`, `preview.onEvent` |
+| `apps/server/src/orchestration/runtimeLayer.ts` (or equivalent) | Provide `PreviewManager.Default` |
+| `apps/web/src/environmentApi.ts` | Wire `preview` slot in `createEnvironmentApi` |
+| `apps/web/src/keybindings.ts` | Add `isPreviewToggleShortcut`, `isPreviewRefreshShortcut` helpers |
+| `apps/web/src/routes/_chat.tsx` | Handle `preview.toggle` in global shortcut handler |
+| `apps/web/src/components/ChatView.tsx` | Replace local `planSidebarOpen` with `rightPanelStore`; render `PreviewPanel` |
+| `apps/web/src/components/ThreadTerminalDrawer.tsx` | At terminal link activation, when `match.kind === "url"` and link looks like a dev URL, show context menu with "Open in preview" / "Open in browser"; pass through to `localApi.preview.openTab(...)` when chosen |
+| `apps/web/src/components/ProjectScriptsControl.tsx` | Add `previewUrl` + `autoOpenPreview` form fields in the Add/Edit dialog |
+| `apps/web/src/projectScripts.ts` | Carry the new fields through `commandForProjectScript` / serialization |
+| `apps/web/src/types.ts` | Add `PreviewSession` mirror types (or re‑export from contracts) |
+| `apps/web/src/lib/desktopBridge.d.ts` (or wherever bridge types live) | Add `preview` namespace shape |
+| `apps/desktop/src/main.ts` | Register `preview:*` IPC handlers; instantiate `previewViewManager`; wire `mainWindow` injection |
+| `apps/desktop/src/preload.ts` | Expose `desktopBridge.preview.*` |
+| `KEYBINDINGS.md` | Document new commands and `previewFocus`/`previewOpen` `when` keys |
### NOT changed
@@ -335,10 +335,7 @@ export class PreviewInvalidUrlError extends Schema.TaggedErrorClass<PreviewInval
}
}
-export const PreviewError = Schema.Union([
- PreviewSessionLookupError,
- PreviewInvalidUrlError,
-]);
+export const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);
export type PreviewError = typeof PreviewError.Type;
```
@@ -360,9 +357,9 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"diff.toggle",
- "preview.toggle", // NEW
- "preview.refresh", // NEW
- "preview.focusUrl", // NEW
+ "preview.toggle", // NEW
+ "preview.refresh", // NEW
+ "preview.focusUrl", // NEW
"commandPalette.toggle",
"chat.new",
"chat.newLocal",
@@ -399,28 +396,21 @@ import {
} from "@t3tools/contracts";
export interface PreviewManagerShape {
- readonly open: (
- input: PreviewOpenInput,
- ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
+ readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly navigate: (
input: PreviewNavigateInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
- readonly refresh: (
- input: PreviewRefreshInput,
- ) => Effect.Effect<void, PreviewError>;
+ readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
- readonly list: (
- threadId: string,
- ) => Effect.Effect<ReadonlyArray<PreviewSessionSnapshot>>;
+ readonly list: (threadId: string) => Effect.Effect<ReadonlyArray<PreviewSessionSnapshot>>;
readonly subscribe: (
listener: (event: PreviewEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
}
-export class PreviewManager extends Context.Service<
- PreviewManager,
- PreviewManagerShape
->()("t3/preview/Services/Manager/PreviewManager") {}
+export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
+ "t3/preview/Services/Manager/PreviewManager",
+) {}
```
### `apps/server/src/preview/Layers/Manager.ts`
@@ -435,15 +425,12 @@ const normalizeUrl = (input: string) =>
const trimmed = input.trim();
if (!trimmed) throw new Error("empty");
// localhost stays http unless explicitly https
- const useHttp =
- /^(localhost|127\.0\.0\.1|0\.0\.0\.0)(:|\/|$)/.test(trimmed);
+ const useHttp = /^(localhost|127\.0\.0\.1|0\.0\.0\.0)(:|\/|$)/.test(trimmed);
const parsed = urlParseLax(trimmed, { https: !useHttp });
if (!parsed?.href) throw new Error("unparseable");
return parsed.href;
}).pipe(
- Effect.catchAll((cause) =>
- Effect.fail(new PreviewInvalidUrlError({ rawUrl: input, cause })),
- ),
+ Effect.catchAll((cause) => Effect.fail(new PreviewInvalidUrlError({ rawUrl: input, cause }))),
);
```
@@ -513,14 +500,19 @@ export class PreviewViewManager {
this.mainWindow = window;
}
- getPreloadPath(): string { return this.preloadPath; }
- getBrowserPartition(): string { return PREVIEW_PARTITION; }
+ getPreloadPath(): string {
+ return this.preloadPath;
+ }
+ getBrowserPartition(): string {
+ return PREVIEW_PARTITION;
+ }
getBrowserSession(): Session {
if (this.browserSession) return this.browserSession;
const sess = session.fromPartition(PREVIEW_PARTITION);
// strip electron/t3code from UA so dev preview doesn't trip bot detection
- const ua = sess.getUserAgent()
+ const ua = sess
+ .getUserAgent()
.replace(/Electron\/[\d.]+ /, "")
.replace(/\s*t3code\/[\d.]+/, "");
sess.setUserAgent(ua);
@@ -593,9 +585,15 @@ export class PreviewViewManager {
await wc.loadURL(url);
}
- goBack(tabId: string): void { this.requireWebContents(tabId).navigationHistory.goBack(); }
- goForward(tabId: string): void { this.requireWebContents(tabId).navigationHistory.goForward(); }
- refresh(tabId: string): void { this.requireWebContents(tabId).reload(); }
+ goBack(tabId: string): void {
+ this.requireWebContents(tabId).navigationHistory.goBack();
+ }
+ goForward(tabId: string): void {
+ this.requireWebContents(tabId).navigationHistory.goForward();
+ }
+ refresh(tabId: string): void {
+ this.requireWebContents(tabId).reload();
+ }
onStateChange(listener: Listener): () => void {
this.listeners.add(listener);
@@ -656,16 +654,17 @@ export class PreviewViewManager {
if (input.type !== "keyDown") return false;
// Mirror the t3code keybinding defaults that should always reach the main window.
const SHORTCUTS = [
- { key: "j", meta: true, shift: true }, // preview.toggle
- { key: "k", meta: true, shift: false }, // commandPalette.toggle
- { key: ",", meta: true, shift: false }, // settings
- { key: "w", meta: true, shift: false }, // close
+ { key: "j", meta: true, shift: true }, // preview.toggle
+ { key: "k", meta: true, shift: false }, // commandPalette.toggle
+ { key: ",", meta: true, shift: false }, // settings
+ { key: "w", meta: true, shift: false }, // close
// future: terminal.* if user wants them while preview focused
];
- return SHORTCUTS.some((s) =>
- s.key.toLowerCase() === input.key.toLowerCase()
- && s.meta === input.meta
- && s.shift === input.shift,
+ return SHORTCUTS.some(
+ (s) =>
+ s.key.toLowerCase() === input.key.toLowerCase() &&
+ s.meta === input.meta &&
+ s.shift === input.shift,
);
}
@@ -704,9 +703,9 @@ export class PreviewViewManager {
const trimmed = input.trim();
if (!trimmed) throw new PreviewInvalidUrlError(input);
const useHttp = /^(localhost|127\.0\.0\.1|0\.0\.0\.0)(:|\/|$)/.test(trimmed);
- const parsed = new URL(trimmed.includes("://")
- ? trimmed
- : `${useHttp ? "http" : "https"}://${trimmed}`);
+ const parsed = new URL(
+ trimmed.includes("://") ? trimmed : `${useHttp ? "http" : "https"}://${trimmed}`,
+ );
return parsed.href;
}
}
@@ -716,9 +715,15 @@ export class PreviewTabNotFoundError extends Error {
super(`Preview tab not found: ${tabId}`);
}
}
-export class PreviewWebContentsNotFoundError extends Error { /* … */ }
-export class PreviewWebviewNotInitializedError extends Error { /* … */ }
-export class PreviewInvalidUrlError extends Error { /* … */ }
+export class PreviewWebContentsNotFoundError extends Error {
+ /* … */
+}
+export class PreviewWebviewNotInitializedError extends Error {
+ /* … */
+}
+export class PreviewInvalidUrlError extends Error {
+ /* … */
+}
export const previewViewManager = new PreviewViewManager();
```
@@ -734,18 +739,20 @@ previewViewManager.setMainWindow(mainWindow);
Register IPC handlers (in `registerIpcHandlers()`):
```ts
-ipcMain.handle("preview:createTab", (_e, tabId: string) =>
- previewViewManager.createTab(tabId));
-ipcMain.handle("preview:closeTab", (_e, tabId: string) =>
- previewViewManager.closeTab(tabId));
+ipcMain.handle("preview:createTab", (_e, tabId: string) => previewViewManager.createTab(tabId));
+ipcMain.handle("preview:closeTab", (_e, tabId: string) => previewViewManager.closeTab(tabId));
ipcMain.handle("preview:setVisibility", (_e, tabId: string, visible: boolean) =>
- previewViewManager.setVisibility(tabId, visible));
+ previewViewManager.setVisibility(tabId, visible),
+);
ipcMain.handle("preview:registerWebview", (_e, tabId: string, wcId: number) =>
- previewViewManager.registerWebview(tabId, wcId));
+ previewViewManager.registerWebview(tabId, wcId),
+);
ipcMain.handle("preview:unregisterWebview", (_e, tabId: string) =>
- previewViewManager.unregisterWebview(tabId));
+ previewViewManager.unregisterWebview(tabId),
+);
ipcMain.handle("preview:navigate", (_e, tabId: string, url: string) =>
- previewViewManager.navigate(tabId, url));
+ previewViewManager.navigate(tabId, url),
+);
ipcMain.handle("preview:goBack", (_e, tabId: string) => previewViewManager.goBack(tabId));
ipcMain.handle("preview:goForward", (_e, tabId: string) => previewViewManager.goForward(tabId));
ipcMain.handle("preview:refresh", (_e, tabId: string) => previewViewManager.refresh(tabId));
@@ -776,16 +783,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke("preview:setVisibility", tabId, visible),
registerWebview: (tabId: string, wcId: number) =>
ipcRenderer.invoke("preview:registerWebview", tabId, wcId),
- unregisterWebview: (tabId: string) =>
- ipcRenderer.invoke("preview:unregisterWebview", tabId),
- navigate: (tabId: string, url: string) =>
- ipcRenderer.invoke("preview:navigate", tabId, url),
+ unregisterWebview: (tabId: string) => ipcRenderer.invoke("preview:unregisterWebview", tabId),
+ navigate: (tabId: string, url: string) => ipcRenderer.invoke("preview:navigate", tabId, url),
goBack: (tabId: string) => ipcRenderer.invoke("preview:goBack", tabId),
goForward: (tabId: string) => ipcRenderer.invoke("preview:goForward", tabId),
refresh: (tabId: string) => ipcRenderer.invoke("preview:refresh", tabId),
getPreloadPath: (): Promise<string> => ipcRenderer.invoke("preview:getPreloadPath"),
- getBrowserPartition: (): Promise<string> =>
- ipcRenderer.invoke("preview:getBrowserPartition"),
+ getBrowserPartition: (): Promise<string> => ipcRenderer.invoke("preview:getBrowserPartition"),
onStateChange: (cb: (tabId: string, state: DesktopPreviewTabState) => void) => {
const listener = (_e: unknown, tabId: string, state: DesktopPreviewTabState) =>
cb(tabId, state);
@@ -1096,14 +1100,14 @@ Adding `preview.toggle`, `preview.refresh`, `preview.focusUrl` to `STATIC_KEYBIN
Following t3code's vitest patterns (`bun run test`, never `bun test`):
-| Test file | What it covers |
-|---|---|
-| `packages/contracts/src/preview.test.ts` | Schema encode/decode round-trips for inputs, snapshot, events; URL trimming; error tagged unions |
-| `apps/server/src/preview/Layers/Manager.test.ts` | `open` creates session and emits `opened`; `navigate` updates and emits `navigated`; `close` removes and emits `closed`; subscribers receive monotonic events; `list` returns sorted snapshots |
-| `apps/web/src/previewStateStore.test.ts` | `applyServerEvent` reducer correctness; ring buffer cap; `closed` removes entry; `desktopOverlay` is independent of snapshot fields |
-| `apps/web/src/rightPanelStore.test.ts` | `open` / `close` / `toggle` semantics; per-thread isolation; `?diff=1` sync compatibility |
-| `apps/web/src/components/preview/PreviewView.test.ts` (logic-only via `PreviewView.logic.ts` extraction) | URL bar input → navigation; navigation button enabled-state derivation; visibility toggle on panel hide |
-| Existing `ThreadTerminalDrawer.test.ts` | Add a case: link activation with `kind: "url"` and `previewable: true` shows the context menu (mock `localApi.contextMenu.show`) |
+| Test file | What it covers |
+| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `packages/contracts/src/preview.test.ts` | Schema encode/decode round-trips for inputs, snapshot, events; URL trimming; error tagged unions |
+| `apps/server/src/preview/Layers/Manager.test.ts` | `open` creates session and emits `opened`; `navigate` updates and emits `navigated`; `close` removes and emits `closed`; subscribers receive monotonic events; `list` returns sorted snapshots |
+| `apps/web/src/previewStateStore.test.ts` | `applyServerEvent` reducer correctness; ring buffer cap; `closed` removes entry; `desktopOverlay` is independent of snapshot fields |
+| `apps/web/src/rightPanelStore.test.ts` | `open` / `close` / `toggle` semantics; per-thread isolation; `?diff=1` sync compatibility |
+| `apps/web/src/components/preview/PreviewView.test.ts` (logic-only via `PreviewView.logic.ts` extraction) | URL bar input → navigation; navigation button enabled-state derivation; visibility toggle on panel hide |
+| Existing `ThreadTerminalDrawer.test.ts` | Add a case: link activation with `kind: "url"` and `previewable: true` shows the context menu (mock `localApi.contextMenu.show`) |
Manual smoke checklist (drop in `apps/desktop/test/smoke/`):
@@ -1120,15 +1124,15 @@ Manual smoke checklist (drop in `apps/desktop/test/smoke/`):
## 12. Risks and resolutions
-| Risk | Resolution |
-|---|---|
-| Hidden `<webview>` GPU cost when keeping multiple threads' previews mounted | v1 only mounts the active thread's preview. v2 can adopt the `PersistentThreadTerminalDrawer` pattern + `setVisibility` |
-| `<webview>` keyboard capture eats `mod+shift+j` etc. | `before-input-event` forwarder in `PreviewViewManager` (mirror of ami's pattern, smaller shortcut list) |
-| URL with `X-Frame-Options: DENY` works fine in `<webview>` (good — that's why we picked `<webview>` over iframe) | n/a |
-| Server restart while desktop is alive: `<webview>` is still loaded but server has no record | On WS reconnect, web side sends a `preview.list(threadId)` and if empty, sends a `preview.open(...)` to re‑register the current URL. Add a small `useReconciliation` effect in `PreviewView.tsx` |
-| Renderer process renders something into `<webview>` but never registered → orphaned tab in `PreviewViewManager` | `closeTab` is idempotent; on `<webview>` unmount, `unregisterWebview` is called; if that didn't fire (crash), the next `createTab` for the same `tabId` reuses the record |
-| `autoOpenPreview` racing with terminal output (URL might not be in stdout yet by the time the script "starts") | Two‑phase: if `script.previewUrl` is set, open eagerly with that URL. If not set but `autoOpenPreview === true`, watch terminal output via existing `terminal-links` extraction and open the first `previewable` URL within a 60s window |
-| Multiple windows of the desktop both rendering the same `<webview>` for the same thread | `<webview>` is per‑renderer; each window creates its own. The shared `persist:t3code-preview` partition keeps cookies in sync. Server records the last navigation URL but doesn't enforce single‑renderer |
+| Risk | Resolution |
+| ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Hidden `<webview>` GPU cost when keeping multiple threads' previews mounted | v1 only mounts the active thread's preview. v2 can adopt the `PersistentThreadTerminalDrawer` pattern + `setVisibility` |
+| `<webview>` keyboard capture eats `mod+shift+j` etc. | `before-input-event` forwarder in `PreviewViewManager` (mirror of ami's pattern, smaller shortcut list) |
+| URL with `X-Frame-Options: DENY` works fine in `<webview>` (good — that's why we picked `<webview>` over iframe) | n/a |
+| Server restart while desktop is alive: `<webview>` is still loaded but server has no record | On WS reconnect, web side sends a `preview.list(threadId)` and if empty, sends a `preview.open(...)` to re‑register the current URL. Add a small `useReconciliation` effect in `PreviewView.tsx` |
+| Renderer process renders something into `<webview>` but never registered → orphaned tab in `PreviewViewManager` | `closeTab` is idempotent; on `<webview>` unmount, `unregisterWebview` is called; if that didn't fire (crash), the next `createTab` for the same `tabId` reuses the record |
+| `autoOpenPreview` racing with terminal output (URL might not be in stdout yet by the time the script "starts") | Two‑phase: if `script.previewUrl` is set, open eagerly with that URL. If not set but `autoOpenPreview === true`, watch terminal output via existing `terminal-links` extraction and open the first `previewable` URL within a 60s window |
+| Multiple windows of the desktop both rendering the same `<webview>` for the same thread | `<webview>` is per‑renderer; each window creates its own. The shared `persist:t3code-preview` partition keeps cookies in sync. Server records the last navigation URL but doesn't enforce single‑renderer |
---
@@ -1155,38 +1159,43 @@ Any of these can land in follow-up PRs against the same `PreviewViewManager` + `
Every visible element below is built on existing components. No new design primitives are introduced. References below are to the `apps/web/src/components/ui/` directory.
-| Need | Primitive | File ref | Notes |
-|---|---|---|---|
-| Theme colors / radii | CSS vars `--background`, `--card`, `--muted`, `--muted-foreground`, `--border`, `--input`, `--ring`, `--success`, etc. | `apps/web/src/index.css:86` | Light + `@variant dark` blocks. Always reference vars via tailwind utilities (`bg-card`, `text-muted-foreground`) — never hard‑code hex |
-| `cn` class merger | `cn(...inputs)` from `~/lib/utils` | `apps/web/src/lib/utils.ts:8` | Wraps `cx` + `tailwind-merge` |
-| Buttons (chrome bar back/fwd/refresh) | `Button` `variant="ghost"` `size="icon-xs"` | `apps/web/src/components/ui/button.tsx` | `icon-xs` is `size-7 rounded-md sm:size-6` — exactly the density in the screenshot |
-| Buttons (URL field submit) | `Button` `variant="outline"` `size="sm"` | same | Matches the "ProjectScript primary action" density already in `BranchToolbar` |
-| Button group (back / fwd / refresh as a unit) | `Group` + implicit segmenting (no `GroupSeparator`) | `apps/web/src/components/ui/group.tsx` | Group automatically removes outer borders between adjacent `[data-slot]` children |
-| URL input (chrome bar editable) | `InputGroup` + `InputGroupInput` + `InputGroupAddon align="inline-start"` (globe icon) | `apps/web/src/components/ui/input-group.tsx` | Click‑anywhere‑to‑focus already wired in `InputGroupAddon`'s `onMouseDown` |
-| URL input (chrome bar disabled / read‑only) | Same `InputGroup` with `disabled` on the input | same | Yields the muted look in the screenshot via `has-[input:disabled]:opacity-64` |
-| Tab strip cells | Plain `<button>` + `cn` — **not** `Tabs` (base‑ui Tabs is over‑featured for browser tabs); `Group` semantics differ | new file `PreviewTabStrip.tsx` | Same hover/active treatment as the sidebar's `ChatPreview` rows |
-| "Local" recommendation card | `Card` (no `CardHeader`/`CardPanel` — flat) | `apps/web/src/components/ui/card.tsx` | `Card` already gives `rounded-2xl border bg-card text-card-foreground shadow-xs/5` plus the inset stroke via `before:` |
-| Status pulse dot (running) | `<span>` with `bg-success` and `animate-pulse` | tailwind built‑in | Theme‑aware via `--success` |
-| Tooltips (back/fwd/refresh hover) | `Tooltip` + `TooltipTrigger` + `TooltipPopup` | `apps/web/src/components/ui/tooltip.tsx` | Sub‑200ms hover already configured |
-| Empty state title + description | `Empty`, `EmptyHeader`, `EmptyTitle`, `EmptyDescription`, `EmptyContent`, `EmptyMedia` | `apps/web/src/components/ui/empty.tsx` | `EmptyMedia variant="icon"` gives the stacked‑cards icon with side rotation we want for "no preview yet" |
-| Loading bar (top of webview while navigating) | Plain `<div>` with `bg-primary` + `transition-all` | n/a | Mirrors ami's loading bar (`browser-view.tsx:434`) — single‑pixel‑height div animating `width` |
-| Spinner (inline in URL field while loading) | `Spinner` | `apps/web/src/components/ui/spinner.tsx` | Wraps `Loader2Icon` from lucide |
-| Context menu (terminal link "Open in preview") | `localApi.contextMenu.show(...)` (already exists) | `apps/web/src/localApi.ts:58` | Native menu on desktop, fallback in `contextMenuFallback.ts` on web |
-| Keybinding shortcut label in tooltips | `shortcutLabelForCommand(keybindings, "preview.toggle")` | `apps/web/src/keybindings.ts` | Renders `⌘⇧J` etc. |
-| Right‑panel shell sizing | Match `DiffPanelShell` exactly: `w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border` | `apps/web/src/components/DiffPanelShell.tsx:32` | Single class string, do not reinvent |
+| Need | Primitive | File ref | Notes |
+| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
+| Theme colors / radii | CSS vars `--background`, `--card`, `--muted`, `--muted-foreground`, `--border`, `--input`, `--ring`, `--success`, etc. | `apps/web/src/index.css:86` | Light + `@variant dark` blocks. Always reference vars via tailwind utilities (`bg-card`, `text-muted-foreground`) — never hard‑code hex |
+| `cn` class merger | `cn(...inputs)` from `~/lib/utils` | `apps/web/src/lib/utils.ts:8` | Wraps `cx` + `tailwind-merge` |
+| Buttons (chrome bar back/fwd/refresh) | `Button` `variant="ghost"` `size="icon-xs"` | `apps/web/src/components/ui/button.tsx` | `icon-xs` is `size-7 rounded-md sm:size-6` — exactly the density in the screenshot |
+| Buttons (URL field submit) | `Button` `variant="outline"` `size="sm"` | same | Matches the "ProjectScript primary action" density already in `BranchToolbar` |
+| Button group (back / fwd / refresh as a unit) | `Group` + implicit segmenting (no `GroupSeparator`) | `apps/web/src/components/ui/group.tsx` | Group automatically removes outer borders between adjacent `[data-slot]` children |
+| URL input (chrome bar editable) | `InputGroup` + `InputGroupInput` + `InputGroupAddon align="inline-start"` (globe icon) | `apps/web/src/components/ui/input-group.tsx` | Click‑anywhere‑to‑focus already wired in `InputGroupAddon`'s `onMouseDown` |
+| URL input (chrome bar disabled / read‑only) | Same `InputGroup` with `disabled` on the input | same | Yields the muted look in the screenshot via `has-[input:disabled]:opacity-64` |
+| Tab strip cells | Plain `<button>` + `cn` — **not** `Tabs` (base‑ui Tabs is over‑featured for browser tabs); `Group` semantics differ | new file `PreviewTabStrip.tsx` | Same hover/active treatment as the sidebar's `ChatPreview` rows |
+| "Local" recommendation card | `Card` (no `CardHeader`/`CardPanel` — flat) | `apps/web/src/components/ui/card.tsx` | `Card` already gives `rounded-2xl border bg-card text-card-foreground shadow-xs/5` plus the inset stroke via `before:` |
+| Status pulse dot (running) | `<span>` with `bg-success` and `animate-pulse` | tailwind built‑in | Theme‑aware via `--success` |
+| Tooltips (back/fwd/refresh hover) | `Tooltip` + `TooltipTrigger` + `TooltipPopup` | `apps/web/src/components/ui/tooltip.tsx` | Sub‑200ms hover already configured |
+| Empty state title + description | `Empty`, `EmptyHeader`, `EmptyTitle`, `EmptyDescription`, `EmptyContent`, `EmptyMedia` | `apps/web/src/components/ui/empty.tsx` | `EmptyMedia variant="icon"` gives the stacked‑cards icon with side rotation we want for "no preview yet" |
+| Loading bar (top of webview while navigating) | Plain `<div>` with `bg-primary` + `transition-all` | n/a | Mirrors ami's loading bar (`browser-view.tsx:434`) — single‑pixel‑height div animating `width` |
+| Spinner (inline in URL field while loading) | `Spinner` | `apps/web/src/components/ui/spinner.tsx` | Wraps `Loader2Icon` from lucide |
+| Context menu (terminal link "Open in preview") | `localApi.contextMenu.show(...)` (already exists) | `apps/web/src/localApi.ts:58` | Native menu on desktop, fallback in `contextMenuFallback.ts` on web |
+| Keybinding shortcut label in tooltips | `shortcutLabelForCommand(keybindings, "preview.toggle")` | `apps/web/src/keybindings.ts` | Renders `⌘⇧J` etc. |
+| Right‑panel shell sizing | Match `DiffPanelShell` exactly: `w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border` | `apps/web/src/components/DiffPanelShell.tsx:32` | Single class string, do not reinvent |
**Icons.** Use `lucide-react` everywhere (already in `package.json`). The exact icons we need:
```ts
import {
- ArrowLeft, ArrowRight, // back / forward
- RotateCw, Loader2, // refresh / spinning
- Globe, // favicon fallback
- X, // close tab
- Plus, // new tab
- Copy, ExternalLink, // open in browser, copy URL
- Sidebar, Columns2, // right‑side toggles in tab strip (matches screenshot 2)
- PanelRightOpen, PanelRightClose, // alt for above
+ ArrowLeft,
+ ArrowRight, // back / forward
+ RotateCw,
+ Loader2, // refresh / spinning
+ Globe, // favicon fallback
+ X, // close tab
+ Plus, // new tab
+ Copy,
+ ExternalLink, // open in browser, copy URL
+ Sidebar,
+ Columns2, // right‑side toggles in tab strip (matches screenshot 2)
+ PanelRightOpen,
+ PanelRightClose, // alt for above
} from "lucide-react";
```
@@ -1200,11 +1209,11 @@ import {
Three states render inside `PreviewView.tsx` based on the `PreviewSession` for the active thread:
-| Session state | Component rendered |
-|---|---|
-| no tab open | `<PreviewEmptyState />` — disabled chrome row + "Local" recommendations |
-| tab loading / loaded | `<PreviewWebview />` + chrome row + tab strip |
-| tab navigation failed | `<PreviewUnreachable />` overlay above the webview |
+| Session state | Component rendered |
+| --------------------- | ----------------------------------------------------------------------- |
+| no tab open | `<PreviewEmptyState />` — disabled chrome row + "Local" recommendations |
+| tab loading / loaded | `<PreviewWebview />` + chrome row + tab strip |
+| tab navigation failed | `<PreviewUnreachable />` overlay above the webview |
### 15.1 Empty state (`PreviewEmptyState.tsx`) — matches screenshot 1
@@ -1259,9 +1268,7 @@ export function PreviewEmptyState({ threadId, onOpen }: Props) {
return (
<div className="flex h-full min-h-0 flex-col">
<div className="px-6 pt-10 pb-4">
- <h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
- Local
- </h2>
+ <h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Local</h2>
</div>
{servers.length === 0 ? (
@@ -1308,10 +1315,7 @@ function LocalServerCard({
{server.processName ?? `${server.host}:${server.port}`}
</span>
</div>
- <span
- className="size-2 shrink-0 rounded-full bg-success"
- aria-label="Listening"
- >
+ <span className="size-2 shrink-0 rounded-full bg-success" aria-label="Listening">
<span className="block size-2 rounded-full bg-success animate-ping opacity-60" />
</span>
</Card>
@@ -1362,8 +1366,8 @@ The chrome row in the empty state — note the `disabled` props on every interac
onForward={NOOP}
onRefresh={NOOP}
onSubmitUrl={(url) => api.preview.open({ threadId, url })}
- inputDisabled={false} // we still want to allow paste-to-open
- buttonsDisabled // back/fwd/refresh are visually disabled
+ inputDisabled={false} // we still want to allow paste-to-open
+ buttonsDisabled // back/fwd/refresh are visually disabled
/>
```
@@ -1568,17 +1572,17 @@ When `navStatus._tag === "LoadFailed"`, render this instead of the failed `<webv
Color mapping (Chromium → t3code theme):
-| Chromium | Tailwind/t3code |
-|---|---|
-| `--background-color: #fff` / `--google-gray-900` (dark) | `bg-background` |
-| `--text-color: --google-gray-700` / `--google-gray-500` (dark) | `text-muted-foreground` |
-| `--heading-color: --google-gray-900` / `--google-gray-500` (dark) | `text-foreground` |
-| `--error-code-color: --google-gray-700` / `--google-gray-500` (dark) | `text-muted-foreground/70` |
-| `--quiet-background-color: rgb(247,247,247)` / `--background` (dark) | `bg-muted/40` |
-| `--primary-button-fill-color: --google-blue-600` / `--google-blue-300` (dark) | `bg-primary text-primary-foreground` (theme primary is `oklch(0.488 0.217 264)` light / `oklch(0.588 0.217 264)` dark — a very close blue) |
-| `--secondary-button-*` | `Button variant="outline"` |
-| `--link-color: rgb(88,88,88)` / `--google-blue-300` (dark) | `text-primary underline-offset-4 hover:underline` |
-| Body font `system-ui, sans-serif; font-size: 75%` | We keep DM Sans (already in `apps/web/src/index.css:148`) and `text-sm` — the Chromium font tweak just compensates for their `html { font-size: 125% }` — we don't replicate that |
+| Chromium | Tailwind/t3code |
+| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `--background-color: #fff` / `--google-gray-900` (dark) | `bg-background` |
+| `--text-color: --google-gray-700` / `--google-gray-500` (dark) | `text-muted-foreground` |
+| `--heading-color: --google-gray-900` / `--google-gray-500` (dark) | `text-foreground` |
+| `--error-code-color: --google-gray-700` / `--google-gray-500` (dark) | `text-muted-foreground/70` |
+| `--quiet-background-color: rgb(247,247,247)` / `--background` (dark) | `bg-muted/40` |
+| `--primary-button-fill-color: --google-blue-600` / `--google-blue-300` (dark) | `bg-primary text-primary-foreground` (theme primary is `oklch(0.488 0.217 264)` light / `oklch(0.588 0.217 264)` dark — a very close blue) |
+| `--secondary-button-*` | `Button variant="outline"` |
+| `--link-color: rgb(88,88,88)` / `--google-blue-300` (dark) | `text-primary underline-offset-4 hover:underline` |
+| Body font `system-ui, sans-serif; font-size: 75%` | We keep DM Sans (already in `apps/web/src/index.css:148`) and `text-sm` — the Chromium font tweak just compensates for their `html { font-size: 125% }` — we don't replicate that |
Skeleton:
@@ -1592,7 +1596,7 @@ import { cn } from "~/lib/utils";
interface Props {
url: string;
- errorCode: string; // e.g. "ERR_NAME_NOT_RESOLVED", "ERR_CONNECTION_REFUSED"
+ errorCode: string; // e.g. "ERR_NAME_NOT_RESOLVED", "ERR_CONNECTION_REFUSED"
description: string;
onReload: () => void;
}
@@ -1601,7 +1605,13 @@ const ICON_GENERIC = (
// Replace with an inline SVG that matches the Chromium "icon-generic"
// (a stylized broken page). For v1 a Lucide MapPinOff is a fine stand-in —
// we want a visual that reads "destination unreachable".
- <svg viewBox="0 0 64 64" className="size-10 text-muted-foreground/70" fill="none" stroke="currentColor" strokeWidth="2.5">
+ <svg
+ viewBox="0 0 64 64"
+ className="size-10 text-muted-foreground/70"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ >
<path d="M16 12 L48 12 L48 52 L16 52 Z" />
<path d="M22 22 L42 22 M22 30 L36 30 M22 38 L40 38" strokeLinecap="round" />
<path d="M52 8 L12 56" strokeLinecap="round" />
@@ -1626,7 +1636,13 @@ export function PreviewUnreachable({ url, errorCode, description, onReload }: Pr
{/* Summary — uses dangerouslySetInnerHTML only for the bold host treatment */}
<p className="text-sm leading-relaxed text-muted-foreground">
<strong className="font-semibold text-foreground">{host}</strong>
- &rsquo;s server <abbr title="Domain Name System" className="cursor-help underline decoration-dotted underline-offset-2">DNS address</abbr>{" "}
+ &rsquo;s server{" "}
+ <abbr
+ title="Domain Name System"
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ DNS address
+ </abbr>{" "}
could not be found.
</p>
@@ -1668,11 +1684,16 @@ export function PreviewUnreachable({ url, errorCode, description, onReload }: Pr
}
function safeHost(url: string): string | null {
- try { return new URL(url).host; } catch { return null; }
+ try {
+ return new URL(url).host;
+ } catch {
+ return null;
+ }
}
```
The component intentionally:
+
- Uses theme tokens only — looks correct in light + dark with no extra wiring.
- Drops Chromium's "Diagnose connection" / "Portal sign-in" buttons (irrelevant in our shell).
- Drops the dinosaur game (RIP).
@@ -1683,15 +1704,17 @@ The component intentionally:
A 1.5px primary-colored bar that fills as the page loads, anchored to the bottom of the chrome row. Direct port of ami's pattern (`browser-view.tsx:434`):
```tsx
-{loadProgress > 0 && (
- <div
- className="pointer-events-none absolute bottom-0 left-0 z-10 h-0.5 rounded-full bg-primary transition-all duration-150 ease-out"
- style={{
- width: `${loadProgress}%`,
- boxShadow: "0 0 6px 1px var(--ring)",
- }}
- />
-)}
+{
+ loadProgress > 0 && (
+ <div
+ className="pointer-events-none absolute bottom-0 left-0 z-10 h-0.5 rounded-full bg-primary transition-all duration-150 ease-out"
+ style={{
+ width: `${loadProgress}%`,
+ boxShadow: "0 0 6px 1px var(--ring)",
+ }}
+ />
+ );
+}
```
Progress is computed locally with `useLoadingProgress(isLoading)` — same hook signature as ami's, ~30 lines.
@@ -1708,9 +1731,9 @@ The "Local" recommendations in §15.1 need a feed. New backend service.
import { Context, Effect } from "effect";
export interface DiscoveredLocalServer {
- host: string; // "localhost"
- port: number; // 5175
- url: string; // "http://localhost:5175"
+ host: string; // "localhost"
+ port: number; // 5175
+ url: string; // "http://localhost:5175"
processName: string | null; // "node", "vite", "next-server"
pid: number | null;
}
@@ -1740,6 +1763,7 @@ Two strategies, picked at startup:
2. **Fallback — TCP connect probe**: iterate a curated list of common dev ports `[3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000]` against `127.0.0.1`, mark any that accepts a connection. Used on Windows and as the safety net if `lsof` is missing.
Polling cadence:
+
- When `retain()` count is 0 → not polling.
- When ≥1 → poll every 3s. Diff against last result; only emit `subscribe` callbacks when the set differs.
- `retain()` returns a release fn that decrements the counter; goes idle automatically when the empty state is hidden.
@@ -1762,20 +1786,20 @@ Deduped by URL string. Sort: configured > listening > recent. This yields the "s
Append these to the file list:
-| File | Purpose |
-|---|---|
-| `apps/server/src/preview/Services/PortScanner.ts` | Service tag + interface |
-| `apps/server/src/preview/Layers/PortScanner.ts` | `lsof` strategy + TCP probe fallback + polling |
-| `apps/server/src/preview/Layers/PortScanner.test.ts` | Parser tests for `lsof -F pcn` output |
-| `apps/web/src/lib/favicon.ts` | `faviconUrlForOrigin(url, size)` helper |
-| `apps/web/src/components/preview/PreviewTabStrip.tsx` | Tab strip (screenshot 2) |
-| `apps/web/src/components/preview/TabFavicon.tsx` | Favicon `<img>` w/ `<Globe>` fallback |
-| `apps/web/src/components/preview/BrowserMockup.tsx` | Tiny tailwind browser thumbnail icon |
-| `apps/web/src/components/preview/PreviewLocalServerCard.tsx` | Card row for a discovered server |
-| `apps/web/src/components/preview/PreviewUnreachable.tsx` | 404.html rewritten in tailwind |
+| File | Purpose |
+| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
+| `apps/server/src/preview/Services/PortScanner.ts` | Service tag + interface |
+| `apps/server/src/preview/Layers/PortScanner.ts` | `lsof` strategy + TCP probe fallback + polling |
+| `apps/server/src/preview/Layers/PortScanner.test.ts` | Parser tests for `lsof -F pcn` output |
+| `apps/web/src/lib/favicon.ts` | `faviconUrlForOrigin(url, size)` helper |
+| `apps/web/src/components/preview/PreviewTabStrip.tsx` | Tab strip (screenshot 2) |
+| `apps/web/src/components/preview/TabFavicon.tsx` | Favicon `<img>` w/ `<Globe>` fallback |
+| `apps/web/src/components/preview/BrowserMockup.tsx` | Tiny tailwind browser thumbnail icon |
+| `apps/web/src/components/preview/PreviewLocalServerCard.tsx` | Card row for a discovered server |
+| `apps/web/src/components/preview/PreviewUnreachable.tsx` | 404.html rewritten in tailwind |
| `apps/web/src/components/preview/useDiscoveredLocalServers.ts` | Hook subscribing to `EnvironmentApi.preview.subscribePorts` + merging in `recentUrlsFromTerminal` and `ProjectScript.previewUrl` |
-| `apps/web/src/components/preview/useLoadingProgress.ts` | 30-line progress simulator (port of ami's) |
-| `apps/web/src/components/preview/errorCodeMessages.ts` | `ERR_*` → human-readable description map |
+| `apps/web/src/components/preview/useLoadingProgress.ts` | 30-line progress simulator (port of ami's) |
+| `apps/web/src/components/preview/errorCodeMessages.ts` | `ERR_*` → human-readable description map |
Update the contract additions in §4 to add:
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 40f840548..55b7b60e2 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -48,6 +48,7 @@ import {
setTheme,
showContextMenu,
} from "./methods/window.ts";
+import { previewMethods } from "./methods/preview.ts";
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
@@ -92,4 +93,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
+ for (const previewMethod of previewMethods) {
+ yield* ipc.handle(previewMethod);
+ }
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index 1ded238c6..7502831c0 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -39,3 +39,19 @@ export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mod
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
+export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
+export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
+export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
+export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
+export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
+export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
+export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
+export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
+export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
+export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
+export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
+export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
+export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
+export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
+export const PREVIEW_GET_BROWSER_PARTITION_CHANNEL = "desktop:preview-get-browser-partition";
+export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts
new file mode 100644
index 000000000..1b00eacdf
--- /dev/null
+++ b/apps/desktop/src/ipc/methods/preview.ts
@@ -0,0 +1,61 @@
+import * as Effect from "effect/Effect";
+import { BrowserWindow } from "electron";
+
+import { previewViewManager } from "../../preview-view-manager.ts";
+import * as IpcChannels from "../channels.ts";
+import type { DesktopIpcMethod } from "../DesktopIpc.ts";
+
+previewViewManager.getBrowserSession();
+previewViewManager.onStateChange((tabId, state) => {
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!window.isDestroyed()) {
+ window.webContents.send(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
+ }
+ }
+});
+
+const tabIdFrom = (raw: unknown): string => {
+ if (typeof raw !== "object" || raw === null || !("tabId" in raw)) {
+ throw new Error("preview tab id is required");
+ }
+ const tabId = raw.tabId;
+ if (typeof tabId !== "string" || tabId.trim().length === 0) {
+ throw new Error("preview tab id must be a non-empty string");
+ }
+ return tabId;
+};
+
+const method = (channel: string, handler: (raw: unknown) => unknown | Promise<unknown>): DesktopIpcMethod<unknown, never> => ({
+ channel,
+ handler: (raw) => Effect.tryPromise({ try: () => Promise.resolve(handler(raw)), catch: (error) => error }),
+});
+
+export const previewMethods = [
+ method(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, (raw) => previewViewManager.createTab(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, (raw) => previewViewManager.closeTab(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, (raw) => {
+ const tabId = tabIdFrom(raw);
+ const webContentsId = typeof raw === "object" && raw !== null && "webContentsId" in raw ? raw.webContentsId : null;
+ if (typeof webContentsId !== "number" || !Number.isInteger(webContentsId) || webContentsId <= 0) {
+ throw new Error("preview webContentsId must be a positive integer");
+ }
+ return previewViewManager.registerWebview(tabId, webContentsId);
+ }),
+ method(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, (raw) => {
+ const tabId = tabIdFrom(raw);
+ const url = typeof raw === "object" && raw !== null && "url" in raw ? raw.url : null;
+ if (typeof url !== "string") throw new Error("preview url must be a string");
+ return previewViewManager.navigate(tabId, url);
+ }),
+ method(IpcChannels.PREVIEW_GO_BACK_CHANNEL, (raw) => previewViewManager.goBack(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, (raw) => previewViewManager.goForward(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_REFRESH_CHANNEL, (raw) => previewViewManager.refresh(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, (raw) => previewViewManager.zoomIn(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, (raw) => previewViewManager.zoomOut(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, (raw) => previewViewManager.resetZoom(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, (raw) => previewViewManager.hardReload(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, (raw) => previewViewManager.openDevTools(tabIdFrom(raw))),
+ method(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, () => previewViewManager.clearCookies()),
+ method(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, () => previewViewManager.clearCache()),
+ method(IpcChannels.PREVIEW_GET_BROWSER_PARTITION_CHANNEL, () => previewViewManager.getBrowserPartition()),
+] as const;
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 84f7580cb..86a0ed576 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -1,4 +1,4 @@
-import type { DesktopBridge } from "@t3tools/contracts";
+import type { DesktopBridge, DesktopPreviewTabState } from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
@@ -141,4 +141,37 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
};
},
+ preview: {
+ createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
+ closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
+ registerWebview: (tabId, webContentsId) =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
+ navigate: (tabId, url) =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, { tabId, url }),
+ goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }),
+ goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }),
+ refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }),
+ zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }),
+ zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
+ resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
+ hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
+ openDevTools: (tabId) =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
+ clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
+ clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
+ getBrowserPartition: () =>
+ ipcRenderer.invoke(IpcChannels.PREVIEW_GET_BROWSER_PARTITION_CHANNEL),
+ onStateChange: (listener) => {
+ const wrappedListener = (
+ _event: Electron.IpcRendererEvent,
+ tabId: unknown,
+ state: unknown,
+ ) => {
+ if (typeof tabId !== "string" || typeof state !== "object" || state === null) return;
+ listener(tabId, state as DesktopPreviewTabState);
+ };
+ ipcRenderer.on(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
+ return () => ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
+ },
+ },
} satisfies DesktopBridge);
diff --git a/apps/desktop/src/preview-view-manager.ts b/apps/desktop/src/preview-view-manager.ts
new file mode 100644
index 000000000..6e27850bd
--- /dev/null
+++ b/apps/desktop/src/preview-view-manager.ts
@@ -0,0 +1,455 @@
+/**
+ * PreviewViewManager — desktop side of the in-app browser preview.
+ *
+ * Hosts per-tab Chromium WebContents references (the actual <webview>
+ * elements live in the renderer; we only attach listeners and forward state
+ * here). Single layer-scoped browser session partition.
+ */
+import { normalizePreviewUrl } from "@t3tools/shared/preview";
+import { type BrowserWindow, type Session, session, webContents } from "electron";
+
+const PREVIEW_PARTITION = "persist:t3code-preview";
+
+export type PreviewNavStatus =
+ | { kind: "Idle" }
+ | { kind: "Loading"; url: string; title: string }
+ | { kind: "Success"; url: string; title: string }
+ | {
+ kind: "LoadFailed";
+ url: string;
+ title: string;
+ code: number;
+ description: string;
+ };
+
+export interface PreviewTabState {
+ tabId: string;
+ webContentsId: number | null;
+ navStatus: PreviewNavStatus;
+ canGoBack: boolean;
+ canGoForward: boolean;
+ zoomFactor: number;
+ updatedAt: string;
+}
+
+/** Discrete zoom levels mirroring Chrome's preset list. */
+const ZOOM_LEVELS: ReadonlyArray<number> = [
+ 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0,
+];
+
+const DEFAULT_ZOOM_FACTOR = 1.0;
+const ZOOM_EPSILON = 0.001;
+
+const findZoomStep = (current: number): number => {
+ for (let index = 0; index < ZOOM_LEVELS.length; index += 1) {
+ if (Math.abs(ZOOM_LEVELS[index]! - current) < ZOOM_EPSILON) return index;
+ if (ZOOM_LEVELS[index]! > current) return index - 1;
+ }
+ return ZOOM_LEVELS.length - 1;
+};
+
+const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
+ const step = findZoomStep(current);
+ if (direction === "in") {
+ return ZOOM_LEVELS[Math.min(step + 1, ZOOM_LEVELS.length - 1)] ?? current;
+ }
+ return ZOOM_LEVELS[Math.max(step - 1, 0)] ?? current;
+};
+
+type Listener = (tabId: string, state: PreviewTabState) => void;
+
+interface ManagedListeners {
+ navigate: () => void;
+ failed: (event: Event, code: number, description: string) => void;
+}
+
+const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
+ key: string;
+ meta: boolean;
+ shift: boolean;
+ control: boolean;
+}> = Object.freeze([
+ // mod+shift+J → preview.toggle
+ { key: "j", meta: true, shift: true, control: false },
+ // mod+K → command palette
+ { key: "k", meta: true, shift: false, control: false },
+ // mod+, → settings (macOS convention)
+ { key: ",", meta: true, shift: false, control: false },
+ // mod+W → close tab/panel
+ { key: "w", meta: true, shift: false, control: false },
+]);
+
+export class PreviewViewManager {
+ private mainWindow: BrowserWindow | null = null;
+ private readonly tabs = new Map<string, PreviewTabState>();
+ private readonly attached = new Map<number, ManagedListeners>();
+ private browserSession: Session | null = null;
+ private readonly listeners = new Set<Listener>();
+
+ setMainWindow(window: BrowserWindow): void {
+ this.mainWindow = window;
+ }
+
+ getBrowserPartition(): string {
+ return PREVIEW_PARTITION;
+ }
+
+ getBrowserSession(): Session {
+ if (this.browserSession) return this.browserSession;
+ const sess = session.fromPartition(PREVIEW_PARTITION);
+ const ua = sess
+ .getUserAgent()
+ .replace(/Electron\/[\d.]+ /, "")
+ .replace(/\s*t3code\/[\d.]+/, "");
+ sess.setUserAgent(ua);
+ sess.setPermissionRequestHandler((_wc, perm, callback) => {
+ const allow = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
+ callback(allow.includes(perm));
+ });
+ this.browserSession = sess;
+ return sess;
+ }
+
+ createTab(tabId: string): PreviewTabState {
+ const existing = this.tabs.get(tabId);
+ if (existing) return existing;
+ const initial: PreviewTabState = {
+ tabId,
+ webContentsId: null,
+ navStatus: { kind: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ zoomFactor: DEFAULT_ZOOM_FACTOR,
+ updatedAt: new Date().toISOString(),
+ };
+ this.tabs.set(tabId, initial);
+ this.emit(tabId, initial);
+ return initial;
+ }
+
+ closeTab(tabId: string): void {
+ const tab = this.tabs.get(tabId);
+ if (!tab) return;
+ if (tab.webContentsId != null) {
+ this.detachListeners(tab.webContentsId);
+ }
+ const closed: PreviewTabState = {
+ ...tab,
+ webContentsId: null,
+ navStatus: { kind: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ zoomFactor: DEFAULT_ZOOM_FACTOR,
+ updatedAt: new Date().toISOString(),
+ };
+ this.tabs.delete(tabId);
+ this.emit(tabId, closed);
+ }
+
+ registerWebview(tabId: string, webContentsId: number): void {
+ const tab = this.tabs.get(tabId);
+ if (!tab) {
+ throw new PreviewTabNotFoundError(tabId);
+ }
+ const wc = webContents.fromId(webContentsId);
+ if (!wc) {
+ throw new PreviewWebContentsNotFoundError(tabId, webContentsId);
+ }
+ // Defence in depth: a malicious renderer could otherwise trick us into
+ // attaching listeners to the main window's WebContents (or any other
+ // process) by passing an arbitrary id.
+ if (wc.getType() !== "webview") {
+ throw new PreviewWebContentsNotFoundError(tabId, webContentsId);
+ }
+ if (this.mainWindow && wc.hostWebContents !== this.mainWindow.webContents) {
+ throw new PreviewWebContentsNotFoundError(tabId, webContentsId);
+ }
+ if (tab.webContentsId === webContentsId && this.attached.has(webContentsId)) {
+ return;
+ }
+ if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
+ this.detachListeners(tab.webContentsId);
+ }
+ this.attachListeners(tabId, wc);
+ // Restore the persisted zoom factor onto the freshly-attached WebContents
+ // so a thread-switch + remount lands the user back where they were.
+ if (Math.abs(tab.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
+ try {
+ wc.setZoomFactor(tab.zoomFactor);
+ } catch {
+ // wc may have been torn down between resolution and call.
+ }
+ }
+ this.update(tabId, {
+ webContentsId,
+ navStatus: this.computeNavStatus(wc),
+ canGoBack: wc.navigationHistory.canGoBack(),
+ canGoForward: wc.navigationHistory.canGoForward(),
+ zoomFactor: tab.zoomFactor,
+ });
+ }
+
+ async navigate(tabId: string, rawUrl: string): Promise<void> {
+ const wc = this.requireWebContents(tabId);
+ const url = this.normalizeUrl(rawUrl);
+ if (wc.getURL() === url) {
+ wc.reload();
+ return;
+ }
+ await wc.loadURL(url);
+ }
+
+ goBack(tabId: string): void {
+ const wc = this.requireWebContents(tabId);
+ if (wc.navigationHistory.canGoBack()) {
+ wc.navigationHistory.goBack();
+ }
+ }
+
+ goForward(tabId: string): void {
+ const wc = this.requireWebContents(tabId);
+ if (wc.navigationHistory.canGoForward()) {
+ wc.navigationHistory.goForward();
+ }
+ }
+
+ refresh(tabId: string): void {
+ const wc = this.requireWebContents(tabId);
+ wc.reload();
+ }
+
+ /** Bypass HTTP cache on the next load — equivalent to Cmd+Shift+R. */
+ hardReload(tabId: string): void {
+ const wc = this.requireWebContents(tabId);
+ wc.reloadIgnoringCache();
+ }
+
+ /**
+ * Open the guest webview's DevTools, detached so it doesn't steal panel
+ * area. Idempotent — re-invoking focuses the existing window.
+ */
+ openDevTools(tabId: string): void {
+ const wc = this.requireWebContents(tabId);
+ if (wc.isDevToolsOpened()) {
+ wc.devToolsWebContents?.focus();
+ return;
+ }
+ wc.openDevTools({ mode: "detach" });
+ }
+
+ /**
+ * Drop cookies/localStorage/etc. for the preview partition. Affects every
+ * preview tab since they all share `persist:t3code-preview`.
+ */
+ async clearCookies(): Promise<void> {
+ const sess = this.getBrowserSession();
+ await sess.clearStorageData({
+ storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
+ });
+ }
+
+ /** Drop the HTTP cache for the preview partition. */
+ async clearCache(): Promise<void> {
+ const sess = this.getBrowserSession();
+ await sess.clearCache();
+ }
+
+ zoomIn(tabId: string): void {
+ this.applyZoom(tabId, (current) => nextZoomLevel(current, "in"));
+ }
+
+ zoomOut(tabId: string): void {
+ this.applyZoom(tabId, (current) => nextZoomLevel(current, "out"));
+ }
+
+ resetZoom(tabId: string): void {
+ this.applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR);
+ }
+
+ private applyZoom(tabId: string, transform: (current: number) => number): void {
+ const tab = this.tabs.get(tabId);
+ if (!tab) return;
+ const next = transform(tab.zoomFactor);
+ if (Math.abs(next - tab.zoomFactor) < ZOOM_EPSILON) return;
+ if (tab.webContentsId != null) {
+ const wc = webContents.fromId(tab.webContentsId);
+ if (wc && !wc.isDestroyed()) {
+ wc.setZoomFactor(next);
+ }
+ }
+ this.update(tabId, { zoomFactor: next });
+ }
+
+ onStateChange(listener: Listener): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ destroy(): void {
+ for (const tabId of Array.from(this.tabs.keys())) {
+ this.closeTab(tabId);
+ }
+ this.listeners.clear();
+ }
+
+ private attachListeners(tabId: string, wc: Electron.WebContents): void {
+ const sync = () => {
+ if (wc.isDestroyed()) return;
+ this.update(tabId, {
+ navStatus: this.computeNavStatus(wc),
+ canGoBack: wc.navigationHistory.canGoBack(),
+ canGoForward: wc.navigationHistory.canGoForward(),
+ });
+ };
+ const failed = (_event: Event, code: number, description: string): void => {
+ // -3 = ABORTED (user navigated away mid-load); ignore.
+ if (code === -3) return;
+ this.update(tabId, {
+ navStatus: {
+ kind: "LoadFailed",
+ url: wc.getURL(),
+ title: wc.getTitle(),
+ code,
+ description,
+ },
+ });
+ };
+
+ wc.on("did-navigate", sync);
+ wc.on("did-navigate-in-page", sync);
+ wc.on("page-title-updated", sync);
+ wc.on("did-start-loading", sync);
+ wc.on("did-stop-loading", sync);
+ wc.on("did-fail-load", failed as never);
+
+ // Keep external links inside the same view (matches ami's policy).
+ wc.setWindowOpenHandler(({ url }) => {
+ void wc.loadURL(url);
+ return { action: "deny" };
+ });
+
+ // Forward app-level shortcuts to the main window so mod+shift+J etc.
+ // still toggles the preview panel even when the webview has focus.
+ wc.on("before-input-event", (event, input) => {
+ if (this.isAppShortcut(input) && this.mainWindow && !this.mainWindow.isDestroyed()) {
+ event.preventDefault();
+ this.mainWindow.webContents.sendInputEvent({
+ type: "keyDown",
+ keyCode: input.key,
+ modifiers: [
+ ...(input.meta ? (["meta"] as const) : []),
+ ...(input.shift ? (["shift"] as const) : []),
+ ...(input.control ? (["control"] as const) : []),
+ ...(input.alt ? (["alt"] as const) : []),
+ ],
+ });
+ }
+ });
+
+ this.attached.set(wc.id, { navigate: sync, failed });
+ }
+
+ private detachListeners(webContentsId: number): void {
+ const handlers = this.attached.get(webContentsId);
+ if (!handlers) return;
+ this.attached.delete(webContentsId);
+ const wc = webContents.fromId(webContentsId);
+ if (!wc || wc.isDestroyed()) return;
+ wc.off("did-navigate", handlers.navigate);
+ wc.off("did-navigate-in-page", handlers.navigate);
+ wc.off("page-title-updated", handlers.navigate);
+ wc.off("did-start-loading", handlers.navigate);
+ wc.off("did-stop-loading", handlers.navigate);
+ wc.off("did-fail-load", handlers.failed as never);
+ }
+
+ private isAppShortcut(input: Electron.Input): boolean {
+ if (input.type !== "keyDown") return false;
+ return APP_FORWARDED_SHORTCUTS.some(
+ (shortcut) =>
+ shortcut.key.toLowerCase() === input.key.toLowerCase() &&
+ shortcut.meta === input.meta &&
+ shortcut.shift === input.shift &&
+ shortcut.control === input.control,
+ );
+ }
+
+ private computeNavStatus(wc: Electron.WebContents): PreviewNavStatus {
+ const url = wc.getURL();
+ const title = wc.getTitle();
+ if (url === "" || url === "about:blank") return { kind: "Idle" };
+ if (wc.isLoading()) return { kind: "Loading", url, title };
+ return { kind: "Success", url, title };
+ }
+
+ private requireWebContents(tabId: string): Electron.WebContents {
+ const tab = this.tabs.get(tabId);
+ if (!tab) throw new PreviewTabNotFoundError(tabId);
+ if (tab.webContentsId == null) throw new PreviewWebviewNotInitializedError(tabId);
+ const wc = webContents.fromId(tab.webContentsId);
+ if (!wc) throw new PreviewWebContentsNotFoundError(tabId, tab.webContentsId);
+ return wc;
+ }
+
+ private update(tabId: string, patch: Partial<PreviewTabState>): void {
+ const current = this.tabs.get(tabId);
+ if (!current) return;
+ const next: PreviewTabState = {
+ ...current,
+ ...patch,
+ updatedAt: new Date().toISOString(),
+ };
+ this.tabs.set(tabId, next);
+ this.emit(tabId, next);
+ }
+
+ private emit(tabId: string, state: PreviewTabState): void {
+ for (const listener of this.listeners) {
+ try {
+ listener(tabId, state);
+ } catch {
+ // listener errors must not crash the manager
+ }
+ }
+ }
+
+ private normalizeUrl(input: string): string {
+ // Surface the shared error directly so the IPC caller (and any future
+ // desktop-side telemetry) gets the `detail` field for free. Defining a
+ // bespoke desktop class would just lose information.
+ return normalizePreviewUrl(input);
+ }
+}
+
+export class PreviewTabNotFoundError extends Error {
+ readonly tabId: string;
+ constructor(tabId: string) {
+ super(`Preview tab not found: ${tabId}`);
+ this.name = "PreviewTabNotFoundError";
+ this.tabId = tabId;
+ }
+}
+
+export class PreviewWebContentsNotFoundError extends Error {
+ readonly tabId: string;
+ readonly webContentsId: number;
+ constructor(tabId: string, webContentsId: number) {
+ super(`WebContents ${webContentsId} not found for preview tab ${tabId}`);
+ this.name = "PreviewWebContentsNotFoundError";
+ this.tabId = tabId;
+ this.webContentsId = webContentsId;
+ }
+}
+
+export class PreviewWebviewNotInitializedError extends Error {
+ readonly tabId: string;
+ constructor(tabId: string) {
+ super(`Preview tab "${tabId}" has no webview registered`);
+ this.name = "PreviewWebviewNotInitializedError";
+ this.tabId = tabId;
+ }
+}
+
+export const previewViewManager = new PreviewViewManager();
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 35145cc1d..6a4981367 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -11,6 +11,7 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
+import { previewViewManager } from "../preview-view-manager.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -192,9 +193,12 @@ const make = Effect.gen(function* () {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
+ webviewTag: true,
},
});
+ previewViewManager.setMainWindow(window);
+
window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
diff --git a/apps/server/src/preview/Layers/Manager.test.ts b/apps/server/src/preview/Layers/Manager.test.ts
new file mode 100644
index 000000000..197b79d56
--- /dev/null
+++ b/apps/server/src/preview/Layers/Manager.test.ts
@@ -0,0 +1,261 @@
+import { it } from "@effect/vitest";
+import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
+import { Effect, PubSub } from "effect";
+import { expect } from "vitest";
+
+import { PreviewManager } from "../Services/Manager.ts";
+import { PreviewManagerLive } from "./Manager.ts";
+
+const DRAIN_LIMIT = 100;
+
+interface EventCollector {
+ /** Drain everything published since the last call (or since subscribe). */
+ readonly drain: Effect.Effect<ReadonlyArray<PreviewEvent>>;
+}
+
+/**
+ * Each `it.effect` shares the live PreviewManager layer across the whole
+ * `it.layer` block, so tests that assert per-thread counts must use a unique
+ * thread id to avoid bleeding state from earlier tests.
+ */
+let nextThreadId = 0;
+const freshThreadId = () => ThreadId.make(`thread-${++nextThreadId}`);
+
+/**
+ * Subscribe to the manager's event stream BEFORE the test publishes. We
+ * use `subscribeEvents` (synchronous PubSub.subscribe under the hood) so
+ * no event can land between subscribe and the consumer drain.
+ */
+const collectEvents = Effect.gen(function* () {
+ const manager = yield* PreviewManager;
+ const subscription = yield* manager.subscribeEvents;
+ const collector: EventCollector = {
+ drain: PubSub.takeUpTo(subscription, DRAIN_LIMIT),
+ };
+ return collector;
+}).pipe(Effect.withSpan("preview.test.collectEvents"));
+
+it.layer(PreviewManagerLive)("PreviewManager", (it) => {
+ it.effect("opens a session and emits opened with normalized URL", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const collector = yield* collectEvents;
+
+ const snapshot = yield* manager.open({ threadId, url: "localhost:5173" });
+ expect(snapshot.tabId.startsWith("tab_")).toBe(true);
+ expect(snapshot.navStatus._tag).toBe("Loading");
+ if (snapshot.navStatus._tag === "Loading") {
+ expect(snapshot.navStatus.url).toBe("http://localhost:5173/");
+ }
+
+ const events = yield* collector.drain;
+ expect(events).toHaveLength(1);
+ expect(events[0]?.type).toBe("opened");
+ if (events[0]?.type === "opened") {
+ expect(events[0].tabId).toBe(snapshot.tabId);
+ }
+ }),
+ );
+
+ it.effect("opens an Idle tab when no URL is supplied", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const snapshot = yield* manager.open({ threadId });
+ expect(snapshot.navStatus._tag).toBe("Idle");
+ }),
+ );
+
+ it.effect("treats bare hosts as https", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const snapshot = yield* manager.open({ threadId, url: "example.com" });
+ if (snapshot.navStatus._tag === "Loading") {
+ expect(snapshot.navStatus.url).toBe("https://example.com/");
+ }
+ }),
+ );
+
+ it.effect("rejects empty URL with PreviewInvalidUrlError", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const error = yield* Effect.flip(manager.open({ threadId, url: " " }));
+ expect(error._tag).toBe("PreviewInvalidUrlError");
+ }),
+ );
+
+ it.effect("navigate updates snapshot and emits navigated", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const collector = yield* collectEvents;
+
+ const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
+ const snapshot = yield* manager.navigate({
+ threadId,
+ tabId: opened.tabId,
+ url: "http://localhost:5173/about",
+ resolvedTitle: "About",
+ });
+
+ expect(snapshot.navStatus._tag).toBe("Success");
+ if (snapshot.navStatus._tag === "Success") {
+ expect(snapshot.navStatus.url).toBe("http://localhost:5173/about");
+ expect(snapshot.navStatus.title).toBe("About");
+ }
+ const events = yield* collector.drain;
+ expect(events.map((e) => e.type)).toEqual(["opened", "navigated"]);
+ }),
+ );
+
+ it.effect("navigate fails for unknown tab", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const error = yield* Effect.flip(
+ manager.navigate({
+ threadId,
+ tabId: "tab_missing",
+ url: "http://localhost:5173",
+ }),
+ );
+ expect(error._tag).toBe("PreviewSessionLookupError");
+ }),
+ );
+
+ it.effect("reportStatus emits failed for LoadFailed nav", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const collector = yield* collectEvents;
+
+ const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
+ yield* manager.reportStatus({
+ threadId,
+ tabId: opened.tabId,
+ navStatus: {
+ _tag: "LoadFailed",
+ url: "http://localhost:5173",
+ title: "",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ },
+ canGoBack: false,
+ canGoForward: false,
+ });
+
+ const events = yield* collector.drain;
+ const failed = events.find((e) => e.type === "failed");
+ expect(failed?.type).toBe("failed");
+ if (failed?.type === "failed") {
+ expect(failed.code).toBe(-105);
+ expect(failed.description).toBe("ERR_NAME_NOT_RESOLVED");
+ }
+ }),
+ );
+
+ it.effect("close removes the session and emits closed", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const collector = yield* collectEvents;
+
+ yield* manager.open({ threadId, url: "http://localhost:5173" });
+ yield* manager.close({ threadId });
+
+ const result = yield* manager.list({ threadId });
+ expect(result.sessions).toHaveLength(0);
+ const events = yield* collector.drain;
+ const closed = events.find((e) => e.type === "closed");
+ expect(closed?.type).toBe("closed");
+ }),
+ );
+
+ it.effect("close is idempotent for unknown threads", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ yield* manager.close({ threadId });
+ const result = yield* manager.list({ threadId });
+ expect(result.sessions).toHaveLength(0);
+ }),
+ );
+
+ it.effect("list returns every snapshot for the thread sorted by updatedAt", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const first = yield* manager.open({ threadId, url: "http://localhost:5173" });
+ const second = yield* manager.open({ threadId, url: "http://localhost:3000" });
+ const result = yield* manager.list({ threadId });
+ expect(result.sessions).toHaveLength(2);
+ const ids = result.sessions.map((s) => s.tabId);
+ expect(ids).toContain(first.tabId);
+ expect(ids).toContain(second.tabId);
+ }),
+ );
+
+ it.effect("open creates an independent tab on every call", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const collector = yield* collectEvents;
+
+ const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
+ const b = yield* manager.open({ threadId, url: "http://localhost:3000/path" });
+
+ expect(a.tabId).not.toBe(b.tabId);
+ const list = yield* manager.list({ threadId });
+ expect(list.sessions).toHaveLength(2);
+
+ const events = yield* collector.drain;
+ expect(events.map((e) => e.type)).toEqual(["opened", "opened"]);
+ }),
+ );
+
+ it.effect("close with mismatching tabId is a no-op", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ yield* manager.open({ threadId, url: "http://localhost:5173" });
+ yield* manager.close({ threadId, tabId: "tab_missing" });
+
+ const list = yield* manager.list({ threadId });
+ expect(list.sessions).toHaveLength(1);
+ }),
+ );
+
+ it.effect("close with explicit tabId removes only that tab", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
+ const b = yield* manager.open({ threadId, url: "http://localhost:3000" });
+
+ yield* manager.close({ threadId, tabId: a.tabId });
+
+ const list = yield* manager.list({ threadId });
+ expect(list.sessions.map((s) => s.tabId)).toEqual([b.tabId]);
+ }),
+ );
+
+ it.effect("multiple subscribers receive every event independently", () =>
+ Effect.gen(function* () {
+ const threadId = freshThreadId();
+ const manager = yield* PreviewManager;
+ const aSub = yield* manager.subscribeEvents;
+ const bSub = yield* manager.subscribeEvents;
+
+ yield* manager.open({ threadId, url: "http://localhost:5173" });
+ yield* manager.open({ threadId, url: "http://localhost:3000" });
+
+ const aEvents = yield* PubSub.takeUpTo(aSub, DRAIN_LIMIT);
+ const bEvents = yield* PubSub.takeUpTo(bSub, DRAIN_LIMIT);
+ expect(aEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
+ expect(bEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
+ }),
+ );
+});
diff --git a/apps/server/src/preview/Layers/Manager.ts b/apps/server/src/preview/Layers/Manager.ts
new file mode 100644
index 000000000..3a70f0dce
--- /dev/null
+++ b/apps/server/src/preview/Layers/Manager.ts
@@ -0,0 +1,313 @@
+/**
+ * In-memory PreviewManager implementation.
+ *
+ * Sessions are keyed by `(threadId, tabId)`; a single thread can host
+ * multiple tabs (browser-style). `open` always creates a new tab — tab
+ * lifecycle is owned by the renderer.
+ *
+ * Events are published via Effect's `PubSub`, so subscriber failures are
+ * isolated from the publishing call (a closed WS subscriber queue cannot
+ * fail an in-progress `navigate()`).
+ */
+import {
+ type PreviewEvent,
+ PreviewInvalidUrlError,
+ type PreviewListResult,
+ PreviewSessionLookupError,
+ type PreviewSessionSnapshot,
+} from "@t3tools/contracts";
+import {
+ newPreviewTabId,
+ normalizePreviewUrl,
+ PreviewUrlNormalizationError,
+} from "@t3tools/shared/preview";
+import { Effect, Layer, PubSub, Stream, SynchronizedRef } from "effect";
+
+import { PreviewManager, type PreviewManagerShape } from "../Services/Manager.ts";
+
+interface PreviewSessionState {
+ readonly threadId: string;
+ readonly tabId: string;
+ readonly snapshot: PreviewSessionSnapshot;
+}
+
+interface ManagerState {
+ /** All sessions across every thread, keyed by `${threadId}\u0000${tabId}`. */
+ readonly sessions: ReadonlyMap<string, PreviewSessionState>;
+}
+
+const initialState: ManagerState = { sessions: new Map() };
+
+const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
+
+const sessionsForThread = (
+ state: ManagerState,
+ threadId: string,
+): ReadonlyArray<PreviewSessionState> => {
+ const out: PreviewSessionState[] = [];
+ for (const session of state.sessions.values()) {
+ if (session.threadId === threadId) out.push(session);
+ }
+ return out;
+};
+
+const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
+ Effect.try({
+ try: () => normalizePreviewUrl(rawUrl),
+ catch: (cause) =>
+ new PreviewInvalidUrlError({
+ rawUrl,
+ detail:
+ cause instanceof PreviewUrlNormalizationError
+ ? cause.detail
+ : cause instanceof Error
+ ? cause.message
+ : String(cause),
+ }),
+ });
+
+const buildLoadingSnapshot = (input: {
+ readonly threadId: string;
+ readonly tabId: string;
+ readonly url: string;
+ readonly title: string;
+}): PreviewSessionSnapshot => ({
+ threadId: input.threadId,
+ tabId: input.tabId,
+ navStatus: { _tag: "Loading", url: input.url, title: input.title },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: new Date().toISOString(),
+});
+
+const buildIdleSnapshot = (input: {
+ readonly threadId: string;
+ readonly tabId: string;
+}): PreviewSessionSnapshot => ({
+ threadId: input.threadId,
+ tabId: input.tabId,
+ navStatus: { _tag: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: new Date().toISOString(),
+});
+
+export const makePreviewManager = Effect.gen(function* () {
+ const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
+ // Unbounded PubSub is fine here — events are tiny and we don't want to
+ // block publishers if a subscriber is slow. WS clients backpressure on
+ // their own queues downstream.
+ const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
+ const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
+
+ /**
+ * Atomic read-modify-write over the session for `(threadId, tabId)`. The
+ * mutator runs under the SynchronizedRef so concurrent writers cannot
+ * interleave. Lookup failures travel through the modify result so both
+ * branches yield the same `[A, S]` shape `modifyEffect` requires.
+ *
+ * The event is published INSIDE the lock so observers see events in the
+ * same order as the underlying state transitions. Publishing an unbounded
+ * PubSub is non-blocking, so this is cheap.
+ */
+ const mutateExistingSession = <R, E>(
+ threadId: string,
+ tabId: string,
+ mutator: (
+ session: PreviewSessionState,
+ ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEvent | null; result: R }, E>,
+ ): Effect.Effect<R, E | PreviewSessionLookupError> => {
+ type ModifyResult =
+ | { kind: "fail"; error: PreviewSessionLookupError }
+ | { kind: "ok"; result: R };
+
+ return SynchronizedRef.modifyEffect(stateRef, (state) => {
+ const session = state.sessions.get(compositeKey(threadId, tabId));
+ if (!session) {
+ return Effect.succeed([
+ { kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
+ state,
+ ] as readonly [ModifyResult, ManagerState]);
+ }
+ return mutator(session).pipe(
+ Effect.flatMap(({ next, emit, result }) =>
+ Effect.gen(function* () {
+ if (emit) yield* PubSub.publish(eventsPubSub, emit);
+ const sessions = new Map(state.sessions);
+ sessions.set(compositeKey(threadId, tabId), next);
+ return [{ kind: "ok", result } as ModifyResult, { sessions }] as readonly [
+ ModifyResult,
+ ManagerState,
+ ];
+ }),
+ ),
+ );
+ }).pipe(
+ Effect.flatMap((modify) =>
+ modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
+ ),
+ );
+ };
+
+ const open: PreviewManagerShape["open"] = (input) =>
+ Effect.gen(function* () {
+ const tabId = newPreviewTabId();
+ const snapshot = input.url
+ ? buildLoadingSnapshot({
+ threadId: input.threadId,
+ tabId,
+ url: yield* normalizeUrl(input.url),
+ title: "",
+ })
+ : buildIdleSnapshot({ threadId: input.threadId, tabId });
+ yield* SynchronizedRef.update(stateRef, (state) => {
+ const sessions = new Map(state.sessions);
+ sessions.set(compositeKey(input.threadId, tabId), {
+ threadId: input.threadId,
+ tabId,
+ snapshot,
+ });
+ return { sessions };
+ });
+ yield* PubSub.publish(eventsPubSub, {
+ type: "opened",
+ threadId: input.threadId,
+ tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ return snapshot;
+ });
+
+ const navigate: PreviewManagerShape["navigate"] = (input) =>
+ Effect.gen(function* () {
+ const url = yield* normalizeUrl(input.url);
+ return yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
+ Effect.sync(() => {
+ const previousTitle =
+ session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
+ const resolvedTitle = input.resolvedTitle ?? previousTitle;
+ const snapshot: PreviewSessionSnapshot = {
+ threadId: session.threadId,
+ tabId: session.tabId,
+ navStatus: { _tag: "Success", url, title: resolvedTitle },
+ canGoBack: session.snapshot.canGoBack,
+ canGoForward: session.snapshot.canGoForward,
+ updatedAt: new Date().toISOString(),
+ };
+ return {
+ next: { ...session, snapshot },
+ emit: {
+ type: "navigated",
+ threadId: session.threadId,
+ tabId: session.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ },
+ result: snapshot,
+ };
+ }),
+ );
+ });
+
+ const reportStatus: PreviewManagerShape["reportStatus"] = (input) =>
+ mutateExistingSession(input.threadId, input.tabId, (session) =>
+ Effect.sync(() => {
+ const snapshot: PreviewSessionSnapshot = {
+ threadId: session.threadId,
+ tabId: session.tabId,
+ navStatus: input.navStatus,
+ canGoBack: input.canGoBack,
+ canGoForward: input.canGoForward,
+ updatedAt: new Date().toISOString(),
+ };
+ const emit: PreviewEvent =
+ input.navStatus._tag === "LoadFailed"
+ ? {
+ type: "failed",
+ threadId: session.threadId,
+ tabId: session.tabId,
+ createdAt: snapshot.updatedAt,
+ url: input.navStatus.url,
+ title: input.navStatus.title,
+ code: input.navStatus.code,
+ description: input.navStatus.description,
+ }
+ : {
+ type: "navigated",
+ threadId: session.threadId,
+ tabId: session.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ };
+ return {
+ next: { ...session, snapshot },
+ emit,
+ result: undefined as void,
+ };
+ }),
+ );
+
+ const refresh: PreviewManagerShape["refresh"] = (input) =>
+ // Verify the session exists; the desktop bridge handles the actual reload
+ // and will report progress back via `reportStatus`. No event emitted.
+ mutateExistingSession(input.threadId, input.tabId, (session) =>
+ Effect.succeed({ next: session, emit: null, result: undefined as void }),
+ );
+
+ const close: PreviewManagerShape["close"] = (input) =>
+ Effect.flatMap(
+ SynchronizedRef.modify(stateRef, (state) => {
+ const eventsToEmit: PreviewEvent[] = [];
+ const sessions = new Map(state.sessions);
+ const targets = input.tabId
+ ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
+ (entry): entry is PreviewSessionState => entry !== undefined,
+ )
+ : sessionsForThread(state, input.threadId);
+ for (const target of targets) {
+ sessions.delete(compositeKey(target.threadId, target.tabId));
+ eventsToEmit.push({
+ type: "closed",
+ threadId: target.threadId,
+ tabId: target.tabId,
+ createdAt: new Date().toISOString(),
+ });
+ }
+ if (eventsToEmit.length === 0) {
+ return [eventsToEmit, state] as const;
+ }
+ return [eventsToEmit, { sessions }] as const;
+ }),
+ (events) =>
+ events.length === 0
+ ? Effect.void
+ : Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
+ discard: true,
+ }),
+ );
+
+ const list: PreviewManagerShape["list"] = (input) =>
+ SynchronizedRef.get(stateRef).pipe(
+ Effect.map(
+ (state): PreviewListResult => ({
+ sessions: sessionsForThread(state, input.threadId)
+ .map((s) => s.snapshot)
+ .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
+ }),
+ ),
+ );
+
+ return {
+ open,
+ navigate,
+ reportStatus,
+ refresh,
+ close,
+ list,
+ events,
+ subscribeEvents: PubSub.subscribe(eventsPubSub),
+ } satisfies PreviewManagerShape;
+});
+
+export const PreviewManagerLive = Layer.effect(PreviewManager, makePreviewManager);
diff --git a/apps/server/src/preview/Layers/PortScanner.test.ts b/apps/server/src/preview/Layers/PortScanner.test.ts
new file mode 100644
index 000000000..b81103c15
--- /dev/null
+++ b/apps/server/src/preview/Layers/PortScanner.test.ts
@@ -0,0 +1,180 @@
+import * as net from "node:net";
+
+import { Effect } from "effect";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { PreviewPortScanner } from "../Services/PortScanner.ts";
+import { __testing, PreviewPortScannerLive } from "./PortScanner.ts";
+
+const { parseLsofOutput, parsePortFromLsofName, serversEqual } = __testing;
+
+describe("parsePortFromLsofName", () => {
+ it("parses *:port", () => {
+ expect(parsePortFromLsofName("*:5173")).toBe(5173);
+ });
+
+ it("parses 127.0.0.1:port", () => {
+ expect(parsePortFromLsofName("127.0.0.1:5173")).toBe(5173);
+ });
+
+ it("parses localhost:port", () => {
+ expect(parsePortFromLsofName("localhost:5173")).toBe(5173);
+ });
+
+ it("parses [::1]:port", () => {
+ expect(parsePortFromLsofName("[::1]:5173")).toBe(5173);
+ });
+
+ it("ignores non-local hosts", () => {
+ expect(parsePortFromLsofName("192.168.1.10:5173")).toBeNull();
+ });
+
+ it("strips trailing description", () => {
+ expect(parsePortFromLsofName("*:5173 (LISTEN)")).toBe(5173);
+ });
+
+ it("rejects garbage", () => {
+ expect(parsePortFromLsofName("")).toBeNull();
+ expect(parsePortFromLsofName("not-a-port")).toBeNull();
+ expect(parsePortFromLsofName("*:0")).toBeNull();
+ expect(parsePortFromLsofName("*:99999")).toBeNull();
+ });
+});
+
+describe("parseLsofOutput", () => {
+ it("parses a typical lsof -F pcn output", () => {
+ const sample = [
+ "p12345",
+ "cnode",
+ "n*:5173",
+ "p67890",
+ "cnext-server",
+ "n127.0.0.1:3000",
+ "n127.0.0.1:9229", // node debug port too — same process
+ "p13579",
+ "cChrome",
+ "n192.168.1.10:443", // not local — ignored
+ ].join("\n");
+
+ const servers = parseLsofOutput(sample);
+ expect(servers).toEqual([
+ {
+ host: "localhost",
+ port: 3000,
+ url: "http://localhost:3000",
+ processName: "next-server",
+ pid: 67890,
+ },
+ {
+ host: "localhost",
+ port: 5173,
+ url: "http://localhost:5173",
+ processName: "node",
+ pid: 12345,
+ },
+ {
+ host: "localhost",
+ port: 9229,
+ url: "http://localhost:9229",
+ processName: "next-server",
+ pid: 67890,
+ },
+ ]);
+ });
+
+ it("handles empty input", () => {
+ expect(parseLsofOutput("")).toEqual([]);
+ });
+
+ it("dedupes by host:port", () => {
+ const sample = ["p1", "cnode", "n*:5173", "n127.0.0.1:5173"].join("\n");
+ const servers = parseLsofOutput(sample);
+ expect(servers).toHaveLength(1);
+ expect(servers[0]?.port).toBe(5173);
+ });
+});
+
+describe("serversEqual", () => {
+ const a = {
+ host: "localhost",
+ port: 5173,
+ url: "http://localhost:5173",
+ processName: "node",
+ pid: 1,
+ };
+ it("returns true for identical lists", () => {
+ expect(serversEqual([a], [{ ...a }])).toBe(true);
+ });
+ it("returns false for different lengths", () => {
+ expect(serversEqual([a], [])).toBe(false);
+ });
+ it("returns false for different processName", () => {
+ expect(serversEqual([a], [{ ...a, processName: "other" }])).toBe(false);
+ });
+});
+
+/**
+ * Integration tests against a real TCP listener. We force the Windows code
+ * path (TCP-probe fallback) by monkey-patching `process.platform` for the
+ * duration of the test so we don't depend on `lsof` being installed.
+ */
+describe("PreviewPortScanner integration (TCP probe path)", () => {
+ let originalPlatform: NodeJS.Platform;
+ let server: net.Server;
+
+ beforeEach(async () => {
+ originalPlatform = process.platform;
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ // 3001 is in COMMON_DEV_PORTS so the TCP-probe pass will check it.
+ server = net.createServer();
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(3001, "127.0.0.1", () => resolve());
+ });
+ });
+
+ afterEach(async () => {
+ Object.defineProperty(process, "platform", {
+ value: originalPlatform,
+ configurable: true,
+ });
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("scan() returns a server we just opened on a curated dev port", async () => {
+ const result = await Effect.runPromise(
+ Effect.scoped(
+ Effect.gen(function* () {
+ const scanner = yield* PreviewPortScanner;
+ return yield* scanner.scan();
+ }).pipe(Effect.provide(PreviewPortScannerLive)),
+ ),
+ );
+ const found = result.find((s) => s.port === 3001);
+ expect(found).toBeDefined();
+ expect(found?.host).toBe("localhost");
+ });
+
+ it("retain() drives an immediate broadcast to subscribers", async () => {
+ const received: number[] = [];
+ await Effect.runPromise(
+ Effect.scoped(
+ Effect.gen(function* () {
+ const scanner = yield* PreviewPortScanner;
+ const unsubscribe = yield* scanner.subscribe((servers) =>
+ Effect.sync(() => {
+ for (const server of servers) received.push(server.port);
+ }),
+ );
+ const release = yield* scanner.retain();
+ // The retain() pollTick is fire-and-forget within Effect, so wait
+ // a frame for the broadcast to land.
+ yield* Effect.sleep("100 millis");
+ unsubscribe();
+ release();
+ }).pipe(Effect.provide(PreviewPortScannerLive)),
+ ),
+ );
+ expect(received).toContain(3001);
+ });
+});
diff --git a/apps/server/src/preview/Layers/PortScanner.ts b/apps/server/src/preview/Layers/PortScanner.ts
new file mode 100644
index 000000000..a73330158
--- /dev/null
+++ b/apps/server/src/preview/Layers/PortScanner.ts
@@ -0,0 +1,243 @@
+/**
+ * In-process PortScanner implementation.
+ *
+ * macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
+ * stable line-prefixed field format; this is the only `lsof` flag set we rely
+ * on).
+ *
+ * Windows / lsof missing: TCP-connects to a curated list of common dev ports
+ * on 127.0.0.1.
+ *
+ * Polling is reference-counted via `retain()`. A single layer-scoped fiber
+ * polls forever, but each tick is a no-op when the retain count is zero.
+ */
+import * as net from "node:net";
+
+import type { DiscoveredLocalServer } from "@t3tools/contracts";
+import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
+import { Cause, Data, Duration, Effect, Layer, Ref, Schedule } from "effect";
+
+import { runProcess } from "../../processRunner.ts";
+import {
+ COMMON_DEV_PORTS,
+ PreviewPortScanner,
+ type PreviewPortScannerShape,
+} from "../Services/PortScanner.ts";
+
+const POLL_INTERVAL = Duration.seconds(3);
+const TCP_PROBE_TIMEOUT_MS = 200;
+const LSOF_TIMEOUT_MS = 5_000;
+
+type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
+
+class LsofProbeError extends Data.TaggedError("LsofProbeError")<{
+ readonly cause: unknown;
+}> {}
+
+interface ScannerState {
+ readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
+}
+
+const parseLsofOutput = (raw: string): ReadonlyArray<DiscoveredLocalServer> => {
+ const seen = new Map<string, DiscoveredLocalServer>();
+ let pid: number | null = null;
+ let processName: string | null = null;
+
+ for (const line of raw.split("\n")) {
+ if (line.length === 0) continue;
+ const tag = line.charAt(0);
+ const value = line.slice(1);
+ if (tag === "p") {
+ const parsed = Number.parseInt(value, 10);
+ pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
+ processName = null;
+ continue;
+ }
+ if (tag === "c") {
+ processName = value.trim() || null;
+ continue;
+ }
+ if (tag === "n") {
+ const portMatch = parsePortFromLsofName(value);
+ if (portMatch == null) continue;
+ const url = `http://localhost:${portMatch}`;
+ const key = `localhost:${portMatch}`;
+ if (seen.has(key)) continue;
+ seen.set(key, {
+ host: "localhost",
+ port: portMatch,
+ url,
+ processName,
+ pid,
+ });
+ }
+ }
+
+ return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
+};
+
+const parsePortFromLsofName = (name: string): number | null => {
+ // Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
+ // "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
+ const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
+ if (trimmed.length === 0) return null;
+ const lastColon = trimmed.lastIndexOf(":");
+ if (lastColon < 0) return null;
+ const hostPart = trimmed.slice(0, lastColon);
+ const portPart = trimmed.slice(lastColon + 1);
+ if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
+ const port = Number.parseInt(portPart, 10);
+ if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
+ return port;
+};
+
+const probeLsof = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer> | null> =>
+ Effect.tryPromise({
+ try: () =>
+ runProcess("lsof", ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"], {
+ timeoutMs: LSOF_TIMEOUT_MS,
+ allowNonZeroExit: true,
+ maxBufferBytes: 1024 * 1024,
+ outputMode: "truncate",
+ }),
+ catch: (cause) => new LsofProbeError({ cause }),
+ }).pipe(
+ Effect.map((result) => parseLsofOutput(result.stdout)),
+ Effect.catch(() => Effect.succeed(null)),
+ );
+
+const probeTcpPort = (port: number): Promise<boolean> =>
+ new Promise((resolve) => {
+ const socket = new net.Socket();
+ let settled = false;
+ const finish = (ok: boolean) => {
+ if (settled) return;
+ settled = true;
+ socket.destroy();
+ resolve(ok);
+ };
+ socket.setTimeout(TCP_PROBE_TIMEOUT_MS);
+ socket.once("timeout", () => finish(false));
+ socket.once("error", () => finish(false));
+ socket.once("connect", () => finish(true));
+ socket.connect({ host: "127.0.0.1", port });
+ });
+
+const probeCommonPorts = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>> =>
+ Effect.promise(async () => {
+ const results = await Promise.all(
+ COMMON_DEV_PORTS.map(async (port) => ({ port, listening: await probeTcpPort(port) })),
+ );
+ return results
+ .filter((r) => r.listening)
+ .map<DiscoveredLocalServer>((r) => ({
+ host: "localhost",
+ port: r.port,
+ url: `http://localhost:${r.port}`,
+ processName: null,
+ pid: null,
+ }));
+ });
+
+const serversEqual = (
+ left: ReadonlyArray<DiscoveredLocalServer>,
+ right: ReadonlyArray<DiscoveredLocalServer>,
+): boolean => {
+ if (left.length !== right.length) return false;
+ for (let i = 0; i < left.length; i += 1) {
+ const a = left[i];
+ const b = right[i];
+ if (!a || !b) return false;
+ if (
+ a.host !== b.host ||
+ a.port !== b.port ||
+ a.url !== b.url ||
+ a.processName !== b.processName ||
+ a.pid !== b.pid
+ ) {
+ return false;
+ }
+ }
+ return true;
+};
+
+export const makePreviewPortScanner = Effect.gen(function* () {
+ const stateRef = yield* Ref.make<ScannerState>({
+ lastSnapshot: [],
+ });
+ const listeners = new Set<Listener>();
+ // Plain integer because the release callback returned by `retain()` runs
+ // outside any Effect context (the WS subscriber's release path) and must
+ // be a synchronous side-effect-only function.
+ let retainCount = 0;
+
+ const scanOnce = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>> =>
+ Effect.gen(function* () {
+ if (process.platform === "win32") {
+ return yield* probeCommonPorts();
+ }
+ const lsof = yield* probeLsof();
+ if (lsof !== null) return lsof;
+ return yield* probeCommonPorts();
+ });
+
+ const broadcast = (servers: ReadonlyArray<DiscoveredLocalServer>): Effect.Effect<void> =>
+ Effect.forEach(Array.from(listeners), (listener) => listener(servers), { discard: true });
+
+ const pollTick = Effect.gen(function* () {
+ if (retainCount <= 0) return;
+ const next = yield* scanOnce();
+ const state = yield* Ref.get(stateRef);
+ if (serversEqual(state.lastSnapshot, next)) return;
+ yield* Ref.update(stateRef, (s) => ({ ...s, lastSnapshot: next }));
+ yield* broadcast(next);
+ }).pipe(
+ Effect.catchCause((cause: Cause.Cause<never>) =>
+ Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
+ ),
+ );
+
+ // Single layer-scoped polling fiber. Ticks are no-ops when no client is
+ // currently retained, so the cost is one Ref.get every POLL_INTERVAL.
+ yield* Effect.forkScoped(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
+
+ const retain: PreviewPortScannerShape["retain"] = () =>
+ Effect.gen(function* () {
+ const wasIdle = retainCount === 0;
+ retainCount += 1;
+ if (wasIdle) {
+ // Run an immediate scan + broadcast so the new retainer doesn't have
+ // to wait up to POLL_INTERVAL for the first emission.
+ yield* pollTick;
+ }
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ retainCount = Math.max(0, retainCount - 1);
+ };
+ });
+
+ const subscribe: PreviewPortScannerShape["subscribe"] = (listener) =>
+ Effect.sync(() => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ });
+
+ return {
+ scan: scanOnce,
+ subscribe,
+ retain,
+ } satisfies PreviewPortScannerShape;
+});
+
+export const PreviewPortScannerLive = Layer.effect(PreviewPortScanner, makePreviewPortScanner);
+
+/** Exposed for tests. */
+export const __testing = {
+ parseLsofOutput,
+ parsePortFromLsofName,
+ serversEqual,
+};
diff --git a/apps/server/src/preview/Services/Manager.ts b/apps/server/src/preview/Services/Manager.ts
new file mode 100644
index 000000000..7c80c21c5
--- /dev/null
+++ b/apps/server/src/preview/Services/Manager.ts
@@ -0,0 +1,94 @@
+/**
+ * PreviewManager - Per-thread browser preview session orchestration.
+ *
+ * Owns metadata-only preview sessions keyed by `(threadId, tabId)`. A thread
+ * can host multiple concurrent tabs (browser-style). The actual Chromium
+ * <webview> lives in the desktop renderer; this service tracks the canonical
+ * URL/title/nav state per tab so sessions survive reconnects and are visible
+ * to multiple connected clients.
+ *
+ * Event delivery uses Effect's `PubSub` so listener failures (e.g. a
+ * disconnected WS subscriber's queue being closed) cannot propagate back
+ * into the mutating call's failure channel — matches the codebase
+ * convention used by `SessionCredentialService`.
+ *
+ * @module PreviewManager
+ */
+import {
+ type PreviewCloseInput,
+ type PreviewError,
+ type PreviewEvent,
+ type PreviewListInput,
+ type PreviewListResult,
+ type PreviewNavigateInput,
+ type PreviewOpenInput,
+ type PreviewRefreshInput,
+ type PreviewReportStatusInput,
+ type PreviewSessionSnapshot,
+} from "@t3tools/contracts";
+import { Context, type Effect, type PubSub, type Scope, type Stream } from "effect";
+
+export interface PreviewManagerShape {
+ /**
+ * Open a brand new preview tab for `threadId`. When `url` is omitted the
+ * tab starts in the `Idle` state so the user can type into the URL bar;
+ * otherwise it transitions straight to `Loading`. Always emits `opened`.
+ */
+ readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
+
+ /**
+ * Update the session's URL/title from the renderer (after the <webview>
+ * resolved navigation, including redirects). Emits a `navigated` event.
+ */
+ readonly navigate: (
+ input: PreviewNavigateInput,
+ ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
+
+ /**
+ * Renderer reports current nav status (Loading/Success/LoadFailed) and
+ * back/forward availability. Drives `failed` and `navigated` events.
+ */
+ readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
+
+ /**
+ * Renderer requested a reload. Server records intent (no state change) so
+ * subscribers can reconcile if needed; the desktop bridge actually reloads.
+ */
+ readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
+
+ /**
+ * Close the session (drop server-side state, emit `closed`). When `tabId`
+ * is omitted, closes every session for the thread.
+ */
+ readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
+
+ /**
+ * List active preview sessions for a thread. Returns an empty array when
+ * the thread has no sessions.
+ */
+ readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
+
+ /**
+ * Stream of preview events. Each subscriber gets its own buffered stream;
+ * subscriber failures are isolated and do not affect other subscribers
+ * or publishers.
+ *
+ * NOTE: `Stream.fromPubSub` defers `PubSub.subscribe` until the stream
+ * starts running, so `Stream.runForEach(...).pipe(Effect.forkScoped)` may
+ * miss a publish landing between fork and stream-start. Callers that
+ * cannot tolerate this gap should use `subscribeEvents` below.
+ */
+ readonly events: Stream.Stream<PreviewEvent>;
+
+ /**
+ * Acquire a PubSub subscription synchronously in the caller's fiber so
+ * no publish can land in the narrow gap between subscribe and consumer
+ * loop start. The subscription's lifetime is bound to the provided
+ * `Scope`; release happens automatically on scope close.
+ */
+ readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
+}
+
+export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
+ "t3/preview/Services/Manager/PreviewManager",
+) {}
diff --git a/apps/server/src/preview/Services/PortScanner.ts b/apps/server/src/preview/Services/PortScanner.ts
new file mode 100644
index 000000000..19a83c51c
--- /dev/null
+++ b/apps/server/src/preview/Services/PortScanner.ts
@@ -0,0 +1,36 @@
+/**
+ * PreviewPortScanner - Discovers listening localhost ports for the preview
+ * empty-state recommendations.
+ *
+ * Reference-counted polling: the scanner only runs when at least one client
+ * has called `retain()`. This keeps idle desktops from running `lsof` every
+ * 3 seconds for nothing.
+ *
+ * @module PreviewPortScanner
+ */
+import type { DiscoveredLocalServer } from "@t3tools/contracts";
+import { Context, type Effect } from "effect";
+
+export interface PreviewPortScannerShape {
+ /** One-shot snapshot of currently listening localhost ports. */
+ readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
+ /** Subscribe to changes. Listener invoked on every diff. Returns unsubscribe fn. */
+ readonly subscribe: (
+ listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
+ ) => Effect.Effect<() => void>;
+ /**
+ * Hint that at least one client is interested → starts polling. Returns
+ * release fn. When release count hits 0, polling stops.
+ */
+ readonly retain: () => Effect.Effect<() => void>;
+}
+
+export class PreviewPortScanner extends Context.Service<
+ PreviewPortScanner,
+ PreviewPortScannerShape
+>()("t3/preview/Services/PortScanner") {}
+
+/** Curated list of common dev-server ports for the Windows TCP-probe fallback. */
+export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
+ 3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
+]);
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 0bf2f6589..46e06085e 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -20,6 +20,7 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
ORCHESTRATION_WS_METHODS,
+ type PreviewEvent,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
@@ -48,6 +49,7 @@ import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
+import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -97,6 +99,8 @@ import { ServerLifecycleEvents, type ServerLifecycleEventsShape } from "./server
import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRuntimeStartup.ts";
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings.ts";
import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/Manager.ts";
+import { PreviewManager } from "./preview/Services/Manager.ts";
+import { PreviewPortScanner } from "./preview/Services/PortScanner.ts";
import {
BrowserTraceCollector,
type BrowserTraceCollectorShape,
@@ -663,6 +667,27 @@ const buildAppUnderTest = (options?: {
...options?.layers?.terminalManager,
}),
),
+ Layer.provide(
+ Layer.mock(PreviewManager)({
+ open: () => Effect.die("PreviewManager not stubbed in this test"),
+ navigate: () => Effect.die("PreviewManager not stubbed in this test"),
+ reportStatus: () => Effect.void,
+ refresh: () => Effect.void,
+ close: () => Effect.void,
+ list: () => Effect.succeed({ sessions: [] }),
+ events: Stream.empty,
+ subscribeEvents: Effect.flatMap(PubSub.unbounded<PreviewEvent>(), (pubsub) =>
+ PubSub.subscribe(pubsub),
+ ),
+ }),
+ ),
+ Layer.provide(
+ Layer.mock(PreviewPortScanner)({
+ scan: () => Effect.succeed([]),
+ subscribe: () => Effect.succeed(() => {}),
+ retain: () => Effect.succeed(() => {}),
+ }),
+ ),
Layer.provide(
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index b7331f95e..aaea59ab6 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -35,6 +35,8 @@ import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
+import { PreviewManagerLive } from "./preview/Layers/Manager.ts";
+import { PreviewPortScannerLive } from "./preview/Layers/PortScanner.ts";
import * as GitManager from "./git/GitManager.ts";
import { KeybindingsLive } from "./keybindings.ts";
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";
@@ -233,6 +235,8 @@ const CheckpointingLayerLive = Layer.empty.pipe(
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
+const PreviewLayerLive = Layer.mergeAll(PreviewManagerLive, PreviewPortScannerLive);
+
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistryLayerLive),
@@ -275,6 +279,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(VcsLayerLive),
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(TerminalLayerLive),
+ Layer.provideMerge(PreviewLayerLive),
Layer.provideMerge(PersistenceLayerLive),
Layer.provideMerge(KeybindingsLive),
Layer.provideMerge(ProviderRegistryLive),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 0f2a8f790..39187075f 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -22,6 +22,7 @@ import {
type AuthEnvironmentScope,
AuthSessionId,
CommandId,
+ type DiscoveredLocalServerList,
EventId,
type OrchestrationCommand,
type GitActionProgressEvent,
@@ -70,6 +71,8 @@ import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
import { ServerRuntimeStartup } from "./serverRuntimeStartup.ts";
import { redactServerSettingsForClient, ServerSettingsService } from "./serverSettings.ts";
import { TerminalManager } from "./terminal/Services/Manager.ts";
+import { PreviewManager } from "./preview/Services/Manager.ts";
+import { PreviewPortScanner } from "./preview/Services/PortScanner.ts";
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
@@ -240,6 +243,8 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
const vcsProvisioning = yield* VcsProvisioningService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const terminalManager = yield* TerminalManager;
+ const previewManager = yield* PreviewManager;
+ const previewPortScanner = yield* PreviewPortScanner;
const providerRegistry = yield* ProviderRegistry;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const config = yield* ServerConfig;
@@ -1350,6 +1355,63 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
),
{ "rpc.aggregate": "terminal" },
),
+ [WS_METHODS.previewOpen]: (input) =>
+ observeRpcEffect(WS_METHODS.previewOpen, previewManager.open(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.previewNavigate]: (input) =>
+ observeRpcEffect(WS_METHODS.previewNavigate, previewManager.navigate(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.previewRefresh]: (input) =>
+ observeRpcEffect(WS_METHODS.previewRefresh, previewManager.refresh(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.previewClose]: (input) =>
+ observeRpcEffect(WS_METHODS.previewClose, previewManager.close(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.previewList]: (input) =>
+ observeRpcEffect(WS_METHODS.previewList, previewManager.list(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.previewReportStatus]: (input) =>
+ observeRpcEffect(WS_METHODS.previewReportStatus, previewManager.reportStatus(input), {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.subscribePreviewEvents]: (_input) =>
+ observeRpcStream(WS_METHODS.subscribePreviewEvents, previewManager.events, {
+ "rpc.aggregate": "preview",
+ }),
+ [WS_METHODS.subscribeDiscoveredLocalServers]: (_input) =>
+ observeRpcStream(
+ WS_METHODS.subscribeDiscoveredLocalServers,
+ Stream.callback<DiscoveredLocalServerList>((queue) =>
+ Effect.acquireRelease(
+ Effect.gen(function* () {
+ const release = yield* previewPortScanner.retain();
+ const initial = yield* previewPortScanner.scan();
+ yield* Queue.offer(queue, {
+ servers: initial,
+ scannedAt: new Date().toISOString(),
+ });
+ const unsubscribe = yield* previewPortScanner.subscribe((servers) =>
+ Queue.offer(queue, {
+ servers,
+ scannedAt: new Date().toISOString(),
+ }),
+ );
+ return { unsubscribe, release };
+ }),
+ ({ unsubscribe, release }) =>
+ Effect.sync(() => {
+ unsubscribe();
+ release();
+ }),
+ ),
+ ),
+ { "rpc.aggregate": "preview" },
+ ),
[WS_METHODS.subscribeServerConfig]: (_input) =>
observeRpcStreamEffect(
WS_METHODS.subscribeServerConfig,
diff --git a/apps/web/package.json b/apps/web/package.json
index cbf554a66..b0910fe60 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -64,6 +64,7 @@
"babel-plugin-react-compiler": "1.0.0",
"msw": "2.12.11",
"playwright": "^1.58.2",
+ "react-grab": "^0.1.32",
"tailwindcss": "^4.0.0",
"vite": "catalog:",
"vite-plus": "catalog:",
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx
index 5a92a244c..f0e9ebb7e 100644
--- a/apps/web/src/components/ChatView.browser.tsx
+++ b/apps/web/src/components/ChatView.browser.tsx
@@ -268,6 +268,26 @@ function createMockEnvironmentApi(input: {
subscribeThread: (() => () =>
undefined) as EnvironmentApi["orchestration"]["subscribeThread"],
},
+ preview: {
+ open: () => {
+ throw new Error("Not implemented in browser test.");
+ },
+ navigate: () => {
+ throw new Error("Not implemented in browser test.");
+ },
+ refresh: () => {
+ throw new Error("Not implemented in browser test.");
+ },
+ close: () => {
+ throw new Error("Not implemented in browser test.");
+ },
+ list: () => Promise.resolve({ sessions: [] }),
+ reportStatus: () => {
+ throw new Error("Not implemented in browser test.");
+ },
+ onEvent: () => () => undefined,
+ subscribePorts: () => () => undefined,
+ } as EnvironmentApi["preview"],
};
}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 75fc0ad32..c417f7fd3 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -36,7 +36,7 @@ import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/proje
import { truncate } from "@t3tools/shared/String";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import { Debouncer } from "@tanstack/react-pacer";
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import { useVcsStatus } from "~/lib/vcsStatusState";
@@ -98,6 +98,14 @@ import { useCommandPaletteStore } from "../commandPaletteStore";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
+import { selectActiveRightPanelKindWithUrl, useRightPanelStore } from "../rightPanelStore";
+import { isPreviewSupportedInRuntime } from "../previewStateStore";
+import { subscribePreviewAction } from "./preview/previewActionBus";
+// Lazy: keeps the entire preview component graph (webview host, favicon
+// helper, Chromium error icon) out of the web bundle until first open.
+const PreviewPanel = lazy(() =>
+ import("./preview/PreviewPanel").then((mod) => ({ default: mod.PreviewPanel })),
+);
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import PlanSidebar from "./PlanSidebar";
@@ -910,7 +918,6 @@ export default function ChatView(props: ChatViewProps) {
>({});
const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =
useState<Record<string, number>>({});
- const [planSidebarOpen, setPlanSidebarOpen] = useState(false);
const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
// Tracks whether the user explicitly dismissed the sidebar for the active turn.
const planSidebarDismissedForTurnRef = useRef<string | null>(null);
@@ -1045,7 +1052,6 @@ export default function ChatView(props: ChatViewProps) {
[activeThread],
);
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
-
useEffect(() => {
if (!activeThreadRef) {
return;
@@ -1068,7 +1074,11 @@ export default function ChatView(props: ChatViewProps) {
reconcileTerminalIds,
terminalUiState.terminalIds,
]);
-
+ const activeRightPanelKind = useRightPanelStore((store) =>
+ selectActiveRightPanelKindWithUrl(store.byThreadKey, activeThreadRef, diffOpen),
+ );
+ const planSidebarOpen = activeRightPanelKind === "plan";
+ const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();
const existingOpenTerminalThreadKeys = useMemo(() => {
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
@@ -1925,12 +1935,47 @@ export default function ChatView(props: ChatViewProps) {
() => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions),
[keybindings, nonTerminalShortcutLabelOptions],
);
+ const previewPanelShortcutLabel = useMemo(
+ () => shortcutLabelForCommand(keybindings, "preview.toggle", nonTerminalShortcutLabelOptions),
+ [keybindings, nonTerminalShortcutLabelOptions],
+ );
+ // Right-panel arbitration:
+ // - The diff panel's openness is mirrored by the `?diff=1` URL search
+ // param so it deep-links cleanly. The store still records preview/plan
+ // openness; when both fight, `selectActiveRightPanelKindWithUrl` lets
+ // diff win (URL is truth).
+ // - The two toggles below treat the panels as mutually exclusive: opening
+ // one always tears down the other in BOTH the URL and the store. Without
+ // this, e.g. clicking the browser button while diff is URL-pinned would
+ // just toggle the (overridden) store value and look like a no-op.
+ const onTogglePreview = useCallback(() => {
+ if (!activeThreadRef) return;
+ if (previewPanelOpen) {
+ useRightPanelStore.getState().close(activeThreadRef);
+ return;
+ }
+ if (diffOpen) {
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: { environmentId, threadId },
+ replace: true,
+ search: (previous) => ({ ...stripDiffSearchParams(previous), diff: undefined }),
+ });
+ }
+ useRightPanelStore.getState().open(activeThreadRef, "preview");
+ }, [activeThreadRef, diffOpen, environmentId, navigate, previewPanelOpen, threadId]);
const onToggleDiff = useCallback(() => {
if (!isServerThread) {
return;
}
if (!diffOpen) {
onDiffPanelOpen?.();
+ // Switching to diff: drop whatever the store had (e.g. preview) so
+ // that when the user later closes diff, an old store entry doesn't
+ // unexpectedly resurface.
+ if (activeThreadRef) {
+ useRightPanelStore.getState().close(activeThreadRef);
+ }
}
void navigate({
to: "/$environmentId/$threadId",
@@ -1944,7 +1989,25 @@ export default function ChatView(props: ChatViewProps) {
return diffOpen ? { ...rest, diff: undefined } : { ...rest, diff: "1" };
},
});
- }, [diffOpen, environmentId, isServerThread, navigate, onDiffPanelOpen, threadId]);
+ }, [
+ activeThreadRef,
+ diffOpen,
+ environmentId,
+ isServerThread,
+ navigate,
+ onDiffPanelOpen,
+ threadId,
+ ]);
+
+ // Route the global mod+shift+J shortcut (dispatched from `routes/_chat.tsx`
+ // via `previewActionBus`) through the URL-aware toggle defined above.
+ useEffect(() => {
+ return subscribePreviewAction((action) => {
+ if (action !== "toggle-panel") return;
+ if (!isPreviewSupportedInRuntime()) return;
+ onTogglePreview();
+ });
+ }, [onTogglePreview]);
const envLocked = Boolean(
activeThread &&
@@ -2223,6 +2286,19 @@ export default function ChatView(props: ChatViewProps) {
terminalId: targetTerminalId,
data: `${script.command}\r`,
});
+ if (
+ script.autoOpenPreview &&
+ script.previewUrl &&
+ isPreviewSupportedInRuntime() &&
+ activeThreadRef
+ ) {
+ try {
+ await api.preview.open({ threadId: activeThreadId, url: script.previewUrl });
+ useRightPanelStore.getState().open(activeThreadRef, "preview");
+ } catch {
+ // Preview open failures are surfaced via the panel itself.
+ }
+ }
} catch (error) {
setThreadError(
activeThreadId,
@@ -2295,6 +2371,8 @@ export default function ChatView(props: ChatViewProps) {
command: input.command,
icon: input.icon,
runOnWorktreeCreate: input.runOnWorktreeCreate,
+ ...(input.previewUrl ? { previewUrl: input.previewUrl } : {}),
+ ...(input.autoOpenPreview ? { autoOpenPreview: input.autoOpenPreview } : {}),
};
const nextScripts = input.runOnWorktreeCreate
? [
@@ -2330,6 +2408,10 @@ export default function ChatView(props: ChatViewProps) {
command: input.command,
icon: input.icon,
runOnWorktreeCreate: input.runOnWorktreeCreate,
+ ...(input.previewUrl ? { previewUrl: input.previewUrl } : { previewUrl: undefined }),
+ ...(input.autoOpenPreview
+ ? { autoOpenPreview: input.autoOpenPreview }
+ : { autoOpenPreview: undefined }),
};
const nextScripts = activeProject.scripts.map((script) =>
script.id === scriptId
@@ -2424,21 +2506,25 @@ export default function ChatView(props: ChatViewProps) {
handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");
}, [handleInteractionModeChange, interactionMode]);
const togglePlanSidebar = useCallback(() => {
- setPlanSidebarOpen((open) => {
- if (open) {
- planSidebarDismissedForTurnRef.current =
- activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
- } else {
- planSidebarDismissedForTurnRef.current = null;
- }
- return !open;
- });
- }, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
+ if (!activeThreadRef) return;
+ if (planSidebarOpen) {
+ planSidebarDismissedForTurnRef.current =
+ activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
+ } else {
+ planSidebarDismissedForTurnRef.current = null;
+ }
+ useRightPanelStore.getState().toggle(activeThreadRef, "plan");
+ }, [activePlan?.turnId, activeThreadRef, planSidebarOpen, sidebarProposedPlan?.turnId]);
const closePlanSidebar = useCallback(() => {
- setPlanSidebarOpen(false);
+ if (!activeThreadRef) return;
+ useRightPanelStore.getState().close(activeThreadRef);
planSidebarDismissedForTurnRef.current =
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
- }, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
+ }, [activePlan?.turnId, activeThreadRef, sidebarProposedPlan?.turnId]);
+ const closePreviewPanel = useCallback(() => {
+ if (!activeThreadRef) return;
+ useRightPanelStore.getState().close(activeThreadRef);
+ }, [activeThreadRef]);
const persistThreadSettingsForNextTurn = useCallback(
async (input: {
@@ -2523,12 +2609,12 @@ export default function ChatView(props: ChatViewProps) {
setShowScrollToBottom(false);
if (planSidebarOpenOnNextThreadRef.current) {
planSidebarOpenOnNextThreadRef.current = false;
- setPlanSidebarOpen(true);
- } else {
- planSidebarOpenOnNextThreadRef.current = false;
- setPlanSidebarOpen(false);
+ if (activeThreadRef) {
+ useRightPanelStore.getState().open(activeThreadRef, "plan");
+ }
}
planSidebarDismissedForTurnRef.current = null;
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- activeThreadRef is reset transitively
}, [activeThread?.id]);
// Auto-open the plan sidebar when plan/todo steps arrive for the current turn.
@@ -2541,10 +2627,13 @@ export default function ChatView(props: ChatViewProps) {
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
if (planSidebarDismissedForTurnRef.current === turnKey) return;
- setPlanSidebarOpen(true);
+ if (activeThreadRef) {
+ useRightPanelStore.getState().open(activeThreadRef, "plan");
+ }
}, [
activePlan,
activeLatestTurn?.turnId,
+ activeThreadRef,
autoOpenPlanSidebar,
planSidebarOpen,
sidebarProposedPlan?.turnId,
@@ -3462,7 +3551,9 @@ export default function ChatView(props: ChatViewProps) {
// step-tracking activities that the sidebar will display.
if (nextInteractionMode === "default" && autoOpenPlanSidebar) {
planSidebarDismissedForTurnRef.current = null;
- setPlanSidebarOpen(true);
+ if (activeThreadRef) {
+ useRightPanelStore.getState().open(activeThreadRef, "plan");
+ }
}
sendInFlightRef.current = false;
} catch (err) {
@@ -3828,6 +3919,9 @@ export default function ChatView(props: ChatViewProps) {
terminalOpen={terminalUiState.terminalOpen}
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
diffToggleShortcutLabel={diffPanelShortcutLabel}
+ previewAvailable={isPreviewSupportedInRuntime()}
+ previewOpen={previewPanelOpen}
+ previewToggleShortcutLabel={previewPanelShortcutLabel}
gitCwd={gitCwd}
diffOpen={diffOpen}
onRunProjectScript={runProjectScript}
@@ -3835,6 +3929,7 @@ export default function ChatView(props: ChatViewProps) {
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
onToggleTerminal={toggleTerminalVisibility}
+ onTogglePreview={onTogglePreview}
onToggleDiff={onToggleDiff}
/>
</header>
@@ -4020,7 +4115,6 @@ export default function ChatView(props: ChatViewProps) {
</div>
{/* end chat column */}
- {/* Plan sidebar */}
{planSidebarOpen && !shouldUsePlanSidebarSheet ? (
<PlanSidebar
activePlan={activePlan}
@@ -4034,6 +4128,11 @@ export default function ChatView(props: ChatViewProps) {
onClose={closePlanSidebar}
/>
) : null}
+ {previewPanelOpen && !shouldUsePlanSidebarSheet && activeThreadRef ? (
+ <Suspense fallback={null}>
+ <PreviewPanel mode="inline" threadRef={activeThreadRef} visible />
+ </Suspense>
+ ) : null}
</div>
{/* end horizontal flex container */}
@@ -4054,6 +4153,13 @@ export default function ChatView(props: ChatViewProps) {
onAddTerminalContext={addTerminalContextToDraft}
/>
))}
+ {shouldUsePlanSidebarSheet && previewPanelOpen && activeThreadRef ? (
+ <RightPanelSheet open onClose={closePreviewPanel}>
+ <Suspense fallback={null}>
+ <PreviewPanel mode="sheet" threadRef={activeThreadRef} visible />
+ </Suspense>
+ </RightPanelSheet>
+ ) : null}
{shouldUsePlanSidebarSheet ? (
<RightPanelSheet open={planSidebarOpen} onClose={closePlanSidebar}>
<PlanSidebar
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index 4588ac51b..a9c218c0c 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -85,6 +85,10 @@ export interface NewProjectScriptInput {
icon: ProjectScriptIcon;
runOnWorktreeCreate: boolean;
keybinding: string | null;
+ /** Optional URL to open in the in-app preview when this script runs. */
+ previewUrl: string | null;
+ /** When true, automatically open the preview panel pointed at `previewUrl`. */
+ autoOpenPreview: boolean;
}
interface ProjectScriptsControlProps {
@@ -115,6 +119,8 @@ export default function ProjectScriptsControl({
const [iconPickerOpen, setIconPickerOpen] = useState(false);
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
+ const [previewUrl, setPreviewUrl] = useState("");
+ const [autoOpenPreview, setAutoOpenPreview] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
@@ -166,12 +172,15 @@ export default function ProjectScriptsControl({
keybinding,
command: commandForProjectScript(scriptIdForValidation),
});
+ const trimmedPreviewUrl = previewUrl.trim();
const payload = {
name: trimmedName,
command: trimmedCommand,
icon,
runOnWorktreeCreate,
keybinding: keybindingRule?.key ?? null,
+ previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
+ autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
} satisfies NewProjectScriptInput;
if (editingScriptId) {
await onUpdateScript(editingScriptId, payload);
@@ -193,6 +202,8 @@ export default function ProjectScriptsControl({
setIconPickerOpen(false);
setRunOnWorktreeCreate(false);
setKeybinding("");
+ setPreviewUrl("");
+ setAutoOpenPreview(false);
setValidationError(null);
setDialogOpen(true);
};
@@ -205,6 +216,8 @@ export default function ProjectScriptsControl({
setIconPickerOpen(false);
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
+ setPreviewUrl(script.previewUrl ?? "");
+ setAutoOpenPreview(script.autoOpenPreview ?? false);
setValidationError(null);
setDialogOpen(true);
};
@@ -327,6 +340,8 @@ export default function ProjectScriptsControl({
setIcon("play");
setRunOnWorktreeCreate(false);
setKeybinding("");
+ setPreviewUrl("");
+ setAutoOpenPreview(false);
setValidationError(null);
}}
open={dialogOpen}
@@ -413,6 +428,18 @@ export default function ProjectScriptsControl({
onChange={(event) => setCommand(event.target.value)}
/>
</div>
+ <div className="space-y-1.5">
+ <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
+ <Input
+ id="script-preview-url"
+ placeholder="http://localhost:5173"
+ value={previewUrl}
+ onChange={(event) => setPreviewUrl(event.target.value)}
+ />
+ <p className="text-xs text-muted-foreground">
+ Open this URL in the in-app preview when this action runs.
+ </p>
+ </div>
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
<span>Run automatically on worktree creation</span>
<Switch
@@ -420,6 +447,18 @@ export default function ProjectScriptsControl({
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
/>
</label>
+ <label
+ className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm ${
+ previewUrl.trim().length === 0 ? "opacity-60" : ""
+ }`}
+ >
+ <span>Open preview automatically when this action runs</span>
+ <Switch
+ checked={autoOpenPreview}
+ disabled={previewUrl.trim().length === 0}
+ onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
+ />
+ </label>
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
</form>
</DialogPanel>
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index b740a9ed7..0213aa0b0 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -48,6 +48,7 @@ import {
import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { attachTerminalSession } from "../terminalSessionState";
+import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -509,11 +510,26 @@ export function TerminalViewport({
}
if (match.kind === "url") {
- void localApi.shell.openExternal(match.text).catch((error: unknown) => {
- writeSystemMessage(
- latestTerminal,
- error instanceof Error ? error.message : "Unable to open link",
- );
+ const fallbackToBrowser = () => {
+ void localApi.shell.openExternal(match.text).catch((error: unknown) => {
+ writeSystemMessage(
+ latestTerminal,
+ error instanceof Error ? error.message : "Unable to open link",
+ );
+ });
+ };
+ const api = readEnvironmentApi(threadRef.environmentId);
+ if (!api) {
+ fallbackToBrowser();
+ return;
+ }
+ void openTerminalLinkInPreview({
+ url: match.text,
+ position: { x: event.clientX, y: event.clientY },
+ threadRef,
+ api,
+ localApi,
+ fallbackToBrowser,
});
return;
}
diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx
index 1346d1292..41b213f2b 100644
--- a/apps/web/src/components/chat/ChatHeader.tsx
+++ b/apps/web/src/components/chat/ChatHeader.tsx
@@ -9,7 +9,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime";
import { memo } from "react";
import GitActionsControl from "../GitActionsControl";
import { type DraftId } from "~/composerDraftStore";
-import { DiffIcon, TerminalSquareIcon } from "lucide-react";
+import { DiffIcon, Globe, TerminalSquareIcon } from "lucide-react";
+import { Badge } from "../ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
import { Toggle } from "../ui/toggle";
@@ -33,6 +34,10 @@ interface ChatHeaderProps {
terminalOpen: boolean;
terminalToggleShortcutLabel: string | null;
diffToggleShortcutLabel: string | null;
+ /** False on the web build; true only when the desktop preview bridge is present. */
+ previewAvailable: boolean;
+ previewOpen: boolean;
+ previewToggleShortcutLabel: string | null;
gitCwd: string | null;
diffOpen: boolean;
onRunProjectScript: (script: ProjectScript) => void;
@@ -40,6 +45,7 @@ interface ChatHeaderProps {
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onDeleteProjectScript: (scriptId: string) => Promise<void>;
onToggleTerminal: () => void;
+ onTogglePreview: () => void;
onToggleDiff: () => void;
}
@@ -71,6 +77,9 @@ export const ChatHeader = memo(function ChatHeader({
terminalOpen,
terminalToggleShortcutLabel,
diffToggleShortcutLabel,
+ previewAvailable,
+ previewOpen,
+ previewToggleShortcutLabel,
gitCwd,
diffOpen,
onRunProjectScript,
@@ -78,6 +87,7 @@ export const ChatHeader = memo(function ChatHeader({
onUpdateProjectScript,
onDeleteProjectScript,
onToggleTerminal,
+ onTogglePreview,
onToggleDiff,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -155,6 +165,29 @@ export const ChatHeader = memo(function ChatHeader({
: "Toggle terminal drawer"}
</TooltipPopup>
</Tooltip>
+ {previewAvailable ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Toggle
+ className="shrink-0"
+ pressed={previewOpen}
+ onPressedChange={onTogglePreview}
+ aria-label="Toggle preview browser"
+ variant="outline"
+ size="xs"
+ >
+ <Globe className="size-3" />
+ </Toggle>
+ }
+ />
+ <TooltipPopup side="bottom">
+ {previewToggleShortcutLabel
+ ? `Toggle preview browser (${previewToggleShortcutLabel})`
+ : "Toggle preview browser"}
+ </TooltipPopup>
+ </Tooltip>
+ ) : null}
<Tooltip>
<TooltipTrigger
render={
diff --git a/apps/web/src/components/preview/BrowserMockup.tsx b/apps/web/src/components/preview/BrowserMockup.tsx
new file mode 100644
index 000000000..3b1882bbd
--- /dev/null
+++ b/apps/web/src/components/preview/BrowserMockup.tsx
@@ -0,0 +1,24 @@
+import { cn } from "~/lib/utils";
+
+/** Browser-window thumbnail glyph for the "Local" recommendation cards. */
+export function BrowserMockup({ className }: { className?: string }) {
+ return (
+ <div
+ aria-hidden
+ className={cn(
+ "relative flex flex-col gap-0.5 overflow-hidden rounded-[5px] border border-border/60 bg-card p-1 shadow-xs/5",
+ className,
+ )}
+ >
+ <div className="flex gap-[2px]">
+ <span className="size-[3px] rounded-full bg-destructive/80" />
+ <span className="size-[3px] rounded-full bg-warning/80" />
+ <span className="size-[3px] rounded-full bg-success/80" />
+ </div>
+ <div className="mt-[1px] flex flex-1 flex-col gap-[2px]">
+ <span className="h-[2px] w-full rounded-full bg-muted-foreground/30" />
+ <span className="h-[2px] w-3/5 rounded-full bg-muted-foreground/20" />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewChromeRow.tsx b/apps/web/src/components/preview/PreviewChromeRow.tsx
new file mode 100644
index 000000000..2780d6bf4
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewChromeRow.tsx
@@ -0,0 +1,197 @@
+import { ArrowLeft, ArrowRight, ExternalLink, Globe, RotateCw } from "lucide-react";
+import {
+ type FormEvent,
+ type KeyboardEvent,
+ type ReactNode,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+import { Button } from "~/components/ui/button";
+import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
+import { cn } from "~/lib/utils";
+
+interface Props {
+ url: string;
+ loading: boolean;
+ loadProgress: number;
+ canGoBack: boolean;
+ canGoForward: boolean;
+ refreshDisabled: boolean;
+ inputDisabled?: boolean | undefined;
+ /** Bumping this value re-focuses and selects the URL input. */
+ focusUrlNonce?: number | undefined;
+ onBack: () => void;
+ onForward: () => void;
+ onRefresh: () => void;
+ onSubmit: (url: string) => void;
+ /** When provided, renders an "Open in browser" affordance to the right. */
+ onOpenInBrowser?: (() => void) | undefined;
+ /**
+ * Trailing slot rendered after the URL input. Used by the preview view
+ * to mount the three-dot menu (hard reload, devtools, zoom, clear data).
+ */
+ trailingActions?: ReactNode;
+}
+
+const NOOP = () => {};
+
+export function PreviewChromeRow({
+ url,
+ loading,
+ loadProgress,
+ canGoBack,
+ canGoForward,
+ refreshDisabled,
+ inputDisabled,
+ focusUrlNonce,
+ onBack,
+ onForward,
+ onRefresh,
+ onSubmit,
+ onOpenInBrowser,
+ trailingActions,
+}: Props) {
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [draft, setDraft] = useState(url);
+
+ // Sync the input with external URL changes, but only when the user isn't
+ // actively typing (preserves in-progress edits during navigation events).
+ useEffect(() => {
+ setDraft((previous) => (document.activeElement === inputRef.current ? previous : url));
+ }, [url]);
+
+ useEffect(() => {
+ if (focusUrlNonce == null) return;
+ const node = inputRef.current;
+ if (!node) return;
+ node.focus();
+ node.select();
+ }, [focusUrlNonce]);
+
+ const submit = (event?: FormEvent | KeyboardEvent) => {
+ event?.preventDefault();
+ const next = draft.trim();
+ if (next.length === 0) return;
+ onSubmit(next);
+ };
+
+ return (
+ <div className="relative">
+ <form
+ onSubmit={submit}
+ className="flex items-center gap-2 border-b border-border bg-background px-2 py-1.5"
+ >
+ <div className="flex items-center gap-0.5" role="group" aria-label="Navigation">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={canGoBack ? onBack : NOOP}
+ disabled={!canGoBack}
+ aria-label="Back"
+ type="button"
+ />
+ }
+ >
+ <ArrowLeft />
+ </TooltipTrigger>
+ <TooltipPopup>Back</TooltipPopup>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={canGoForward ? onForward : NOOP}
+ disabled={!canGoForward}
+ aria-label="Forward"
+ type="button"
+ />
+ }
+ >
+ <ArrowRight />
+ </TooltipTrigger>
+ <TooltipPopup>Forward</TooltipPopup>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={refreshDisabled ? NOOP : onRefresh}
+ disabled={refreshDisabled}
+ aria-label={loading ? "Stop" : "Refresh"}
+ type="button"
+ />
+ }
+ >
+ <RotateCw className={cn(loading && "animate-spin")} />
+ </TooltipTrigger>
+ <TooltipPopup>{loading ? "Loading…" : "Refresh"}</TooltipPopup>
+ </Tooltip>
+ </div>
+
+ <InputGroup className="flex-1">
+ <InputGroupAddon align="inline-start">
+ <Globe className="size-3.5 text-muted-foreground" aria-hidden />
+ </InputGroupAddon>
+ <InputGroupInput
+ ref={inputRef}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") submit(event);
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setDraft(url);
+ inputRef.current?.blur();
+ }
+ }}
+ placeholder="Search or enter URL"
+ spellCheck={false}
+ disabled={inputDisabled}
+ data-preview-url-input
+ size="sm"
+ />
+ </InputGroup>
+
+ {onOpenInBrowser ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={onOpenInBrowser}
+ aria-label="Open in system browser"
+ type="button"
+ />
+ }
+ >
+ <ExternalLink />
+ </TooltipTrigger>
+ <TooltipPopup>Open in system browser</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ {trailingActions}
+ </form>
+ {loadProgress > 0 ? (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute bottom-0 left-0 z-10 h-0.5 rounded-r-full bg-primary transition-all duration-150 ease-out"
+ style={{
+ width: `${loadProgress}%`,
+ boxShadow: "0 0 6px 1px var(--color-ring)",
+ }}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewEmptyState.tsx b/apps/web/src/components/preview/PreviewEmptyState.tsx
new file mode 100644
index 000000000..653fb9361
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewEmptyState.tsx
@@ -0,0 +1,59 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { Globe } from "lucide-react";
+
+import { Empty, EmptyDescription, EmptyMedia, EmptyTitle } from "~/components/ui/empty";
+
+import { PreviewLocalServerCard } from "./PreviewLocalServerCard";
+import { useDiscoveredLocalServers } from "./useDiscoveredLocalServers";
+
+interface Props {
+ environmentId: EnvironmentId;
+ configuredUrls?: ReadonlyArray<string> | undefined;
+ recentlySeenUrls?: ReadonlyArray<string> | undefined;
+ onOpenUrl: (url: string) => void;
+}
+
+export function PreviewEmptyState({
+ environmentId,
+ configuredUrls,
+ recentlySeenUrls,
+ onOpenUrl,
+}: Props) {
+ const servers = useDiscoveredLocalServers({
+ environmentId,
+ configuredUrls,
+ recentlySeenUrls,
+ });
+
+ if (servers.length === 0) {
+ return (
+ <Empty>
+ <EmptyMedia variant="icon">
+ <Globe className="size-4.5 text-muted-foreground" />
+ </EmptyMedia>
+ <EmptyTitle>No preview yet</EmptyTitle>
+ <EmptyDescription>
+ Type a URL above, or run a dev script. Listening localhost ports will show up here
+ automatically.
+ </EmptyDescription>
+ </Empty>
+ );
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-y-auto">
+ <h2 className="px-4 pt-4 pb-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground/80">
+ Local
+ </h2>
+ <div className="flex flex-col gap-1.5 px-3 pb-4">
+ {servers.map((server) => (
+ <PreviewLocalServerCard
+ key={`${server.host}:${server.port}`}
+ server={server}
+ onOpen={() => onOpenUrl(server.url)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewLocalServerCard.tsx b/apps/web/src/components/preview/PreviewLocalServerCard.tsx
new file mode 100644
index 000000000..c2e3018d3
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewLocalServerCard.tsx
@@ -0,0 +1,58 @@
+import { cn } from "~/lib/utils";
+
+import { BrowserMockup } from "./BrowserMockup";
+import type { PreviewableServer } from "./useDiscoveredLocalServers";
+
+interface Props {
+ server: PreviewableServer;
+ onOpen: () => void;
+}
+
+export function PreviewLocalServerCard({ server, onOpen }: Props) {
+ const subtitle = describeServer(server);
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className={cn(
+ "group flex w-full items-center gap-3 rounded-xl border border-border/70 bg-card px-3 py-2.5 text-left transition-colors",
+ "hover:border-border hover:bg-accent/40",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
+ )}
+ >
+ <BrowserMockup className="size-7 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm font-medium text-foreground">
+ {server.host}:{server.port}
+ </span>
+ <span className="truncate text-xs text-muted-foreground">{subtitle}</span>
+ </div>
+ {server.listening ? <PulsingDot /> : <DimDot />}
+ </button>
+ );
+}
+
+function describeServer(server: PreviewableServer): string {
+ if (server.processName) return server.processName;
+ if (server.listening) return "Listening";
+ if (server.source === "configured") return "Configured";
+ return "Recently seen";
+}
+
+function PulsingDot() {
+ return (
+ <span aria-label="Listening" className="relative inline-flex size-2 shrink-0">
+ <span className="absolute inset-0 animate-ping rounded-full bg-success opacity-60" />
+ <span className="relative inline-flex size-2 rounded-full bg-success" />
+ </span>
+ );
+}
+
+function DimDot() {
+ return (
+ <span
+ aria-label="Not currently listening"
+ className="size-2 shrink-0 rounded-full bg-muted-foreground/40"
+ />
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewMoreMenu.tsx b/apps/web/src/components/preview/PreviewMoreMenu.tsx
new file mode 100644
index 000000000..748a4a270
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewMoreMenu.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { Minus, MoreVertical, Plus as PlusIcon, RotateCcw } from "lucide-react";
+
+import { Button } from "~/components/ui/button";
+import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "~/components/ui/menu";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
+
+import { previewBridge } from "./previewBridge";
+
+interface Props {
+ /** Active preview tab id. Tab-targeting actions are disabled without it. */
+ tabId: string | null;
+ /**
+ * True only after the desktop bridge has registered a `webContentsId` for
+ * the active tab. Tab-targeting actions throw on the desktop side until
+ * then; we disable those items so the menu doesn't fire silent no-ops.
+ */
+ hasWebContents: boolean;
+ /** Current zoom factor as a number (1.0 = 100%). */
+ zoomFactor: number;
+}
+
+/**
+ * Three-dot menu in the chrome row. Wires Hard reload, DevTools, zoom
+ * controls, and storage-clearing actions. Only mounted by `PreviewView`
+ * when the desktop bridge is present, so we can call it unconditionally.
+ */
+export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
+ if (!previewBridge) return null;
+ const bridge = previewBridge;
+ const tabDisabled = !tabId || !hasWebContents;
+ const callTab = (op: (tabId: string) => Promise<void>) => () => {
+ if (!tabId) return;
+ void op(tabId).catch(() => undefined);
+ };
+
+ const zoomLabel = `${Math.round(zoomFactor * 100)}%`;
+
+ return (
+ <Menu>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <MenuTrigger
+ render={
+ <Button variant="ghost" size="icon-xs" type="button" aria-label="Preview menu" />
+ }
+ />
+ }
+ >
+ <MoreVertical />
+ </TooltipTrigger>
+ <TooltipPopup>More</TooltipPopup>
+ </Tooltip>
+ <MenuPopup align="end" sideOffset={6} className="min-w-56">
+ <MenuItem onClick={callTab(bridge.hardReload)} disabled={tabDisabled}>
+ Hard reload
+ </MenuItem>
+ <MenuItem onClick={callTab(bridge.openDevTools)} disabled={tabDisabled}>
+ Open DevTools
+ </MenuItem>
+ <MenuSeparator />
+ {/*
+ Zoom row: label + inline control cluster. `closeOnClick=false`
+ keeps the menu open while the user clicks the +/− buttons.
+ */}
+ <MenuItem
+ closeOnClick={false}
+ onClick={(event: React.MouseEvent) => event.preventDefault()}
+ className="justify-between"
+ disabled={tabDisabled}
+ >
+ <span>Zoom</span>
+ <span className="flex items-center gap-1">
+ <Button
+ variant="outline"
+ size="icon-xs"
+ type="button"
+ onClick={callTab(bridge.zoomOut)}
+ aria-label="Zoom out"
+ disabled={tabDisabled}
+ >
+ <Minus />
+ </Button>
+ <span className="min-w-12 text-center text-xs tabular-nums text-muted-foreground">
+ {zoomLabel}
+ </span>
+ <Button
+ variant="outline"
+ size="icon-xs"
+ type="button"
+ onClick={callTab(bridge.zoomIn)}
+ aria-label="Zoom in"
+ disabled={tabDisabled}
+ >
+ <PlusIcon />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ type="button"
+ onClick={callTab(bridge.resetZoom)}
+ aria-label="Reset zoom"
+ disabled={tabDisabled}
+ >
+ <RotateCcw />
+ </Button>
+ </span>
+ </MenuItem>
+ <MenuSeparator />
+ <MenuItem onClick={() => void bridge.clearCookies().catch(() => undefined)}>
+ Clear cookies
+ </MenuItem>
+ <MenuItem onClick={() => void bridge.clearCache().catch(() => undefined)}>
+ Clear cache
+ </MenuItem>
+ </MenuPopup>
+ </Menu>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewPanel.tsx b/apps/web/src/components/preview/PreviewPanel.tsx
new file mode 100644
index 000000000..edd19a31c
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewPanel.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import type { ScopedThreadRef } from "@t3tools/contracts";
+
+import { isPreviewSupportedInRuntime } from "~/previewStateStore";
+
+import { PreviewPanelShell, type PreviewPanelMode } from "./PreviewPanelShell";
+import { PreviewView } from "./PreviewView";
+
+interface Props {
+ mode: PreviewPanelMode;
+ threadRef: ScopedThreadRef;
+ configuredUrls?: ReadonlyArray<string> | undefined;
+ visible: boolean;
+}
+
+export function PreviewPanel({ mode, threadRef, configuredUrls, visible }: Props) {
+ if (!isPreviewSupportedInRuntime()) {
+ return (
+ <PreviewPanelShell mode={mode}>
+ <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">
+ <p className="max-w-sm text-sm text-muted-foreground">
+ Preview is only available in the T3 Code desktop app.
+ </p>
+ </div>
+ </PreviewPanelShell>
+ );
+ }
+
+ return (
+ <PreviewPanelShell mode={mode}>
+ <PreviewView threadRef={threadRef} configuredUrls={configuredUrls} visible={visible} />
+ </PreviewPanelShell>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewPanelShell.tsx b/apps/web/src/components/preview/PreviewPanelShell.tsx
new file mode 100644
index 000000000..71e8dd561
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewPanelShell.tsx
@@ -0,0 +1,77 @@
+import { type ReactNode, useEffect, useState } from "react";
+
+import { isElectron } from "~/env";
+import { useResizableWidth } from "~/hooks/useResizableWidth";
+import { cn } from "~/lib/utils";
+
+import { RightPanelResizeHandle } from "./RightPanelResizeHandle";
+
+export type PreviewPanelMode = "inline" | "sheet" | "sidebar";
+
+const PREVIEW_PANEL_WIDTH_STORAGE_KEY = "t3code:preview-panel-width";
+const PREVIEW_PANEL_MIN_WIDTH = 360;
+/** Hard ceiling so a wide monitor can't yield a panel that swallows the chat. */
+const PREVIEW_PANEL_MAX_WIDTH_PX = 1400;
+/** Fraction of the viewport allowed; the panel is min(this · vw, MAX_PX). */
+const PREVIEW_PANEL_MAX_WIDTH_FRACTION = 0.7;
+const PREVIEW_PANEL_DEFAULT_WIDTH = 540;
+
+/**
+ * Shell for the preview panel. In inline mode the panel is user-resizable
+ * via a drag handle on the left edge; width persists per browser. In
+ * sheet/sidebar modes the parent owns the size.
+ */
+export function PreviewPanelShell(props: { mode: PreviewPanelMode; children: ReactNode }) {
+ const useDragRegion = isElectron && props.mode !== "sheet";
+ const isInline = props.mode === "inline";
+ const maxWidth = useViewportClampedMaxWidth();
+ const { width, handlers } = useResizableWidth({
+ storageKey: PREVIEW_PANEL_WIDTH_STORAGE_KEY,
+ defaultWidth: PREVIEW_PANEL_DEFAULT_WIDTH,
+ minWidth: PREVIEW_PANEL_MIN_WIDTH,
+ maxWidth,
+ edge: "left",
+ });
+
+ return (
+ <div
+ className={cn(
+ "relative flex h-full min-w-0 flex-col bg-background",
+ isInline ? "shrink-0 border-l border-border" : "w-full",
+ )}
+ style={isInline ? { width: `${width}px` } : undefined}
+ data-preview-panel-mode={props.mode}
+ >
+ {isInline ? <RightPanelResizeHandle handlers={handlers} /> : null}
+ {useDragRegion ? <div className="electron-drag-region h-0 w-full" aria-hidden /> : null}
+ {props.children}
+ </div>
+ );
+}
+
+/**
+ * Track viewport width to derive a sensible upper bound for the panel.
+ * Resize-aware so dragging the OS window narrower re-clamps the stored
+ * width on the next render (the hook's clamp picks this up automatically).
+ */
+function useViewportClampedMaxWidth(): number {
+ const [vw, setVw] = useState(() => (typeof window === "undefined" ? 1280 : window.innerWidth));
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ let frame = 0;
+ const onResize = () => {
+ // Coalesce rapid resize events into one rAF tick.
+ if (frame !== 0) return;
+ frame = window.requestAnimationFrame(() => {
+ frame = 0;
+ setVw(window.innerWidth);
+ });
+ };
+ window.addEventListener("resize", onResize);
+ return () => {
+ window.removeEventListener("resize", onResize);
+ if (frame !== 0) window.cancelAnimationFrame(frame);
+ };
+ }, []);
+ return Math.min(PREVIEW_PANEL_MAX_WIDTH_PX, Math.floor(vw * PREVIEW_PANEL_MAX_WIDTH_FRACTION));
+}
diff --git a/apps/web/src/components/preview/PreviewUnreachable.tsx b/apps/web/src/components/preview/PreviewUnreachable.tsx
new file mode 100644
index 000000000..c6ada2cb4
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewUnreachable.tsx
@@ -0,0 +1,90 @@
+import { useState } from "react";
+
+import { Button } from "~/components/ui/button";
+
+import { describePreviewError } from "./errorCodeMessages";
+
+interface Props {
+ url: string;
+ /** Chromium net error code, e.g. -105. */
+ code: number;
+ /** Stringified Chromium error, e.g. "ERR_NAME_NOT_RESOLVED". */
+ description: string;
+ onReload: () => void;
+}
+
+/** Theme-aware tailwind port of Chromium's "This site can't be reached" page. */
+export function PreviewUnreachable({ url, code, description, onReload }: Props) {
+ const [showDetails, setShowDetails] = useState(false);
+ const host = safeHost(url) ?? url;
+ const friendly = describePreviewError(code, description);
+ const errorLabel = description.length > 0 ? description : `ERR_${Math.abs(code) || "FAILED"}`;
+
+ return (
+ <div className="relative flex h-full min-h-0 w-full overflow-y-auto bg-background">
+ <div className="mx-auto flex w-full max-w-xl flex-1 flex-col px-8 py-12 sm:py-16">
+ <ErrorIcon className="mb-6 size-12 text-muted-foreground/70" />
+ <h1 className="mb-3 text-2xl font-semibold leading-tight text-foreground">
+ This site can&rsquo;t be reached
+ </h1>
+ <p className="text-sm leading-relaxed text-muted-foreground">
+ <span className="font-semibold text-foreground">{host}</span>: {friendly}.
+ </p>
+
+ {showDetails ? (
+ <div className="mt-6 rounded-lg border border-border bg-muted/40 p-4 text-sm">
+ <p className="mb-2 font-medium text-foreground">Try:</p>
+ <ul className="list-disc space-y-1 pl-5 text-muted-foreground">
+ <li>Checking your connection</li>
+ <li>Confirming the dev server is running</li>
+ <li>Checking the proxy and the firewall</li>
+ </ul>
+ </div>
+ ) : null}
+
+ <div className="mt-8 text-xs uppercase tracking-wide text-muted-foreground/70">
+ {errorLabel}
+ </div>
+
+ <div className="mt-auto flex items-center gap-2 pt-8">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setShowDetails((value) => !value)}
+ >
+ {showDetails ? "Hide details" : "Details"}
+ </Button>
+ <div className="flex-1" />
+ <Button type="button" size="sm" onClick={onReload}>
+ Reload
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ErrorIcon({ className }: { className?: string }) {
+ return (
+ <svg
+ viewBox="0 0 64 64"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ className={className}
+ >
+ <path d="M16 12 L48 12 L48 52 L16 52 Z" />
+ <path d="M22 22 L42 22 M22 30 L36 30 M22 38 L40 38" strokeLinecap="round" />
+ <path d="M52 8 L12 56" strokeLinecap="round" />
+ </svg>
+ );
+}
+
+function safeHost(url: string): string | null {
+ try {
+ return new URL(url).host;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx
new file mode 100644
index 000000000..352ac9740
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewView.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { scopedThreadKey } from "@t3tools/client-runtime";
+import { type ScopedThreadRef } from "@t3tools/contracts";
+import { useCallback, useEffect, useState } from "react";
+
+import { ensureEnvironmentApi } from "~/environmentApi";
+import { ensureLocalApi } from "~/localApi";
+import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
+
+import { previewBridge } from "./previewBridge";
+import { subscribePreviewAction } from "./previewActionBus";
+import { PreviewChromeRow } from "./PreviewChromeRow";
+import { PreviewEmptyState } from "./PreviewEmptyState";
+import { PreviewMoreMenu } from "./PreviewMoreMenu";
+import { PreviewUnreachable } from "./PreviewUnreachable";
+import { PreviewWebview } from "./PreviewWebview";
+import { useLoadingProgress } from "./useLoadingProgress";
+import { usePreviewSession } from "./usePreviewSession";
+import { ZoomIndicator } from "./ZoomIndicator";
+
+interface Props {
+ threadRef: ScopedThreadRef;
+ configuredUrls?: ReadonlyArray<string> | undefined;
+ visible: boolean;
+}
+
+const localApi = typeof window === "undefined" ? null : ensureLocalApi();
+
+/**
+ * Single-tab preview surface: chrome row on top, one webview below, empty
+ * state when no session exists for the thread.
+ */
+export function PreviewView({ threadRef, configuredUrls, visible }: Props) {
+ const [focusUrlNonce, setFocusUrlNonce] = useState(0);
+ const previewState = usePreviewStateStore((state) =>
+ selectThreadPreviewState(state.byThreadKey, threadRef),
+ );
+ const rememberUrl = usePreviewStateStore((state) => state.rememberUrl);
+
+ usePreviewSession(threadRef);
+
+ const { snapshot, desktopOverlay } = previewState;
+ const tabId = snapshot?.tabId ?? null;
+ const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
+ const url = navStatus._tag === "Idle" ? "" : navStatus.url;
+ const loading = desktopOverlay?.loading ?? navStatus._tag === "Loading";
+ const canGoBack = desktopOverlay?.canGoBack ?? snapshot?.canGoBack ?? false;
+ const canGoForward = desktopOverlay?.canGoForward ?? snapshot?.canGoForward ?? false;
+ const refreshDisabled = navStatus._tag === "Idle";
+ const isUnreachable = navStatus._tag === "LoadFailed";
+ const loadProgress = useLoadingProgress(loading);
+
+ const handleSubmitUrl = useCallback(
+ async (next: string) => {
+ const api = ensureEnvironmentApi(threadRef.environmentId);
+ try {
+ if (tabId && previewBridge) {
+ // Drive the webview imperatively; `usePreviewBridge` mirrors the
+ // resolved URL back to the server so other clients stay in sync.
+ await previewBridge.navigate(tabId, next);
+ rememberUrl(threadRef, next);
+ } else {
+ const resolved = await api.preview.open({ threadId: threadRef.threadId, url: next });
+ const resolvedUrl = resolved.navStatus._tag === "Idle" ? next : resolved.navStatus.url;
+ rememberUrl(threadRef, resolvedUrl);
+ }
+ } catch {
+ // Server-side `failed` event renders the unreachable view.
+ }
+ },
+ [rememberUrl, tabId, threadRef],
+ );
+
+ const handleRefresh = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.refresh(tabId);
+ }, [tabId]);
+
+ const handleZoomIn = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.zoomIn(tabId);
+ }, [tabId]);
+
+ const handleZoomOut = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.zoomOut(tabId);
+ }, [tabId]);
+
+ const handleResetZoom = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
+ }, [tabId]);
+
+ const handleBack = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.goBack(tabId);
+ }, [tabId]);
+
+ const handleForward = useCallback(() => {
+ if (previewBridge && tabId) void previewBridge.goForward(tabId);
+ }, [tabId]);
+
+ const handleOpenInBrowser = useCallback(() => {
+ if (!localApi || !url) return;
+ void localApi.shell.openExternal(url).catch(() => undefined);
+ }, [url]);
+
+ // Subscribe only while visible; `toggle-panel` is owned by ChatView's
+ // URL-aware handler regardless of whether the panel is currently mounted.
+ useEffect(() => {
+ if (!visible) return;
+ return subscribePreviewAction((action) => {
+ switch (action) {
+ case "refresh":
+ handleRefresh();
+ return;
+ case "focus-url":
+ setFocusUrlNonce((value) => value + 1);
+ return;
+ case "zoom-in":
+ handleZoomIn();
+ return;
+ case "zoom-out":
+ handleZoomOut();
+ return;
+ case "reset-zoom":
+ handleResetZoom();
+ return;
+ case "toggle-panel":
+ return;
+ }
+ });
+ }, [handleRefresh, handleResetZoom, handleZoomIn, handleZoomOut, visible]);
+
+ return (
+ <div
+ className="flex h-full min-h-0 flex-col bg-background"
+ data-thread-key={scopedThreadKey(threadRef)}
+ >
+ <PreviewChromeRow
+ url={url}
+ loading={loading}
+ loadProgress={loadProgress}
+ canGoBack={canGoBack}
+ canGoForward={canGoForward}
+ refreshDisabled={refreshDisabled}
+ focusUrlNonce={focusUrlNonce}
+ onBack={handleBack}
+ onForward={handleForward}
+ onRefresh={handleRefresh}
+ onSubmit={(next) => void handleSubmitUrl(next)}
+ onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
+ trailingActions={
+ previewBridge ? (
+ <PreviewMoreMenu
+ tabId={tabId}
+ hasWebContents={desktopOverlay !== null}
+ zoomFactor={desktopOverlay?.zoomFactor ?? 1}
+ />
+ ) : null
+ }
+ />
+
+ <div className="relative flex-1 overflow-hidden">
+ {tabId && snapshot ? (
+ <PreviewWebview
+ key={tabId}
+ threadRef={threadRef}
+ tabId={tabId}
+ initialUrl={url || null}
+ className="absolute inset-0 h-full w-full"
+ />
+ ) : (
+ <PreviewEmptyState
+ environmentId={threadRef.environmentId}
+ configuredUrls={configuredUrls}
+ recentlySeenUrls={previewState.recentlySeenUrls}
+ onOpenUrl={(next) => void handleSubmitUrl(next)}
+ />
+ )}
+ {snapshot && desktopOverlay ? (
+ <ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
+ ) : null}
+ {isUnreachable && navStatus._tag === "LoadFailed" ? (
+ <div className="absolute inset-0 z-10 bg-background">
+ <PreviewUnreachable
+ url={navStatus.url}
+ code={navStatus.code}
+ description={navStatus.description}
+ onReload={handleRefresh}
+ />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/PreviewWebview.tsx b/apps/web/src/components/preview/PreviewWebview.tsx
new file mode 100644
index 000000000..3f78c588f
--- /dev/null
+++ b/apps/web/src/components/preview/PreviewWebview.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { useEffect, useRef, useState } from "react";
+
+import { isElectron } from "~/env";
+
+import { previewBridge } from "./previewBridge";
+import { usePreviewBridge } from "./usePreviewBridge";
+
+interface Props {
+ threadRef: ScopedThreadRef;
+ tabId: string;
+ /**
+ * URL to load on first mount. Subsequent prop changes are ignored — once
+ * the webview is live, navigation flows exclusively through the bridge
+ * (`previewBridge.navigate`, `goBack`, `goForward`, `refresh`). Otherwise,
+ * a snapshot URL update from the server would re-set `<webview src>` and
+ * race with the `loadURL` we already issued via the bridge.
+ */
+ initialUrl: string | null;
+ className?: string;
+}
+
+interface ElectronWebview extends HTMLElement {
+ src: string;
+ partition: string;
+ allowpopups: boolean;
+ reload: () => void;
+ getWebContentsId: () => number;
+}
+
+declare global {
+ interface HTMLElementTagNameMap {
+ webview: ElectronWebview;
+ }
+}
+
+/**
+ * Hosts the Electron `<webview>` for a single preview tab. Returns null on
+ * web builds. The two-step handshake (createTab → wait for `dom-ready` →
+ * registerWebview) is necessary because `getWebContentsId()` only returns a
+ * valid id once the embedded contents have parsed; calling it synchronously
+ * after mount throws.
+ */
+export function PreviewWebview({ threadRef, tabId, initialUrl, className }: Props) {
+ const [config, setConfig] = useState<{ partition: string } | null>(null);
+ const webviewRef = useRef<ElectronWebview | null>(null);
+ // Capture once at mount; never re-derived from `initialUrl` props later.
+ const initialSrcRef = useRef<string>(initialUrl ?? "about:blank");
+ const bridge = previewBridge;
+
+ // Per-tab desktop lifecycle: createTab on mount, closeTab on unmount,
+ // mirror state into the store, and reflect navigation back to the server.
+ usePreviewBridge({ threadRef, tabId });
+
+ useEffect(() => {
+ if (!bridge) return;
+ let cancelled = false;
+ void bridge
+ .getBrowserPartition()
+ .then((partition) => {
+ if (cancelled) return;
+ setConfig({ partition });
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [bridge]);
+
+ useEffect(() => {
+ if (!bridge || !config) return;
+ const webview = webviewRef.current;
+ if (!webview) return;
+
+ const onDomReady = () => {
+ try {
+ const id = webview.getWebContentsId();
+ if (Number.isFinite(id)) {
+ void bridge.registerWebview(tabId, id);
+ }
+ } catch {
+ // The next dom-ready (e.g. cross-document navigation) will retry.
+ }
+ };
+ webview.addEventListener("dom-ready", onDomReady as EventListener);
+ // Defensive: dom-ready may have fired between React commit and this
+ // effect running. Failures fall through to the listener above.
+ try {
+ const existing = webview.getWebContentsId();
+ if (Number.isFinite(existing)) {
+ void bridge.registerWebview(tabId, existing);
+ }
+ } catch {
+ // covered by dom-ready listener
+ }
+
+ return () => {
+ webview.removeEventListener("dom-ready", onDomReady as EventListener);
+ };
+ }, [bridge, config, tabId]);
+
+ if (!isElectron || !bridge || !config) return null;
+
+ return (
+ <webview
+ ref={webviewRef}
+ src={initialSrcRef.current}
+ partition={config.partition}
+ allowpopups
+ data-preview-tab={tabId}
+ className={className}
+ />
+ );
+}
diff --git a/apps/web/src/components/preview/RightPanelResizeHandle.tsx b/apps/web/src/components/preview/RightPanelResizeHandle.tsx
new file mode 100644
index 000000000..5091c8b59
--- /dev/null
+++ b/apps/web/src/components/preview/RightPanelResizeHandle.tsx
@@ -0,0 +1,34 @@
+import type { ResizableWidthHandlers } from "~/hooks/useResizableWidth";
+import { cn } from "~/lib/utils";
+
+interface Props {
+ handlers: ResizableWidthHandlers;
+ className?: string;
+}
+
+/**
+ * Hit target for resizing a right-anchored panel via its left edge.
+ *
+ * - Sits on top of the panel's border with a 4px overlap on each side so the
+ * user can grab a few pixels off the edge without aiming.
+ * - Visual indicator is a 1px line that lights up on hover/active to mirror
+ * VS Code / Cursor.
+ */
+export function RightPanelResizeHandle({ handlers, className }: Props) {
+ return (
+ <div
+ role="separator"
+ aria-orientation="vertical"
+ className={cn(
+ "group absolute inset-y-0 -left-1 z-20 w-2 cursor-col-resize select-none",
+ className,
+ )}
+ {...handlers}
+ >
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-transparent transition-colors duration-150 group-hover:bg-border group-active:bg-primary/60"
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/ZoomIndicator.tsx b/apps/web/src/components/preview/ZoomIndicator.tsx
new file mode 100644
index 000000000..0ac536668
--- /dev/null
+++ b/apps/web/src/components/preview/ZoomIndicator.tsx
@@ -0,0 +1,54 @@
+import { useEffect, useRef, useState } from "react";
+
+import { cn } from "~/lib/utils";
+
+const HIDE_AFTER_MS = 1500;
+const ZOOM_EPSILON = 0.001;
+
+interface Props {
+ /** Current zoom factor (1.0 = 100%); changes drive the transient indicator. */
+ zoomFactor: number;
+}
+
+/**
+ * Floating "X%" pill that surfaces in the top-right of the webview area
+ * whenever the zoom factor changes, then fades out after a short pause.
+ *
+ * Suppressed for the first render's value so we don't flash 100% on mount.
+ */
+export function ZoomIndicator({ zoomFactor }: Props) {
+ const [visible, setVisible] = useState(false);
+ const lastFactorRef = useRef(zoomFactor);
+ const timerRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (Math.abs(lastFactorRef.current - zoomFactor) < ZOOM_EPSILON) return;
+ lastFactorRef.current = zoomFactor;
+ setVisible(true);
+ if (timerRef.current !== null) window.clearTimeout(timerRef.current);
+ timerRef.current = window.setTimeout(() => {
+ setVisible(false);
+ timerRef.current = null;
+ }, HIDE_AFTER_MS);
+ return () => {
+ if (timerRef.current !== null) {
+ window.clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ };
+ }, [zoomFactor]);
+
+ const percent = `${Math.round(zoomFactor * 100)}%`;
+
+ return (
+ <div
+ aria-hidden={!visible}
+ className={cn(
+ "pointer-events-none absolute top-3 right-3 z-20 select-none rounded-full border border-border/70 bg-popover/95 px-2.5 py-1 text-xs font-medium text-foreground shadow-md/10 backdrop-blur transition-all duration-200 ease-out",
+ visible ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-1",
+ )}
+ >
+ {percent}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/preview/errorCodeMessages.ts b/apps/web/src/components/preview/errorCodeMessages.ts
new file mode 100644
index 000000000..78ee92880
--- /dev/null
+++ b/apps/web/src/components/preview/errorCodeMessages.ts
@@ -0,0 +1,12 @@
+import { PREVIEW_ERROR_CODE_MESSAGES } from "./previewConstants";
+
+/**
+ * Resolve a friendly description for a Chromium / network error. Falls back
+ * to the description string passed in when the code isn't in our table.
+ */
+export function describePreviewError(code: number, description: string): string {
+ const friendly = PREVIEW_ERROR_CODE_MESSAGES[description];
+ if (friendly) return friendly;
+ if (description.length > 0) return description;
+ return `Network error (${code})`;
+}
diff --git a/apps/web/src/components/preview/openTerminalLinkInPreview.ts b/apps/web/src/components/preview/openTerminalLinkInPreview.ts
new file mode 100644
index 000000000..0cafb4394
--- /dev/null
+++ b/apps/web/src/components/preview/openTerminalLinkInPreview.ts
@@ -0,0 +1,70 @@
+import type { EnvironmentApi, LocalApi, ScopedThreadRef } from "@t3tools/contracts";
+import { isPreviewableUrl } from "@t3tools/shared/preview";
+
+import { isPreviewSupportedInRuntime } from "~/previewStateStore";
+import { useRightPanelStore } from "~/rightPanelStore";
+
+interface OpenTerminalLinkInPreviewInput {
+ readonly url: string;
+ readonly position: { x: number; y: number };
+ readonly threadRef: ScopedThreadRef;
+ readonly api: EnvironmentApi;
+ readonly localApi: LocalApi;
+ /** Called whenever the URL ultimately needs to open in the system browser. */
+ readonly fallbackToBrowser: () => void;
+}
+
+/**
+ * Handles a terminal-link click that resolves to a URL.
+ *
+ * - For non-loopback / unsupported runtimes, defers to the system browser.
+ * - For previewable URLs in the desktop build, presents a context menu to
+ * choose between the in-app preview and the system browser.
+ *
+ * Failures fall back to the system browser so a stuck context-menu doesn't
+ * leave the user without a way to open the link.
+ */
+export async function openTerminalLinkInPreview(
+ input: OpenTerminalLinkInPreviewInput,
+): Promise<void> {
+ const supportsPreview =
+ isPreviewableUrl(input.url) &&
+ isPreviewSupportedInRuntime() &&
+ input.threadRef.threadId.length > 0;
+
+ if (!supportsPreview) {
+ input.fallbackToBrowser();
+ return;
+ }
+
+ let choice: "open-in-preview" | "open-in-browser" | null;
+ try {
+ choice = await input.localApi.contextMenu.show(
+ [
+ { id: "open-in-preview", label: "Open in preview" },
+ { id: "open-in-browser", label: "Open in browser" },
+ ],
+ input.position,
+ );
+ } catch {
+ input.fallbackToBrowser();
+ return;
+ }
+
+ if (choice === "open-in-preview") {
+ try {
+ await input.api.preview.open({
+ threadId: input.threadRef.threadId,
+ url: input.url,
+ });
+ useRightPanelStore.getState().open(input.threadRef, "preview");
+ } catch {
+ input.fallbackToBrowser();
+ }
+ return;
+ }
+
+ if (choice === "open-in-browser") {
+ input.fallbackToBrowser();
+ }
+}
diff --git a/apps/web/src/components/preview/previewActionBus.ts b/apps/web/src/components/preview/previewActionBus.ts
new file mode 100644
index 000000000..23efdf487
--- /dev/null
+++ b/apps/web/src/components/preview/previewActionBus.ts
@@ -0,0 +1,31 @@
+"use client";
+
+/**
+ * Typed window-event bus for preview-panel actions. Lets the global
+ * keybinding handler in `routes/_chat.tsx` reach `ChatView`'s URL-aware
+ * arbitration without prop drilling or shared refs.
+ */
+export type PreviewAction =
+ | "toggle-panel"
+ | "refresh"
+ | "focus-url"
+ | "zoom-in"
+ | "zoom-out"
+ | "reset-zoom";
+
+const EVENT_NAME = "t3code:preview-action";
+
+export function dispatchPreviewAction(action: PreviewAction): void {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(new CustomEvent<PreviewAction>(EVENT_NAME, { detail: action }));
+}
+
+export function subscribePreviewAction(listener: (action: PreviewAction) => void): () => void {
+ if (typeof window === "undefined") return () => {};
+ const handler = (event: Event) => {
+ const detail = (event as CustomEvent<PreviewAction>).detail;
+ if (typeof detail === "string") listener(detail);
+ };
+ window.addEventListener(EVENT_NAME, handler);
+ return () => window.removeEventListener(EVENT_NAME, handler);
+}
diff --git a/apps/web/src/components/preview/previewBridge.ts b/apps/web/src/components/preview/previewBridge.ts
new file mode 100644
index 000000000..90e9bf724
--- /dev/null
+++ b/apps/web/src/components/preview/previewBridge.ts
@@ -0,0 +1,9 @@
+/**
+ * Module-level handle to the desktop preview bridge.
+ *
+ * Resolved once at import time so React hooks don't pay for repeated
+ * `window.desktopBridge?.preview` lookups on every render. `null` on the web
+ * build where there's no Electron host.
+ */
+export const previewBridge =
+ typeof window === "undefined" ? null : (window.desktopBridge?.preview ?? null);
diff --git a/apps/web/src/components/preview/previewConstants.ts b/apps/web/src/components/preview/previewConstants.ts
new file mode 100644
index 000000000..d174577a5
--- /dev/null
+++ b/apps/web/src/components/preview/previewConstants.ts
@@ -0,0 +1,21 @@
+/** Cap for the per-thread "recently seen" URL list shown in the empty state. */
+export const PREVIEW_RECENT_URL_LIMIT = 10;
+
+/**
+ * Common Chromium error codes mapped to a short human label. Used by the
+ * unreachable view to drop the raw `ERR_*` code in favour of friendlier copy.
+ */
+export const PREVIEW_ERROR_CODE_MESSAGES: Readonly<Record<string, string>> = Object.freeze({
+ ERR_NAME_NOT_RESOLVED: "DNS address could not be found",
+ ERR_NAME_RESOLUTION_FAILED: "DNS address could not be found",
+ ERR_CONNECTION_REFUSED: "Connection refused",
+ ERR_CONNECTION_RESET: "Connection was reset",
+ ERR_CONNECTION_CLOSED: "Connection was closed",
+ ERR_CONNECTION_TIMED_OUT: "Connection timed out",
+ ERR_INTERNET_DISCONNECTED: "No internet connection",
+ ERR_TIMED_OUT: "Connection timed out",
+ ERR_CERT_AUTHORITY_INVALID: "Certificate authority is not trusted",
+ ERR_CERT_COMMON_NAME_INVALID: "Certificate hostname mismatch",
+ ERR_CERT_DATE_INVALID: "Certificate is expired or not yet valid",
+ ERR_TOO_MANY_REDIRECTS: "Too many redirects",
+});
diff --git a/apps/web/src/components/preview/useDiscoveredLocalServers.test.ts b/apps/web/src/components/preview/useDiscoveredLocalServers.test.ts
new file mode 100644
index 000000000..43bd879d0
--- /dev/null
+++ b/apps/web/src/components/preview/useDiscoveredLocalServers.test.ts
@@ -0,0 +1,116 @@
+import type { DiscoveredLocalServer } from "@t3tools/contracts";
+import { describe, expect, it } from "vitest";
+
+import { mergeServers, type PreviewableServer } from "./useDiscoveredLocalServers";
+
+const scannerServer = (overrides: Partial<DiscoveredLocalServer>): DiscoveredLocalServer => ({
+ host: "localhost",
+ port: 5173,
+ url: "http://localhost:5173",
+ processName: "vite",
+ pid: 1234,
+ ...overrides,
+});
+
+describe("mergeServers", () => {
+ it("returns scanner-only entries unchanged", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({})],
+ configuredUrls: [],
+ recentlySeenUrls: [],
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ host: "localhost",
+ port: 5173,
+ source: "scanner",
+ listening: true,
+ processName: "vite",
+ });
+ });
+
+ it("enriches a configured entry with live process metadata when scanner sees it", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({ port: 5173, processName: "node", pid: 9999 })],
+ configuredUrls: ["http://localhost:5173"],
+ recentlySeenUrls: [],
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ port: 5173,
+ source: "configured",
+ listening: true,
+ processName: "node",
+ pid: 9999,
+ });
+ });
+
+ it("keeps configured entries that the scanner doesn't see, with listening=false", () => {
+ const result = mergeServers({
+ scanner: [],
+ configuredUrls: ["http://localhost:5173"],
+ recentlySeenUrls: [],
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ source: "configured",
+ listening: false,
+ });
+ });
+
+ it("dedupes recently-seen URLs against scanner+configured entries", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({ port: 5173 })],
+ configuredUrls: [],
+ recentlySeenUrls: ["http://localhost:5173/", "http://localhost:8080/"],
+ });
+ expect(result.map((s) => s.port)).toEqual([5173, 8080]);
+ expect(result.find((s) => s.port === 5173)?.source).toBe("scanner");
+ expect(result.find((s) => s.port === 8080)?.source).toBe("recent");
+ });
+
+ it("ignores non-loopback URLs in configured/recent inputs", () => {
+ const result = mergeServers({
+ scanner: [],
+ configuredUrls: ["https://example.com", "ws://localhost:5173"],
+ recentlySeenUrls: ["https://api.example.com"],
+ });
+ expect(result).toHaveLength(0);
+ });
+
+ it("sorts: configured before scanner before recent, then by port", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({ port: 8080 }), scannerServer({ port: 3000 })],
+ configuredUrls: ["http://localhost:5173"],
+ recentlySeenUrls: ["http://localhost:9000/", "http://localhost:4321/"],
+ });
+ expect(result.map((s) => `${s.source}:${s.port}`)).toEqual([
+ "configured:5173",
+ "scanner:3000",
+ "scanner:8080",
+ "recent:4321",
+ "recent:9000",
+ ]);
+ });
+
+ it("dedupes by lowercased host", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({ host: "Localhost", port: 5173 })],
+ configuredUrls: ["http://localhost:5173"],
+ recentlySeenUrls: [],
+ });
+ expect(result).toHaveLength(1);
+ });
+});
+
+describe("PreviewableServer interface", () => {
+ it("preserves listening flag through enrichment", () => {
+ const result = mergeServers({
+ scanner: [scannerServer({})],
+ configuredUrls: ["http://localhost:5173"],
+ recentlySeenUrls: [],
+ });
+ const merged: PreviewableServer | undefined = result[0];
+ expect(merged?.listening).toBe(true);
+ });
+});
diff --git a/apps/web/src/components/preview/useDiscoveredLocalServers.ts b/apps/web/src/components/preview/useDiscoveredLocalServers.ts
new file mode 100644
index 000000000..9eab8592d
--- /dev/null
+++ b/apps/web/src/components/preview/useDiscoveredLocalServers.ts
@@ -0,0 +1,141 @@
+import type { DiscoveredLocalServer } from "@t3tools/contracts";
+import { isLoopbackHost } from "@t3tools/shared/preview";
+import { useEffect, useMemo, useState } from "react";
+
+import { ensureEnvironmentApi } from "~/environmentApi";
+import type { EnvironmentId } from "@t3tools/contracts";
+
+export interface PreviewableServer extends DiscoveredLocalServer {
+ source: "scanner" | "configured" | "recent";
+ /**
+ * True when the port scanner currently sees this server listening. A
+ * `configured` entry can also be `listening` when the scan enriched it.
+ */
+ listening: boolean;
+}
+
+interface UseDiscoveredLocalServersInput {
+ environmentId: EnvironmentId;
+ configuredUrls?: ReadonlyArray<string> | undefined;
+ recentlySeenUrls?: ReadonlyArray<string> | undefined;
+}
+
+/**
+ * Subscribe to live localhost port scans, merge in configured /
+ * recently-seen URLs, and return a stable sorted list. Retains the scanner
+ * while mounted.
+ */
+export function useDiscoveredLocalServers(
+ input: UseDiscoveredLocalServersInput,
+): ReadonlyArray<PreviewableServer> {
+ const [scannerSnapshot, setScannerSnapshot] = useState<ReadonlyArray<DiscoveredLocalServer>>([]);
+
+ useEffect(() => {
+ const api = ensureEnvironmentApi(input.environmentId);
+ setScannerSnapshot([]);
+ const unsubscribe = api.preview.subscribePorts((next) => {
+ setScannerSnapshot(next.servers);
+ });
+ return unsubscribe;
+ }, [input.environmentId]);
+
+ return useMemo(
+ () =>
+ mergeServers({
+ scanner: scannerSnapshot,
+ configuredUrls: input.configuredUrls ?? [],
+ recentlySeenUrls: input.recentlySeenUrls ?? [],
+ }),
+ [scannerSnapshot, input.configuredUrls, input.recentlySeenUrls],
+ );
+}
+
+export function mergeServers(input: {
+ scanner: ReadonlyArray<DiscoveredLocalServer>;
+ configuredUrls: ReadonlyArray<string>;
+ recentlySeenUrls: ReadonlyArray<string>;
+}): ReadonlyArray<PreviewableServer> {
+ const seen = new Map<string, PreviewableServer>();
+
+ for (const url of input.configuredUrls) {
+ const parsed = parseLocalUrl(url);
+ if (!parsed) continue;
+ const key = canonicalKey(parsed.host, parsed.port);
+ if (seen.has(key)) continue;
+ seen.set(key, {
+ host: parsed.host,
+ port: parsed.port,
+ url: parsed.url,
+ processName: null,
+ pid: null,
+ source: "configured",
+ listening: false,
+ });
+ }
+
+ for (const server of input.scanner) {
+ const key = canonicalKey(server.host, server.port);
+ const existing = seen.get(key);
+ if (existing) {
+ // Enrich a configured entry with live process metadata; flip
+ // `listening` so it pulses green like a scanner-discovered entry.
+ seen.set(key, {
+ ...existing,
+ processName: server.processName ?? existing.processName,
+ pid: server.pid ?? existing.pid,
+ listening: true,
+ });
+ continue;
+ }
+ seen.set(key, { ...server, source: "scanner", listening: true });
+ }
+
+ for (const url of input.recentlySeenUrls) {
+ const parsed = parseLocalUrl(url);
+ if (!parsed) continue;
+ const key = canonicalKey(parsed.host, parsed.port);
+ if (seen.has(key)) continue;
+ seen.set(key, {
+ host: parsed.host,
+ port: parsed.port,
+ url: parsed.url,
+ processName: null,
+ pid: null,
+ source: "recent",
+ listening: false,
+ });
+ }
+
+ return Array.from(seen.values()).toSorted((a, b) => {
+ const sourceOrder: Record<PreviewableServer["source"], number> = {
+ configured: 0,
+ scanner: 1,
+ recent: 2,
+ };
+ if (sourceOrder[a.source] !== sourceOrder[b.source]) {
+ return sourceOrder[a.source] - sourceOrder[b.source];
+ }
+ return a.port - b.port;
+ });
+}
+
+function canonicalKey(host: string, port: number): string {
+ return `${host.toLowerCase()}:${port}`;
+}
+
+function parseLocalUrl(raw: string): { host: string; port: number; url: string } | null {
+ try {
+ const parsed = new URL(raw);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
+ if (!isLoopbackHost(parsed.hostname)) return null;
+ const port = parsed.port
+ ? Number.parseInt(parsed.port, 10)
+ : parsed.protocol === "http:"
+ ? 80
+ : 443;
+ if (!Number.isFinite(port) || port <= 0) return null;
+ return { host: parsed.hostname, port, url: parsed.href };
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/src/components/preview/useLoadingProgress.ts b/apps/web/src/components/preview/useLoadingProgress.ts
new file mode 100644
index 000000000..6c47cea60
--- /dev/null
+++ b/apps/web/src/components/preview/useLoadingProgress.ts
@@ -0,0 +1,45 @@
+import { useEffect, useRef, useState } from "react";
+
+const TICK_INTERVAL_MS = 120;
+const FADE_OUT_DELAY_MS = 220;
+const SEED_PERCENT = 4;
+const ASYMPTOTE_PERCENT = 90;
+const APPROACH_FACTOR = 0.08;
+const MIN_INCREMENT = 0.5;
+
+/**
+ * Indeterminate progress simulator for the preview chrome's loading bar.
+ * Animates 0 → 90% asymptotically while `loading` is true, snaps to 100%
+ * on release, then resets after a short pause.
+ *
+ * Uses a ref to thread the latest progress through interval ticks without
+ * needing `loading` to retrigger the effect, which sidesteps the stale-
+ * closure pitfalls of reading `progress` directly.
+ */
+export function useLoadingProgress(loading: boolean): number {
+ const [progress, setProgress] = useState(0);
+ const progressRef = useRef(0);
+ progressRef.current = progress;
+
+ useEffect(() => {
+ if (!loading) {
+ if (progressRef.current === 0) return;
+ setProgress(100);
+ const timer = window.setTimeout(() => setProgress(0), FADE_OUT_DELAY_MS);
+ return () => window.clearTimeout(timer);
+ }
+
+ setProgress((value) => (value > 0 && value < 95 ? value : SEED_PERCENT));
+ const interval = window.setInterval(() => {
+ const current = progressRef.current;
+ if (current >= ASYMPTOTE_PERCENT) return;
+ const remaining = ASYMPTOTE_PERCENT - current;
+ const increment = Math.max(MIN_INCREMENT, remaining * APPROACH_FACTOR);
+ setProgress(Math.min(ASYMPTOTE_PERCENT, current + increment));
+ }, TICK_INTERVAL_MS);
+
+ return () => window.clearInterval(interval);
+ }, [loading]);
+
+ return progress;
+}
diff --git a/apps/web/src/components/preview/usePreviewBridge.ts b/apps/web/src/components/preview/usePreviewBridge.ts
new file mode 100644
index 000000000..6a80fb820
--- /dev/null
+++ b/apps/web/src/components/preview/usePreviewBridge.ts
@@ -0,0 +1,137 @@
+"use client";
+
+import type {
+ DesktopPreviewTabState,
+ PreviewReportStatusInput,
+ ScopedThreadRef,
+ ThreadId,
+} from "@t3tools/contracts";
+import { useEffect, useRef } from "react";
+
+import { ensureEnvironmentApi } from "~/environmentApi";
+import { type DesktopPreviewOverlay, usePreviewStateStore } from "~/previewStateStore";
+
+import { previewBridge } from "./previewBridge";
+
+/**
+ * Owns the desktop tab lifecycle, mirrors low-latency button state into the
+ * store, and reflects bridge navigation events back to the server.
+ *
+ * Tab create/close is anchored to the panel mount, NOT to the snapshot, so
+ * snapshot transitions (`opened` → `closed` → `opened`) cannot tear down and
+ * recreate the tab in the wrong order relative to in-flight desktop IPCs.
+ */
+export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: string }): void {
+ const { threadRef, tabId } = input;
+ const applyDesktopState = usePreviewStateStore((state) => state.applyDesktopState);
+ const bridge = previewBridge;
+
+ useEffect(() => {
+ if (!bridge) return;
+ void bridge.createTab(tabId);
+ return () => {
+ void bridge.closeTab(tabId);
+ };
+ }, [bridge, tabId]);
+
+ // One bridge subscription does both jobs (mirror state + forward to
+ // server) so the desktop bridge keeps a single listener entry per tab.
+ const lastReportedUrl = useRef<string | null>(null);
+ const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
+ useEffect(() => {
+ if (!bridge || typeof window === "undefined") return;
+ const api = ensureEnvironmentApi(threadRef.environmentId);
+ lastReportedUrl.current = null;
+ lastReportedKind.current = null;
+ const unsubscribe = bridge.onStateChange((changedTabId, state) => {
+ if (changedTabId !== tabId) return;
+ applyDesktopState(threadRef, projectDesktopState(state));
+ const reported = buildReportInput({
+ threadId: threadRef.threadId,
+ tabId,
+ state,
+ lastReportedUrl: lastReportedUrl.current,
+ lastReportedKind: lastReportedKind.current,
+ });
+ if (!reported) return;
+ lastReportedUrl.current = reported.lastReportedUrl;
+ lastReportedKind.current = reported.lastReportedKind;
+ void api.preview.reportStatus(reported.input).catch(() => undefined);
+ });
+ return unsubscribe;
+ }, [applyDesktopState, bridge, tabId, threadRef]);
+}
+
+function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
+ return {
+ canGoBack: state.canGoBack,
+ canGoForward: state.canGoForward,
+ loading: state.navStatus.kind === "Loading",
+ zoomFactor: state.zoomFactor,
+ };
+}
+
+/**
+ * Decide whether a state change warrants an RPC to the server, and shape
+ * the report payload.
+ *
+ * - Idle never reports — the tab is post-close or pre-load and the server
+ * already knows the canonical state from `open` / `closed`.
+ * - We dedupe on (kind, url): consecutive Loading→Loading→Loading for the
+ * same URL collapses to a single RPC, ditto Success.
+ * - LoadFailed always reports (the server uses it to emit `failed`).
+ */
+function buildReportInput(args: {
+ readonly threadId: ThreadId;
+ readonly tabId: string;
+ readonly state: DesktopPreviewTabState;
+ readonly lastReportedUrl: string | null;
+ readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
+}): {
+ readonly input: PreviewReportStatusInput;
+ readonly lastReportedUrl: string;
+ readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
+} | null {
+ const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
+ const status = state.navStatus;
+ if (status.kind === "Idle") return null;
+
+ // Skip if we've already reported the same kind+url. LoadFailed always
+ // reports (rapid duplicate failures are unusual and worth surfacing).
+ const sameAsLast =
+ status.kind !== "LoadFailed" &&
+ status.kind === lastReportedKind &&
+ status.url === lastReportedUrl;
+ if (sameAsLast) return null;
+
+ const base = {
+ threadId,
+ tabId,
+ canGoBack: state.canGoBack,
+ canGoForward: state.canGoForward,
+ };
+ if (status.kind === "LoadFailed") {
+ return {
+ input: {
+ ...base,
+ navStatus: {
+ _tag: "LoadFailed",
+ url: status.url,
+ title: status.title,
+ code: status.code,
+ description: status.description,
+ },
+ },
+ lastReportedUrl: status.url,
+ lastReportedKind: "LoadFailed",
+ };
+ }
+ return {
+ input: {
+ ...base,
+ navStatus: { _tag: status.kind, url: status.url, title: status.title },
+ },
+ lastReportedUrl: status.url,
+ lastReportedKind: status.kind,
+ };
+}
diff --git a/apps/web/src/components/preview/usePreviewSession.ts b/apps/web/src/components/preview/usePreviewSession.ts
new file mode 100644
index 000000000..152765213
--- /dev/null
+++ b/apps/web/src/components/preview/usePreviewSession.ts
@@ -0,0 +1,67 @@
+"use client";
+
+import { scopedThreadKey } from "@t3tools/client-runtime";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { useEffect } from "react";
+
+import { ensureEnvironmentApi } from "~/environmentApi";
+import { usePreviewStateStore } from "~/previewStateStore";
+
+/**
+ * Subscribes to the server's per-thread preview events and replays the
+ * latest snapshot on mount.
+ *
+ * Reconnect-recovery: when the local renderer remembers a snapshot but the
+ * server has none (server restarted while we were alive), re-issue
+ * `preview.open` so subsequent events land on a real session.
+ */
+export function usePreviewSession(threadRef: ScopedThreadRef): void {
+ const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
+ const applyServerEvent = usePreviewStateStore((state) => state.applyServerEvent);
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ const api = ensureEnvironmentApi(threadRef.environmentId);
+ const threadIdValue = threadRef.threadId;
+ let cancelled = false;
+
+ void api.preview
+ .list({ threadId: threadIdValue })
+ .then((result) => {
+ if (cancelled) return;
+ // Pick the most recent session. Server returns sessions sorted by
+ // `updatedAt` ascending, so the last one is freshest.
+ const serverSnapshot = result.sessions.at(-1) ?? null;
+ if (serverSnapshot) {
+ applyServerSnapshot(threadRef, serverSnapshot);
+ return;
+ }
+ // Server has no sessions — try to recover what the renderer
+ // remembers from before the disconnect.
+ const localSnapshot =
+ usePreviewStateStore.getState().byThreadKey[scopedThreadKey(threadRef)]?.snapshot;
+ const recoverableUrl =
+ localSnapshot && localSnapshot.navStatus._tag !== "Idle"
+ ? localSnapshot.navStatus.url
+ : null;
+ if (recoverableUrl) {
+ void api.preview
+ .open({ threadId: threadIdValue, url: recoverableUrl })
+ .catch(() => undefined);
+ } else {
+ applyServerSnapshot(threadRef, null);
+ }
+ })
+ .catch(() => undefined);
+
+ const unsubscribe = api.preview.onEvent((event) => {
+ if (event.threadId !== threadIdValue) return;
+ applyServerEvent(threadRef, event);
+ });
+
+ return () => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, [applyServerEvent, applyServerSnapshot, threadRef]);
+}
diff --git a/apps/web/src/environmentApi.ts b/apps/web/src/environmentApi.ts
index bdb2e7930..0268d98dc 100644
--- a/apps/web/src/environmentApi.ts
+++ b/apps/web/src/environmentApi.ts
@@ -58,6 +58,16 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
subscribeThread: (input, callback, options) =>
rpcClient.orchestration.subscribeThread(input, callback, options),
},
+ preview: {
+ open: (input) => rpcClient.preview.open(input as never),
+ navigate: (input) => rpcClient.preview.navigate(input as never),
+ refresh: (input) => rpcClient.preview.refresh(input as never),
+ close: (input) => rpcClient.preview.close(input as never),
+ list: (input) => rpcClient.preview.list(input as never),
+ reportStatus: (input) => rpcClient.preview.reportStatus(input as never),
+ onEvent: (callback) => rpcClient.preview.onEvent(callback),
+ subscribePorts: (callback, options) => rpcClient.preview.subscribePorts(callback, options),
+ },
};
}
diff --git a/apps/web/src/hooks/useResizableWidth.ts b/apps/web/src/hooks/useResizableWidth.ts
new file mode 100644
index 000000000..3552c82d9
--- /dev/null
+++ b/apps/web/src/hooks/useResizableWidth.ts
@@ -0,0 +1,176 @@
+import * as Schema from "effect/Schema";
+import {
+ type PointerEvent as ReactPointerEvent,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage";
+
+const WidthSchema = Schema.Finite;
+
+export interface UseResizableWidthOptions {
+ /** localStorage key the persisted width is stored under. */
+ readonly storageKey: string;
+ readonly defaultWidth: number;
+ readonly minWidth: number;
+ readonly maxWidth: number;
+ /**
+ * Which edge of the host element carries the drag handle:
+ * - "left" → panel grows leftward (right-anchored panels)
+ * - "right" → panel grows rightward (left-anchored panels)
+ */
+ readonly edge: "left" | "right";
+}
+
+export interface ResizableWidthHandlers {
+ readonly onPointerDown: (event: ReactPointerEvent<HTMLElement>) => void;
+ readonly onPointerMove: (event: ReactPointerEvent<HTMLElement>) => void;
+ readonly onPointerUp: (event: ReactPointerEvent<HTMLElement>) => void;
+ readonly onPointerCancel: (event: ReactPointerEvent<HTMLElement>) => void;
+}
+
+/**
+ * Width state for a side-anchored panel resized via a drag handle on the
+ * specified edge. Width is read from localStorage on mount and persisted on
+ * drag-end (not on every rAF tick — would otherwise be ~60 writes/sec).
+ *
+ * The hook updates an internal `width` state during drag (so the panel
+ * follows the cursor live) and only commits to localStorage when the user
+ * lifts the pointer.
+ */
+export function useResizableWidth(options: UseResizableWidthOptions): {
+ readonly width: number;
+ readonly handlers: ResizableWidthHandlers;
+} {
+ const { storageKey, defaultWidth, minWidth, maxWidth, edge } = options;
+
+ const clamp = useCallback(
+ (value: number): number => {
+ if (!Number.isFinite(value)) return defaultWidth;
+ return Math.max(minWidth, Math.min(maxWidth, value));
+ },
+ [defaultWidth, maxWidth, minWidth],
+ );
+
+ // No cross-tab subscription: panel width is per-window state.
+ const [width, setWidth] = useState<number>(() => {
+ if (typeof window === "undefined") return defaultWidth;
+ try {
+ const stored = getLocalStorageItem(storageKey, WidthSchema);
+ return clamp(stored ?? defaultWidth);
+ } catch {
+ return defaultWidth;
+ }
+ });
+
+ // Re-clamp if min/max change at runtime (e.g. window resize narrows max).
+ useEffect(() => {
+ setWidth((current) => clamp(current));
+ }, [clamp]);
+
+ const dragStateRef = useRef<{
+ pointerId: number;
+ startX: number;
+ startWidth: number;
+ pending: number;
+ rafId: number | null;
+ target: HTMLElement;
+ } | null>(null);
+
+ const releasePointer = useCallback((pointerId: number) => {
+ const state = dragStateRef.current;
+ if (!state) return;
+ if (state.rafId !== null) {
+ cancelAnimationFrame(state.rafId);
+ }
+ try {
+ if (state.target.hasPointerCapture(pointerId)) {
+ state.target.releasePointerCapture(pointerId);
+ }
+ } catch {
+ // pointer may already be released; harmless.
+ }
+ document.body.style.removeProperty("cursor");
+ document.body.style.removeProperty("user-select");
+ dragStateRef.current = null;
+ }, []);
+
+ const onPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLElement>) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const target = event.currentTarget;
+ try {
+ target.setPointerCapture(event.pointerId);
+ } catch {
+ return;
+ }
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ dragStateRef.current = {
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startWidth: width,
+ pending: width,
+ rafId: null,
+ target,
+ };
+ },
+ [width],
+ );
+
+ const onPointerMove = useCallback(
+ (event: ReactPointerEvent<HTMLElement>) => {
+ const state = dragStateRef.current;
+ if (!state || state.pointerId !== event.pointerId) return;
+ event.preventDefault();
+ const delta = edge === "left" ? state.startX - event.clientX : event.clientX - state.startX;
+ state.pending = clamp(state.startWidth + delta);
+ if (state.rafId !== null) return;
+ state.rafId = requestAnimationFrame(() => {
+ const active = dragStateRef.current;
+ if (!active) return;
+ active.rafId = null;
+ setWidth(active.pending);
+ });
+ },
+ [clamp, edge],
+ );
+
+ const onPointerUp = useCallback(
+ (event: ReactPointerEvent<HTMLElement>) => {
+ const state = dragStateRef.current;
+ if (!state || state.pointerId !== event.pointerId) return;
+ const finalWidth = clamp(state.pending);
+ releasePointer(event.pointerId);
+ // Commit once at drag-end to avoid 60Hz localStorage writes.
+ try {
+ setLocalStorageItem(storageKey, finalWidth, WidthSchema);
+ } catch {
+ // localStorage may be full / disabled; the in-memory state still wins.
+ }
+ setWidth(finalWidth);
+ },
+ [clamp, releasePointer, storageKey],
+ );
+
+ const onPointerCancel = useCallback(
+ (event: ReactPointerEvent<HTMLElement>) => {
+ const state = dragStateRef.current;
+ if (!state || state.pointerId !== event.pointerId) return;
+ // Don't persist a cancelled drag; revert to the start width.
+ releasePointer(event.pointerId);
+ setWidth(state.startWidth);
+ },
+ [releasePointer],
+ );
+
+ return {
+ width,
+ handlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel },
+ };
+}
diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts
index dbf2450f7..f9603bdce 100644
--- a/apps/web/src/keybindings.ts
+++ b/apps/web/src/keybindings.ts
@@ -30,6 +30,8 @@ export interface ShortcutModifierStateLike {
export interface ShortcutMatchContext {
terminalFocus: boolean;
terminalOpen: boolean;
+ previewFocus: boolean;
+ previewOpen: boolean;
[key: string]: boolean;
}
@@ -112,6 +114,8 @@ function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatc
return {
terminalFocus: false,
terminalOpen: false,
+ previewFocus: false,
+ previewOpen: false,
...options?.context,
};
}
@@ -379,6 +383,30 @@ export function isDiffToggleShortcut(
return matchesCommandShortcut(event, keybindings, "diff.toggle", options);
}
+export function isPreviewToggleShortcut(
+ event: ShortcutEventLike,
+ keybindings: ResolvedKeybindingsConfig,
+ options?: ShortcutMatchOptions,
+): boolean {
+ return matchesCommandShortcut(event, keybindings, "preview.toggle", options);
+}
+
+export function isPreviewRefreshShortcut(
+ event: ShortcutEventLike,
+ keybindings: ResolvedKeybindingsConfig,
+ options?: ShortcutMatchOptions,
+): boolean {
+ return matchesCommandShortcut(event, keybindings, "preview.refresh", options);
+}
+
+export function isPreviewFocusUrlShortcut(
+ event: ShortcutEventLike,
+ keybindings: ResolvedKeybindingsConfig,
+ options?: ShortcutMatchOptions,
+): boolean {
+ return matchesCommandShortcut(event, keybindings, "preview.focusUrl", options);
+}
+
export function isChatNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
diff --git a/apps/web/src/lib/favicon.ts b/apps/web/src/lib/favicon.ts
new file mode 100644
index 000000000..e5e94b266
--- /dev/null
+++ b/apps/web/src/lib/favicon.ts
@@ -0,0 +1,20 @@
+/**
+ * Favicon helpers for the preview tab strip.
+ *
+ * Uses Google's s2 favicon endpoint (same approach as ami's tab strip).
+ * Callers should always render a `<Globe />` fallback when the returned URL
+ * fails to load via an `onError` handler.
+ */
+const FAVICON_PROVIDER = "https://www.google.com/s2/favicons";
+
+export function faviconUrlForOrigin(rawUrl: string | null | undefined, size = 32): string | null {
+ if (!rawUrl) return null;
+ try {
+ const url = new URL(rawUrl);
+ if (!url.host) return null;
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
+ return `${FAVICON_PROVIDER}?domain=${encodeURIComponent(url.host)}&sz=${size}`;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/src/lib/previewFocus.ts b/apps/web/src/lib/previewFocus.ts
new file mode 100644
index 000000000..af7e76eaf
--- /dev/null
+++ b/apps/web/src/lib/previewFocus.ts
@@ -0,0 +1,15 @@
+/**
+ * Returns true when the user's keyboard focus is somewhere inside the
+ * preview panel (URL bar, chrome buttons, or — once detected via Electron
+ * `<webview>` focus events — the embedded page).
+ *
+ * Used by the global keybinding handler to gate `preview.refresh` and
+ * `preview.focusUrl` to only fire while the preview owns focus.
+ */
+export function isPreviewFocused(): boolean {
+ const activeElement = document.activeElement;
+ if (!(activeElement instanceof HTMLElement)) return false;
+ if (!activeElement.isConnected) return false;
+ if (activeElement.tagName.toLowerCase() === "webview") return true;
+ return activeElement.closest("[data-preview-panel-mode]") !== null;
+}
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index e92cad9aa..b4aff4f2c 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -18,6 +18,10 @@ import { getRouter } from "./router";
import { APP_DISPLAY_NAME } from "./branding";
import { syncDocumentWindowControlsOverlayClass } from "./lib/windowControlsOverlay";
+if (import.meta.env.DEV) {
+ void import("react-grab");
+}
+
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
const history = isElectron ? createHashHistory() : createBrowserHistory();
diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts
new file mode 100644
index 000000000..39dc7adee
--- /dev/null
+++ b/apps/web/src/previewStateStore.test.ts
@@ -0,0 +1,227 @@
+import { scopeThreadRef } from "@t3tools/client-runtime";
+import { type EnvironmentId, type PreviewSessionSnapshot, ThreadId } from "@t3tools/contracts";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { __testing, selectThreadPreviewState, usePreviewStateStore } from "./previewStateStore";
+
+const environmentId = "env-1" as EnvironmentId;
+const ref = scopeThreadRef(environmentId, ThreadId.make("thread-1"));
+
+const makeSnapshot = (overrides: Partial<PreviewSessionSnapshot> = {}): PreviewSessionSnapshot => ({
+ threadId: "thread-1",
+ tabId: "tab_a",
+ navStatus: { _tag: "Loading", url: "http://localhost:5173/", title: "" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ ...overrides,
+});
+
+beforeEach(() => {
+ usePreviewStateStore.setState({ byThreadKey: {} });
+});
+
+describe("previewStateStore (single-tab)", () => {
+ it("opened event seeds the snapshot and remembers the URL", () => {
+ const snapshot = makeSnapshot();
+ usePreviewStateStore.getState().applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.tabId).toBe(snapshot.tabId);
+ expect(state.recentlySeenUrls).toContain("http://localhost:5173/");
+ });
+
+ it("a second `opened` for a different tab replaces the rendered snapshot", () => {
+ const a = makeSnapshot({ tabId: "tab_a" });
+ const b = makeSnapshot({ tabId: "tab_b" });
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: a.tabId,
+ createdAt: a.updatedAt,
+ snapshot: a,
+ });
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: b.tabId,
+ createdAt: b.updatedAt,
+ snapshot: b,
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.tabId).toBe(b.tabId);
+ });
+
+ it("navigated event updates the snapshot URL", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyServerEvent(ref, {
+ type: "navigated",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: "2026-01-01T00:00:01.000Z",
+ snapshot: {
+ ...snapshot,
+ navStatus: { _tag: "Success", url: "http://localhost:5173/about", title: "About" },
+ },
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.navStatus._tag).toBe("Success");
+ if (state.snapshot?.navStatus._tag === "Success") {
+ expect(state.snapshot.navStatus.url).toBe("http://localhost:5173/about");
+ }
+ });
+
+ it("failed event flips the snapshot to LoadFailed when tabId matches", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyServerEvent(ref, {
+ type: "failed",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: "2026-01-01T00:00:01.000Z",
+ url: "http://localhost:5173/",
+ title: "",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.navStatus._tag).toBe("LoadFailed");
+ });
+
+ it("failed event for a non-active tab is ignored", () => {
+ const snapshot = makeSnapshot({ tabId: "tab_a" });
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyServerEvent(ref, {
+ type: "failed",
+ threadId: "thread-1",
+ tabId: "tab_b",
+ createdAt: "2026-01-01T00:00:01.000Z",
+ url: "http://localhost:9999/",
+ title: "",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.navStatus._tag).toBe("Loading");
+ });
+
+ it("closed event clears snapshot but retains recently-seen URLs", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyServerEvent(ref, {
+ type: "closed",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: "2026-01-01T00:00:01.000Z",
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot).toBeNull();
+ expect(state.recentlySeenUrls).toContain("http://localhost:5173/");
+ });
+
+ it("closed event for a different tab is a no-op", () => {
+ const snapshot = makeSnapshot({ tabId: "tab_a" });
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyServerEvent(ref, {
+ type: "closed",
+ threadId: "thread-1",
+ tabId: "tab_b",
+ createdAt: "2026-01-01T00:00:01.000Z",
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot?.tabId).toBe(snapshot.tabId);
+ });
+
+ it("desktopOverlay updates independently of snapshot", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerEvent(ref, {
+ type: "opened",
+ threadId: "thread-1",
+ tabId: snapshot.tabId,
+ createdAt: snapshot.updatedAt,
+ snapshot,
+ });
+ store.applyDesktopState(ref, {
+ canGoBack: true,
+ canGoForward: false,
+ loading: false,
+ zoomFactor: 1,
+ });
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.desktopOverlay?.canGoBack).toBe(true);
+ expect(state.snapshot?.canGoBack).toBe(false);
+ });
+
+ it("applyServerSnapshot null clears snapshot for a thread that had one", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerSnapshot(ref, snapshot);
+ store.applyServerSnapshot(ref, null);
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.snapshot).toBeNull();
+ });
+
+ it("rememberUrl dedupes and caps at limit", () => {
+ const store = usePreviewStateStore.getState();
+ for (let i = 0; i < __testing.RECENT_URL_LIMIT + 5; i += 1) {
+ store.rememberUrl(ref, `http://localhost:${5000 + i}/`);
+ }
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state.recentlySeenUrls.length).toBeLessThanOrEqual(__testing.RECENT_URL_LIMIT);
+ expect(state.recentlySeenUrls[0]).toBe(
+ `http://localhost:${5000 + __testing.RECENT_URL_LIMIT + 4}/`,
+ );
+ });
+
+ it("removeThread strips the entry", () => {
+ const snapshot = makeSnapshot();
+ const store = usePreviewStateStore.getState();
+ store.applyServerSnapshot(ref, snapshot);
+ store.removeThread(ref);
+ const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
+ expect(state).toEqual(__testing.EMPTY_THREAD_PREVIEW_STATE);
+ });
+});
diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts
new file mode 100644
index 000000000..90719efd4
--- /dev/null
+++ b/apps/web/src/previewStateStore.ts
@@ -0,0 +1,188 @@
+/**
+ * Per-thread preview UI state.
+ *
+ * Single-tab model: one snapshot per thread, mirrored two ways:
+ * - `snapshot` is the server-authoritative URL/title/load-status, replayed
+ * on WS reconnect so the panel survives backend restarts.
+ * - `desktopOverlay` is low-latency state from the local <webview>
+ * (canGoBack/canGoForward/visible/zoom/loading), used by the chrome row's
+ * button enablement.
+ *
+ * The schema-level `tabId` exists because the server still keys sessions by
+ * `(threadId, tabId)`; the client just always tracks one and ignores the rest.
+ */
+import { scopedThreadKey } from "@t3tools/client-runtime";
+import {
+ type PreviewEvent,
+ type PreviewSessionSnapshot,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
+import { create } from "zustand";
+
+import { PREVIEW_RECENT_URL_LIMIT } from "./components/preview/previewConstants";
+
+export interface DesktopPreviewOverlay {
+ canGoBack: boolean;
+ canGoForward: boolean;
+ loading: boolean;
+ zoomFactor: number;
+}
+
+export interface ThreadPreviewState {
+ snapshot: PreviewSessionSnapshot | null;
+ /** Bridge state takes precedence over `snapshot` for nav button enablement. */
+ desktopOverlay: DesktopPreviewOverlay | null;
+ /** Recently-visited URLs surfaced in the empty state. */
+ recentlySeenUrls: string[];
+}
+
+const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
+ snapshot: null,
+ desktopOverlay: null,
+ recentlySeenUrls: [] as string[],
+});
+
+interface PreviewStateStoreState {
+ byThreadKey: Record<string, ThreadPreviewState>;
+ applyServerEvent: (ref: ScopedThreadRef, event: PreviewEvent) => void;
+ applyServerSnapshot: (ref: ScopedThreadRef, snapshot: PreviewSessionSnapshot | null) => void;
+ applyDesktopState: (ref: ScopedThreadRef, overlay: DesktopPreviewOverlay | null) => void;
+ rememberUrl: (ref: ScopedThreadRef, url: string) => void;
+ removeThread: (ref: ScopedThreadRef) => void;
+}
+
+const ensureState = (
+ byThreadKey: Record<string, ThreadPreviewState>,
+ threadKey: string,
+): ThreadPreviewState => byThreadKey[threadKey] ?? EMPTY_THREAD_PREVIEW_STATE;
+
+const updateThread = (
+ state: PreviewStateStoreState,
+ threadKey: string,
+ updater: (current: ThreadPreviewState) => ThreadPreviewState,
+): PreviewStateStoreState["byThreadKey"] => {
+ const current = ensureState(state.byThreadKey, threadKey);
+ const next = updater(current);
+ if (next === current) return state.byThreadKey;
+ return { ...state.byThreadKey, [threadKey]: next };
+};
+
+const removeThreadKey = (
+ byThreadKey: Record<string, ThreadPreviewState>,
+ threadKey: string,
+): Record<string, ThreadPreviewState> => {
+ if (!(threadKey in byThreadKey)) return byThreadKey;
+ const { [threadKey]: _removed, ...rest } = byThreadKey;
+ return rest;
+};
+
+const dedupeRecentUrls = (existing: string[], url: string): string[] => {
+ const next = [url, ...existing.filter((entry) => entry !== url)];
+ return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
+};
+
+export const usePreviewStateStore = create<PreviewStateStoreState>()((set) => ({
+ byThreadKey: {},
+ applyServerEvent: (ref, event) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ let nextByThread = state.byThreadKey;
+ switch (event.type) {
+ case "opened":
+ case "navigated":
+ nextByThread = updateThread(state, threadKey, (current) => {
+ const snapshot = event.snapshot;
+ const recentlySeenUrls =
+ snapshot.navStatus._tag === "Idle"
+ ? current.recentlySeenUrls
+ : dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url);
+ return { ...current, snapshot, recentlySeenUrls };
+ });
+ break;
+ case "failed":
+ nextByThread = updateThread(state, threadKey, (current) => {
+ if (!current.snapshot || current.snapshot.tabId !== event.tabId) return current;
+ return {
+ ...current,
+ snapshot: {
+ ...current.snapshot,
+ navStatus: {
+ _tag: "LoadFailed",
+ url: event.url,
+ title: event.title,
+ code: event.code,
+ description: event.description,
+ },
+ updatedAt: event.createdAt,
+ },
+ };
+ });
+ break;
+ case "closed":
+ nextByThread = updateThread(state, threadKey, (current) => {
+ // Only clear if the closed tab is the one we were tracking; the
+ // server may have multiple tabs per thread but we only render one.
+ if (current.snapshot && current.snapshot.tabId !== event.tabId) return current;
+ return { ...current, snapshot: null, desktopOverlay: null };
+ });
+ break;
+ }
+ return { byThreadKey: nextByThread };
+ }),
+ applyServerSnapshot: (ref, snapshot) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ const nextByThread = updateThread(state, threadKey, (current) => {
+ if (!snapshot && current.snapshot === null) return current;
+ const recentlySeenUrls =
+ snapshot && snapshot.navStatus._tag !== "Idle"
+ ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
+ : current.recentlySeenUrls;
+ return { ...current, snapshot, recentlySeenUrls };
+ });
+ return { byThreadKey: nextByThread };
+ }),
+ applyDesktopState: (ref, overlay) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ const nextByThread = updateThread(state, threadKey, (current) => ({
+ ...current,
+ desktopOverlay: overlay,
+ }));
+ return { byThreadKey: nextByThread };
+ }),
+ rememberUrl: (ref, url) =>
+ set((state) => {
+ if (url.trim().length === 0) return state;
+ const threadKey = scopedThreadKey(ref);
+ const nextByThread = updateThread(state, threadKey, (current) => ({
+ ...current,
+ recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
+ }));
+ return { byThreadKey: nextByThread };
+ }),
+ removeThread: (ref) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ if (!(threadKey in state.byThreadKey)) return state;
+ return { byThreadKey: removeThreadKey(state.byThreadKey, threadKey) };
+ }),
+}));
+
+export function selectThreadPreviewState(
+ byThreadKey: Record<string, ThreadPreviewState>,
+ ref: ScopedThreadRef | null | undefined,
+): ThreadPreviewState {
+ if (!ref) return EMPTY_THREAD_PREVIEW_STATE;
+ return ensureState(byThreadKey, scopedThreadKey(ref));
+}
+
+export function isPreviewSupportedInRuntime(): boolean {
+ if (typeof window === "undefined") return false;
+ return Boolean(window.desktopBridge?.preview);
+}
+
+export const __testing = {
+ EMPTY_THREAD_PREVIEW_STATE,
+ RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
+};
diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts
new file mode 100644
index 000000000..9074ff49d
--- /dev/null
+++ b/apps/web/src/rightPanelStore.test.ts
@@ -0,0 +1,70 @@
+import { scopeThreadRef } from "@t3tools/client-runtime";
+import { type EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import {
+ selectActiveRightPanel,
+ selectActiveRightPanelKindWithUrl,
+ useRightPanelStore,
+} from "./rightPanelStore";
+
+const refA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A"));
+const refB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B"));
+
+beforeEach(() => {
+ useRightPanelStore.setState({ byThreadKey: {} });
+});
+
+describe("rightPanelStore", () => {
+ it("open sets the active panel for a thread", () => {
+ useRightPanelStore.getState().open(refA, "preview");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBeNull();
+ });
+
+ it("opening a different kind replaces the previous one", () => {
+ useRightPanelStore.getState().open(refA, "plan");
+ useRightPanelStore.getState().open(refA, "preview");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
+ });
+
+ it("close clears the active panel", () => {
+ useRightPanelStore.getState().open(refA, "plan");
+ useRightPanelStore.getState().close(refA);
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
+ });
+
+ it("toggle opens then closes the same kind", () => {
+ useRightPanelStore.getState().toggle(refA, "preview");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
+ useRightPanelStore.getState().toggle(refA, "preview");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
+ });
+
+ it("toggle to a different kind switches active", () => {
+ useRightPanelStore.getState().toggle(refA, "preview");
+ useRightPanelStore.getState().toggle(refA, "plan");
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("plan");
+ });
+
+ it("?diff=1 always wins over persisted state", () => {
+ useRightPanelStore.getState().open(refA, "preview");
+ expect(
+ selectActiveRightPanelKindWithUrl(useRightPanelStore.getState().byThreadKey, refA, true),
+ ).toBe("diff");
+ expect(
+ selectActiveRightPanelKindWithUrl(useRightPanelStore.getState().byThreadKey, refA, false),
+ ).toBe("preview");
+ });
+
+ it("removeThread clears persisted state", () => {
+ useRightPanelStore.getState().open(refA, "plan");
+ useRightPanelStore.getState().removeThread(refA);
+ expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
+ });
+
+ it("close on never-opened thread is a no-op", () => {
+ useRightPanelStore.getState().close(refA);
+ expect(useRightPanelStore.getState().byThreadKey).toEqual({});
+ });
+});
diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts
new file mode 100644
index 000000000..b8bba44fd
--- /dev/null
+++ b/apps/web/src/rightPanelStore.ts
@@ -0,0 +1,114 @@
+/**
+ * Per-thread arbiter for the right-side panel.
+ *
+ * Three tenants share the same slot: the plan sidebar, the diff panel, and
+ * the preview panel. Only one is open at a time per thread; the choice is
+ * remembered across thread switches.
+ *
+ * The diff panel still uses `?diff=1` as URL truth for deep-linking — when
+ * that param is present the diff tenant wins regardless of what's persisted
+ * here. See `selectActiveRightPanelKindWithUrl` for the resolution rule.
+ */
+import { scopedThreadKey } from "@t3tools/client-runtime";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+import { resolveStorage } from "./lib/storage";
+
+export const RIGHT_PANEL_KINDS = ["plan", "diff", "preview"] as const;
+export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
+
+const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v1";
+
+interface ThreadRightPanelState {
+ active: RightPanelKind | null;
+}
+
+interface RightPanelStoreState {
+ byThreadKey: Record<string, ThreadRightPanelState>;
+ open: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
+ close: (ref: ScopedThreadRef) => void;
+ toggle: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
+ removeThread: (ref: ScopedThreadRef) => void;
+}
+
+const updateThread = (
+ byThreadKey: Record<string, ThreadRightPanelState>,
+ threadKey: string,
+ next: ThreadRightPanelState,
+): Record<string, ThreadRightPanelState> => {
+ const current = byThreadKey[threadKey];
+ if (current && current.active === next.active) return byThreadKey;
+ if (next.active === null) {
+ if (!current) return byThreadKey;
+ const { [threadKey]: _removed, ...rest } = byThreadKey;
+ return rest;
+ }
+ return { ...byThreadKey, [threadKey]: next };
+};
+
+export const useRightPanelStore = create<RightPanelStoreState>()(
+ persist(
+ (set) => ({
+ byThreadKey: {},
+ open: (ref, kind) =>
+ set((state) => ({
+ byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), { active: kind }),
+ })),
+ close: (ref) =>
+ set((state) => ({
+ byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), { active: null }),
+ })),
+ toggle: (ref, kind) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ const current = state.byThreadKey[threadKey]?.active ?? null;
+ const next: RightPanelKind | null = current === kind ? null : kind;
+ return {
+ byThreadKey: updateThread(state.byThreadKey, threadKey, { active: next }),
+ };
+ }),
+ removeThread: (ref) =>
+ set((state) => {
+ const threadKey = scopedThreadKey(ref);
+ if (!(threadKey in state.byThreadKey)) return state;
+ const { [threadKey]: _removed, ...rest } = state.byThreadKey;
+ return { byThreadKey: rest };
+ }),
+ }),
+ {
+ name: RIGHT_PANEL_STORAGE_KEY,
+ version: 1,
+ storage: createJSONStorage(() =>
+ resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
+ ),
+ partialize: (state) => ({ byThreadKey: state.byThreadKey }),
+ },
+ ),
+);
+
+export function selectActiveRightPanel(
+ byThreadKey: Record<string, ThreadRightPanelState>,
+ ref: ScopedThreadRef | null | undefined,
+): RightPanelKind | null {
+ if (!ref) return null;
+ return byThreadKey[scopedThreadKey(ref)]?.active ?? null;
+}
+
+/**
+ * Resolves the active right panel taking the `?diff=1` URL truth into
+ * account. When `diff=1` the diff panel always wins.
+ *
+ * Prefer using `useSyncDiffSearchToRightPanel` (in ChatView) to mirror the
+ * URL into the store and consume `selectActiveRightPanel` directly — this
+ * helper exists for callers that don't want to install the sync effect.
+ */
+export function selectActiveRightPanelKindWithUrl(
+ byThreadKey: Record<string, ThreadRightPanelState>,
+ ref: ScopedThreadRef | null | undefined,
+ diffSearchActive: boolean,
+): RightPanelKind | null {
+ if (diffSearchActive) return "diff";
+ return selectActiveRightPanel(byThreadKey, ref);
+}
diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx
index 3ccb2e7f7..f28c80f01 100644
--- a/apps/web/src/routes/_chat.tsx
+++ b/apps/web/src/routes/_chat.tsx
@@ -2,16 +2,21 @@ import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useEffect } from "react";
import { useCommandPaletteStore } from "../commandPaletteStore";
+import { dispatchPreviewAction } from "../components/preview/previewActionBus";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import {
startNewLocalThreadFromContext,
startNewThreadFromContext,
} from "../lib/chatThreadActions";
+import { isPreviewFocused } from "../lib/previewFocus";
import { isTerminalFocused } from "../lib/terminalFocus";
import { resolveShortcutCommand } from "../keybindings";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
+import { isPreviewSupportedInRuntime } from "../previewStateStore";
+import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
+import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { useSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "~/rpc/serverState";
@@ -26,6 +31,14 @@ function ChatRouteGlobalShortcuts() {
? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen
: false,
);
+ // The `previewOpen` shortcut-context flag here uses the store-only value;
+ // the URL-aware arbitration lives inside ChatView's `onTogglePreview`,
+ // which we invoke via the action bus to avoid duplicating the rule.
+ const previewOpen = useRightPanelStore((state) =>
+ routeThreadRef
+ ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"
+ : false,
+ );
const appSettings = useSettings();
useEffect(() => {
@@ -35,6 +48,8 @@ function ChatRouteGlobalShortcuts() {
context: {
terminalFocus: isTerminalFocused(),
terminalOpen,
+ previewFocus: isPreviewFocused(),
+ previewOpen,
},
});
@@ -75,6 +90,50 @@ function ChatRouteGlobalShortcuts() {
}),
handleNewThread,
});
+ return;
+ }
+
+ if (command === "preview.toggle") {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!routeThreadRef) return;
+ if (!isPreviewSupportedInRuntime()) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "info",
+ title: "Preview is desktop-only",
+ description: "Open T3 Code in the desktop app to use the in-app preview.",
+ }),
+ );
+ return;
+ }
+ dispatchPreviewAction("toggle-panel");
+ return;
+ }
+
+ // The remaining preview commands only fire when the panel is the
+ // currently-focused tenant. The `when: previewFocus` rule already
+ // gates this, but defend against the keybinding being misconfigured.
+ if (
+ command === "preview.refresh" ||
+ command === "preview.focusUrl" ||
+ command === "preview.zoomIn" ||
+ command === "preview.zoomOut" ||
+ command === "preview.resetZoom"
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ const action =
+ command === "preview.refresh"
+ ? "refresh"
+ : command === "preview.focusUrl"
+ ? "focus-url"
+ : command === "preview.zoomIn"
+ ? "zoom-in"
+ : command === "preview.zoomOut"
+ ? "zoom-out"
+ : "reset-zoom";
+ dispatchPreviewAction(action);
}
};
@@ -89,6 +148,8 @@ function ChatRouteGlobalShortcuts() {
handleNewThread,
keybindings,
defaultProjectRef,
+ previewOpen,
+ routeThreadRef,
selectedThreadKeysSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 67652cc95..254aa92c6 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -23,6 +23,12 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
+ { "key": "mod+shift+j", "command": "preview.toggle" },
+ { "key": "mod+r", "command": "preview.refresh", "when": "previewFocus" },
+ { "key": "mod+l", "command": "preview.focusUrl", "when": "previewFocus" },
+ { "key": "mod+=", "command": "preview.zoomIn", "when": "previewFocus" },
+ { "key": "mod+-", "command": "preview.zoomOut", "when": "previewFocus" },
+ { "key": "mod+0", "command": "preview.resetZoom", "when": "previewFocus" },
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
@@ -51,6 +57,12 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
+- `preview.toggle`: open/close the in-app browser preview panel (desktop app only)
+- `preview.refresh`: reload the active preview tab (in focused preview context by default)
+- `preview.focusUrl`: focus the URL input of the preview panel (in focused preview context by default)
+- `preview.zoomIn`: zoom the preview viewport in one step (in focused preview context by default)
+- `preview.zoomOut`: zoom the preview viewport out one step (in focused preview context by default)
+- `preview.resetZoom`: reset the preview zoom to 100% (in focused preview context by default)
- `commandPalette.toggle`: open or close the global command palette
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
@@ -80,6 +92,8 @@ Currently available context keys:
- `terminalFocus`
- `terminalOpen`
+- `previewFocus`
+- `previewOpen`
Supported operators:
diff --git a/packages/client-runtime/src/wsRpcClient.ts b/packages/client-runtime/src/wsRpcClient.ts
index c1c683616..733c65ee1 100644
--- a/packages/client-runtime/src/wsRpcClient.ts
+++ b/packages/client-runtime/src/wsRpcClient.ts
@@ -79,6 +79,16 @@ export interface WsRpcClient {
readonly onEvent: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalEvents>;
readonly onMetadata: RpcStreamMethod<typeof WS_METHODS.subscribeTerminalMetadata>;
};
+ readonly preview: {
+ readonly open: RpcUnaryMethod<typeof WS_METHODS.previewOpen>;
+ readonly navigate: RpcUnaryMethod<typeof WS_METHODS.previewNavigate>;
+ readonly refresh: RpcUnaryMethod<typeof WS_METHODS.previewRefresh>;
+ readonly close: RpcUnaryMethod<typeof WS_METHODS.previewClose>;
+ readonly list: RpcUnaryMethod<typeof WS_METHODS.previewList>;
+ readonly reportStatus: RpcUnaryMethod<typeof WS_METHODS.previewReportStatus>;
+ readonly onEvent: RpcStreamMethod<typeof WS_METHODS.subscribePreviewEvents>;
+ readonly subscribePorts: RpcStreamMethod<typeof WS_METHODS.subscribeDiscoveredLocalServers>;
+ };
readonly projects: {
readonly searchEntries: RpcUnaryMethod<typeof WS_METHODS.projectsSearchEntries>;
readonly writeFile: RpcUnaryMethod<typeof WS_METHODS.projectsWriteFile>;
@@ -212,6 +222,27 @@ export function createWsRpcClient(
subscriptionOptions(options, WS_METHODS.subscribeTerminalMetadata),
),
},
+ preview: {
+ open: (input) => transport.request((client) => client[WS_METHODS.previewOpen](input)),
+ navigate: (input) => transport.request((client) => client[WS_METHODS.previewNavigate](input)),
+ refresh: (input) => transport.request((client) => client[WS_METHODS.previewRefresh](input)),
+ close: (input) => transport.request((client) => client[WS_METHODS.previewClose](input)),
+ list: (input) => transport.request((client) => client[WS_METHODS.previewList](input)),
+ reportStatus: (input) =>
+ transport.request((client) => client[WS_METHODS.previewReportStatus](input)),
+ onEvent: (listener, options) =>
+ transport.subscribe(
+ (client) => client[WS_METHODS.subscribePreviewEvents]({}),
+ listener,
+ options,
+ ),
+ subscribePorts: (listener, options) =>
+ transport.subscribe(
+ (client) => client[WS_METHODS.subscribeDiscoveredLocalServers]({}),
+ listener,
+ options,
+ ),
+ },
projects: {
searchEntries: (input) =>
transport.request((client) => client[WS_METHODS.projectsSearchEntries](input)),
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index 163d5e236..1cb46f6c7 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -22,4 +22,5 @@ export * from "./editor.ts";
export * from "./project.ts";
export * from "./filesystem.ts";
export * from "./review.ts";
+export * from "./preview.ts";
export * from "./rpc.ts";
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 1d8656ddf..d003e868d 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -54,6 +54,18 @@ import type {
} from "./terminal.ts";
import type { ServerRemoveKeybindingInput, ServerUpsertKeybindingInput } from "./server.ts";
import * as Schema from "effect/Schema";
+import type {
+ DiscoveredLocalServerList,
+ PreviewCloseInput,
+ PreviewEvent,
+ PreviewListInput,
+ PreviewListResult,
+ PreviewNavigateInput,
+ PreviewOpenInput,
+ PreviewRefreshInput,
+ PreviewReportStatusInput,
+ PreviewSessionSnapshot,
+} from "./preview.ts";
import type {
ClientOrchestrationCommand,
OrchestrationGetFullThreadDiffInput,
@@ -402,6 +414,33 @@ export const DesktopCloudAuthFetchResultSchema = Schema.Struct({
});
export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type;
+/**
+ * Renderer-facing snapshot of a desktop preview tab. Mirrors the main-process
+ * PreviewTabState shape but uses serialisable primitives only.
+ */
+export type DesktopPreviewNavStatus =
+ | { kind: "Idle" }
+ | { kind: "Loading"; url: string; title: string }
+ | { kind: "Success"; url: string; title: string }
+ | {
+ kind: "LoadFailed";
+ url: string;
+ title: string;
+ code: number;
+ description: string;
+ };
+
+export interface DesktopPreviewTabState {
+ tabId: string;
+ webContentsId: number | null;
+ navStatus: DesktopPreviewNavStatus;
+ canGoBack: boolean;
+ canGoForward: boolean;
+ /** Current zoom factor (1.0 = 100%). */
+ zoomFactor: number;
+ updatedAt: string;
+}
+
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
@@ -460,6 +499,34 @@ export interface DesktopBridge {
downloadUpdate: () => Promise<DesktopUpdateActionResult>;
installUpdate: () => Promise<DesktopUpdateActionResult>;
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
+ /**
+ * Desktop-only preview surface. Present iff the renderer is hosted by the
+ * Electron desktop build; web builds have `preview === undefined`.
+ */
+ preview?: DesktopPreviewBridge;
+}
+
+export interface DesktopPreviewBridge {
+ createTab: (tabId: string) => Promise<void>;
+ closeTab: (tabId: string) => Promise<void>;
+ registerWebview: (tabId: string, webContentsId: number) => Promise<void>;
+ navigate: (tabId: string, url: string) => Promise<void>;
+ goBack: (tabId: string) => Promise<void>;
+ goForward: (tabId: string) => Promise<void>;
+ refresh: (tabId: string) => Promise<void>;
+ zoomIn: (tabId: string) => Promise<void>;
+ zoomOut: (tabId: string) => Promise<void>;
+ resetZoom: (tabId: string) => Promise<void>;
+ /** Reload bypassing the HTTP cache. */
+ hardReload: (tabId: string) => Promise<void>;
+ /** Open the guest webview's DevTools (detached). */
+ openDevTools: (tabId: string) => Promise<void>;
+ /** Drop cookies + storage data for the preview partition (all tabs). */
+ clearCookies: () => Promise<void>;
+ /** Drop the HTTP cache for the preview partition (all tabs). */
+ clearCache: () => Promise<void>;
+ getBrowserPartition: () => Promise<string>;
+ onStateChange: (listener: (tabId: string, state: DesktopPreviewTabState) => void) => () => void;
}
/**
@@ -619,4 +686,17 @@ export interface EnvironmentApi {
},
) => () => void;
};
+ preview: {
+ open: (input: typeof PreviewOpenInput.Encoded) => Promise<PreviewSessionSnapshot>;
+ navigate: (input: typeof PreviewNavigateInput.Encoded) => Promise<PreviewSessionSnapshot>;
+ refresh: (input: typeof PreviewRefreshInput.Encoded) => Promise<void>;
+ close: (input: typeof PreviewCloseInput.Encoded) => Promise<void>;
+ list: (input: typeof PreviewListInput.Encoded) => Promise<PreviewListResult>;
+ reportStatus: (input: typeof PreviewReportStatusInput.Encoded) => Promise<void>;
+ onEvent: (callback: (event: PreviewEvent) => void) => () => void;
+ subscribePorts: (
+ callback: (servers: DiscoveredLocalServerList) => void,
+ options?: { onResubscribe?: () => void },
+ ) => () => void;
+ };
}
diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts
index 303d5c71c..4399d89d3 100644
--- a/packages/contracts/src/keybindings.ts
+++ b/packages/contracts/src/keybindings.ts
@@ -53,6 +53,12 @@ const STATIC_KEYBINDING_COMMANDS = [
"terminal.new",
"terminal.close",
"diff.toggle",
+ "preview.toggle",
+ "preview.refresh",
+ "preview.focusUrl",
+ "preview.zoomIn",
+ "preview.zoomOut",
+ "preview.resetZoom",
"commandPalette.toggle",
"chat.new",
"chat.newLocal",
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 218d0de74..46d51da37 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -194,6 +194,17 @@ export const ProjectScript = Schema.Struct({
command: TrimmedNonEmptyString,
icon: ProjectScriptIcon,
runOnWorktreeCreate: Schema.Boolean,
+ /**
+ * URL to open in the in-app browser preview when this script runs (or
+ * when the user explicitly requests a preview). Optional; only honored on
+ * the desktop build.
+ */
+ previewUrl: Schema.optional(TrimmedNonEmptyString),
+ /**
+ * When true, automatically open the preview panel pointed at `previewUrl`
+ * the moment this script starts. Ignored without `previewUrl` or on web.
+ */
+ autoOpenPreview: Schema.optional(Schema.Boolean),
});
export type ProjectScript = typeof ProjectScript.Type;
diff --git a/packages/contracts/src/preview.test.ts b/packages/contracts/src/preview.test.ts
new file mode 100644
index 000000000..d1f108ab4
--- /dev/null
+++ b/packages/contracts/src/preview.test.ts
@@ -0,0 +1,162 @@
+import { Schema } from "effect";
+import { describe, expect, it } from "vitest";
+
+import {
+ DiscoveredLocalServer,
+ PreviewEvent,
+ PreviewNavStatus,
+ PreviewSessionSnapshot,
+} from "./preview.ts";
+
+const decodePreviewEvent = Schema.decodeUnknownSync(PreviewEvent);
+const decodeSnapshot = Schema.decodeUnknownSync(PreviewSessionSnapshot);
+const decodeNavStatus = Schema.decodeUnknownSync(PreviewNavStatus);
+const decodeServer = Schema.decodeUnknownSync(DiscoveredLocalServer);
+
+describe("PreviewNavStatus", () => {
+ it("decodes Idle", () => {
+ expect(decodeNavStatus({ _tag: "Idle" })).toEqual({ _tag: "Idle" });
+ });
+
+ it("decodes Loading with title", () => {
+ expect(decodeNavStatus({ _tag: "Loading", url: "http://localhost:5173/", title: "" })).toEqual({
+ _tag: "Loading",
+ url: "http://localhost:5173/",
+ title: "",
+ });
+ });
+
+ it("decodes LoadFailed with code/description", () => {
+ expect(
+ decodeNavStatus({
+ _tag: "LoadFailed",
+ url: "https://example.com/",
+ title: "Example",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ }),
+ ).toEqual({
+ _tag: "LoadFailed",
+ url: "https://example.com/",
+ title: "Example",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ });
+ });
+
+ it("rejects empty url", () => {
+ expect(() => decodeNavStatus({ _tag: "Loading", url: "", title: "" })).toThrow();
+ });
+});
+
+describe("PreviewSessionSnapshot", () => {
+ it("round-trips a Success snapshot", () => {
+ const snapshot = decodeSnapshot({
+ threadId: "thread-1",
+ tabId: "preview-thread-1",
+ navStatus: {
+ _tag: "Success",
+ url: "http://localhost:5173/",
+ title: "Vite App",
+ },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ });
+ expect(snapshot.tabId).toBe("preview-thread-1");
+ expect(snapshot.navStatus._tag).toBe("Success");
+ });
+});
+
+describe("PreviewEvent", () => {
+ it("decodes opened", () => {
+ const event = decodePreviewEvent({
+ type: "opened",
+ threadId: "t",
+ tabId: "preview-t",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ snapshot: {
+ threadId: "t",
+ tabId: "preview-t",
+ navStatus: { _tag: "Idle" },
+ canGoBack: false,
+ canGoForward: false,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ },
+ });
+ expect(event.type).toBe("opened");
+ });
+
+ it("decodes failed with code/description", () => {
+ const event = decodePreviewEvent({
+ type: "failed",
+ threadId: "t",
+ tabId: "preview-t",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ url: "https://example.com/",
+ title: "",
+ code: -105,
+ description: "ERR_NAME_NOT_RESOLVED",
+ });
+ expect(event.type).toBe("failed");
+ if (event.type === "failed") {
+ expect(event.code).toBe(-105);
+ }
+ });
+
+ it("decodes closed without snapshot", () => {
+ const event = decodePreviewEvent({
+ type: "closed",
+ threadId: "t",
+ tabId: "preview-t",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ });
+ expect(event.type).toBe("closed");
+ });
+});
+
+describe("DiscoveredLocalServer", () => {
+ it("decodes a server with process metadata", () => {
+ const server = decodeServer({
+ host: "localhost",
+ port: 5173,
+ url: "http://localhost:5173",
+ processName: "node",
+ pid: 12345,
+ });
+ expect(server.port).toBe(5173);
+ expect(server.processName).toBe("node");
+ });
+
+ it("decodes a server without process metadata", () => {
+ const server = decodeServer({
+ host: "localhost",
+ port: 3000,
+ url: "http://localhost:3000",
+ processName: null,
+ pid: null,
+ });
+ expect(server.processName).toBeNull();
+ });
+
+ it("rejects invalid ports", () => {
+ expect(() =>
+ decodeServer({
+ host: "localhost",
+ port: 0,
+ url: "http://localhost:0",
+ processName: null,
+ pid: null,
+ }),
+ ).toThrow();
+ expect(() =>
+ decodeServer({
+ host: "localhost",
+ port: 70000,
+ url: "http://localhost:70000",
+ processName: null,
+ pid: null,
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/contracts/src/preview.ts b/packages/contracts/src/preview.ts
new file mode 100644
index 000000000..f9ef049c3
--- /dev/null
+++ b/packages/contracts/src/preview.ts
@@ -0,0 +1,181 @@
+/**
+ * Preview - Schemas for the in-app browser preview surface.
+ *
+ * The preview is desktop-only (Chromium <webview>); the server tracks per-thread
+ * tab metadata so it survives client reconnects and multi-window. The desktop
+ * renderer mediates: it owns the actual <webview> and reports navigation back to
+ * the server via these RPCs, the server fans events to all subscribers.
+ *
+ * @module Preview
+ */
+import { Schema } from "effect";
+import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(2048));
+const Title = Schema.String.check(Schema.isMaxLength(512));
+
+export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
+export type PreviewTabId = typeof PreviewTabId.Type;
+
+export const PreviewNavStatus = Schema.Union([
+ Schema.TaggedStruct("Idle", {}),
+ Schema.TaggedStruct("Loading", {
+ url: Url,
+ title: Title,
+ }),
+ Schema.TaggedStruct("Success", {
+ url: Url,
+ title: Title,
+ }),
+ Schema.TaggedStruct("LoadFailed", {
+ url: Url,
+ title: Title,
+ code: Schema.Int,
+ description: Schema.String,
+ }),
+]);
+export type PreviewNavStatus = typeof PreviewNavStatus.Type;
+
+export const PreviewSessionSnapshot = Schema.Struct({
+ threadId: TrimmedNonEmptyString,
+ tabId: PreviewTabId,
+ navStatus: PreviewNavStatus,
+ canGoBack: Schema.Boolean,
+ canGoForward: Schema.Boolean,
+ updatedAt: Schema.String,
+});
+export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
+
+export const PreviewOpenInput = Schema.Struct({
+ threadId: ThreadId,
+ /** Omit to create an empty (Idle) tab the user can type into. */
+ url: Schema.optional(Url),
+});
+export type PreviewOpenInput = typeof PreviewOpenInput.Type;
+
+export const PreviewNavigateInput = Schema.Struct({
+ threadId: ThreadId,
+ tabId: PreviewTabId,
+ url: Url,
+ resolvedTitle: Schema.optional(Title),
+});
+export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
+
+export const PreviewReportStatusInput = Schema.Struct({
+ threadId: ThreadId,
+ tabId: PreviewTabId,
+ navStatus: PreviewNavStatus,
+ canGoBack: Schema.Boolean,
+ canGoForward: Schema.Boolean,
+});
+export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
+
+export const PreviewRefreshInput = Schema.Struct({
+ threadId: ThreadId,
+ tabId: PreviewTabId,
+});
+export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
+
+export const PreviewCloseInput = Schema.Struct({
+ threadId: ThreadId,
+ tabId: Schema.optional(PreviewTabId),
+});
+export type PreviewCloseInput = typeof PreviewCloseInput.Type;
+
+export const PreviewListInput = Schema.Struct({
+ threadId: ThreadId,
+});
+export type PreviewListInput = typeof PreviewListInput.Type;
+
+export const PreviewListResult = Schema.Struct({
+ sessions: Schema.Array(PreviewSessionSnapshot),
+});
+export type PreviewListResult = typeof PreviewListResult.Type;
+
+const PreviewEventBaseSchema = Schema.Struct({
+ threadId: TrimmedNonEmptyString,
+ tabId: PreviewTabId,
+ createdAt: Schema.String,
+});
+
+const PreviewOpenedEvent = Schema.Struct({
+ ...PreviewEventBaseSchema.fields,
+ type: Schema.Literal("opened"),
+ snapshot: PreviewSessionSnapshot,
+});
+
+const PreviewNavigatedEvent = Schema.Struct({
+ ...PreviewEventBaseSchema.fields,
+ type: Schema.Literal("navigated"),
+ snapshot: PreviewSessionSnapshot,
+});
+
+const PreviewFailedEvent = Schema.Struct({
+ ...PreviewEventBaseSchema.fields,
+ type: Schema.Literal("failed"),
+ url: Url,
+ title: Title,
+ code: Schema.Int,
+ description: Schema.String,
+});
+
+const PreviewClosedEvent = Schema.Struct({
+ ...PreviewEventBaseSchema.fields,
+ type: Schema.Literal("closed"),
+});
+
+export const PreviewEvent = Schema.Union([
+ PreviewOpenedEvent,
+ PreviewNavigatedEvent,
+ PreviewFailedEvent,
+ PreviewClosedEvent,
+]);
+export type PreviewEvent = typeof PreviewEvent.Type;
+
+/**
+ * A localhost server detected by the port scanner. Used to populate the
+ * "Local" recommendations in the empty-state of the preview panel.
+ */
+export const DiscoveredLocalServer = Schema.Struct({
+ host: TrimmedNonEmptyString,
+ port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
+ url: Url,
+ processName: Schema.NullOr(TrimmedNonEmptyString),
+ pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
+});
+export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
+
+export const DiscoveredLocalServerList = Schema.Struct({
+ servers: Schema.Array(DiscoveredLocalServer),
+ scannedAt: Schema.String,
+});
+export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
+
+export class PreviewSessionLookupError extends Schema.TaggedErrorClass<PreviewSessionLookupError>()(
+ "PreviewSessionLookupError",
+ {
+ threadId: Schema.String,
+ tabId: Schema.String,
+ },
+) {
+ override get message() {
+ return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
+ }
+}
+
+export class PreviewInvalidUrlError extends Schema.TaggedErrorClass<PreviewInvalidUrlError>()(
+ "PreviewInvalidUrlError",
+ {
+ rawUrl: Schema.String,
+ detail: Schema.optional(Schema.String),
+ },
+) {
+ override get message() {
+ return this.detail
+ ? `Invalid preview URL: ${this.rawUrl} (${this.detail})`
+ : `Invalid preview URL: ${this.rawUrl}`;
+ }
+}
+
+export const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);
+export type PreviewError = typeof PreviewError.Type;
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 5a145f3f6..e8cba6ebe 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -85,6 +85,19 @@ import {
TerminalSessionSnapshot,
TerminalWriteInput,
} from "./terminal.ts";
+import {
+ DiscoveredLocalServerList,
+ PreviewCloseInput,
+ PreviewError,
+ PreviewEvent,
+ PreviewListInput,
+ PreviewListResult,
+ PreviewNavigateInput,
+ PreviewOpenInput,
+ PreviewRefreshInput,
+ PreviewReportStatusInput,
+ PreviewSessionSnapshot,
+} from "./preview.ts";
import {
ServerConfigStreamEvent,
ServerConfig,
@@ -157,6 +170,14 @@ export const WS_METHODS = {
terminalRestart: "terminal.restart",
terminalClose: "terminal.close",
+ // Preview methods
+ previewOpen: "preview.open",
+ previewNavigate: "preview.navigate",
+ previewRefresh: "preview.refresh",
+ previewClose: "preview.close",
+ previewList: "preview.list",
+ previewReportStatus: "preview.reportStatus",
+
// Server meta
serverGetConfig: "server.getConfig",
serverRefreshProviders: "server.refreshProviders",
@@ -184,6 +205,8 @@ export const WS_METHODS = {
subscribeVcsStatus: "subscribeVcsStatus",
subscribeTerminalEvents: "subscribeTerminalEvents",
subscribeTerminalMetadata: "subscribeTerminalMetadata",
+ subscribePreviewEvents: "subscribePreviewEvents",
+ subscribeDiscoveredLocalServers: "subscribeDiscoveredLocalServers",
subscribeServerConfig: "subscribeServerConfig",
subscribeServerLifecycle: "subscribeServerLifecycle",
subscribeAuthAccess: "subscribeAuthAccess",
@@ -454,6 +477,53 @@ export const WsTerminalCloseRpc = Rpc.make(WS_METHODS.terminalClose, {
error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),
});
+export const WsPreviewOpenRpc = Rpc.make(WS_METHODS.previewOpen, {
+ payload: PreviewOpenInput,
+ success: PreviewSessionSnapshot,
+ error: PreviewError,
+});
+
+export const WsPreviewNavigateRpc = Rpc.make(WS_METHODS.previewNavigate, {
+ payload: PreviewNavigateInput,
+ success: PreviewSessionSnapshot,
+ error: PreviewError,
+});
+
+export const WsPreviewRefreshRpc = Rpc.make(WS_METHODS.previewRefresh, {
+ payload: PreviewRefreshInput,
+ error: PreviewError,
+});
+
+export const WsPreviewCloseRpc = Rpc.make(WS_METHODS.previewClose, {
+ payload: PreviewCloseInput,
+ error: PreviewError,
+});
+
+export const WsPreviewListRpc = Rpc.make(WS_METHODS.previewList, {
+ payload: PreviewListInput,
+ success: PreviewListResult,
+});
+
+export const WsPreviewReportStatusRpc = Rpc.make(WS_METHODS.previewReportStatus, {
+ payload: PreviewReportStatusInput,
+ error: PreviewError,
+});
+
+export const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, {
+ payload: Schema.Struct({}),
+ success: PreviewEvent,
+ stream: true,
+});
+
+export const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(
+ WS_METHODS.subscribeDiscoveredLocalServers,
+ {
+ payload: Schema.Struct({}),
+ success: DiscoveredLocalServerList,
+ stream: true,
+ },
+);
+
export const WsOrchestrationDispatchCommandRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.dispatchCommand,
{
@@ -589,6 +659,14 @@ export const WsRpcGroup = RpcGroup.make(
WsTerminalCloseRpc,
WsSubscribeTerminalEventsRpc,
WsSubscribeTerminalMetadataRpc,
+ WsPreviewOpenRpc,
+ WsPreviewNavigateRpc,
+ WsPreviewRefreshRpc,
+ WsPreviewCloseRpc,
+ WsPreviewListRpc,
+ WsPreviewReportStatusRpc,
+ WsSubscribePreviewEventsRpc,
+ WsSubscribeDiscoveredLocalServersRpc,
WsSubscribeServerConfigRpc,
WsSubscribeServerLifecycleRpc,
WsSubscribeAuthAccessRpc,
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 97af1fa58..791e66951 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -150,6 +150,10 @@
"./relayClient": {
"types": "./src/relayClient.ts",
"import": "./src/relayClient.ts"
+ },
+ "./preview": {
+ "types": "./src/preview.ts",
+ "import": "./src/preview.ts"
}
},
"scripts": {
diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts
index 3cc2e9136..ca4942cf9 100644
--- a/packages/shared/src/keybindings.ts
+++ b/packages/shared/src/keybindings.ts
@@ -24,6 +24,13 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
+ { key: "mod+shift+j", command: "preview.toggle" },
+ { key: "mod+r", command: "preview.refresh", when: "previewFocus" },
+ { key: "mod+l", command: "preview.focusUrl", when: "previewFocus" },
+ { key: "mod+=", command: "preview.zoomIn", when: "previewFocus" },
+ { key: "mod++", command: "preview.zoomIn", when: "previewFocus" },
+ { key: "mod+-", command: "preview.zoomOut", when: "previewFocus" },
+ { key: "mod+0", command: "preview.resetZoom", when: "previewFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
diff --git a/packages/shared/src/preview.test.ts b/packages/shared/src/preview.test.ts
new file mode 100644
index 000000000..e9b721724
--- /dev/null
+++ b/packages/shared/src/preview.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ isLoopbackHost,
+ isPreviewableUrl,
+ newPreviewTabId,
+ normalizePreviewUrl,
+ PreviewUrlNormalizationError,
+} from "./preview.ts";
+
+describe("newPreviewTabId", () => {
+ it("returns a unique tab id every call", () => {
+ const a = newPreviewTabId();
+ const b = newPreviewTabId();
+ expect(a).not.toBe(b);
+ expect(a.startsWith("tab_")).toBe(true);
+ });
+});
+
+describe("isLoopbackHost", () => {
+ it.each(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"])("%s is loopback", (host) => {
+ expect(isLoopbackHost(host)).toBe(true);
+ });
+
+ it.each(["example.com", "192.168.1.10", "10.0.0.1", ""])("%s is not loopback", (host) => {
+ expect(isLoopbackHost(host)).toBe(false);
+ });
+});
+
+describe("isPreviewableUrl", () => {
+ it.each([
+ "http://localhost:5173",
+ "http://127.0.0.1:3000/path",
+ "http://0.0.0.0:8080",
+ "http://[::1]:5173",
+ ])("%s is previewable", (url) => {
+ expect(isPreviewableUrl(url)).toBe(true);
+ });
+
+ it.each(["https://example.com", "ws://localhost:5173", "file:///etc/passwd", "not-a-url", ""])(
+ "%s is not previewable",
+ (url) => {
+ expect(isPreviewableUrl(url)).toBe(false);
+ },
+ );
+});
+
+describe("normalizePreviewUrl", () => {
+ it("treats bare loopback hosts as http", () => {
+ expect(normalizePreviewUrl("localhost:5173")).toBe("http://localhost:5173/");
+ expect(normalizePreviewUrl("127.0.0.1:3000")).toBe("http://127.0.0.1:3000/");
+ });
+
+ it("treats bare public hosts as https", () => {
+ expect(normalizePreviewUrl("example.com")).toBe("https://example.com/");
+ });
+
+ it("respects explicit schemes", () => {
+ expect(normalizePreviewUrl("https://localhost:5173")).toBe("https://localhost:5173/");
+ expect(normalizePreviewUrl("http://example.com/path?q=1")).toBe("http://example.com/path?q=1");
+ });
+
+ it("rejects empty input", () => {
+ expect(() => normalizePreviewUrl(" ")).toThrow(PreviewUrlNormalizationError);
+ });
+
+ it("rejects unsupported protocols", () => {
+ expect(() => normalizePreviewUrl("ftp://example.com")).toThrow(PreviewUrlNormalizationError);
+ expect(() => normalizePreviewUrl("file:///etc/passwd")).toThrow(PreviewUrlNormalizationError);
+ });
+
+ it("rejects unparseable junk", () => {
+ expect(() => normalizePreviewUrl("http://")).toThrow(PreviewUrlNormalizationError);
+ });
+});
diff --git a/packages/shared/src/preview.ts b/packages/shared/src/preview.ts
new file mode 100644
index 000000000..963023f0e
--- /dev/null
+++ b/packages/shared/src/preview.ts
@@ -0,0 +1,92 @@
+/**
+ * Pure URL helpers shared between the preview server, desktop main process,
+ * and web renderer. Centralising these guarantees the four call sites agree
+ * on what counts as "loopback" and how to normalise a free-form URL string.
+ */
+
+const TAB_ID_PREFIX = "tab_";
+
+/**
+ * Generate a fresh preview tab id. Lives in shared (not contracts) because
+ * the contracts package is schema-only — runtime helpers belong here.
+ */
+export function newPreviewTabId(): string {
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
+ return `${TAB_ID_PREFIX}${crypto.randomUUID()}`;
+ }
+ return `${TAB_ID_PREFIX}${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
+}
+
+const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
+
+/** Internal — used by `lsof` parsing where the host string is wire-formatted. */
+export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
+ ...LOOPBACK_HOSTS,
+ "*",
+ "[::]",
+ "[::1]",
+]);
+
+const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
+
+export function isLoopbackHost(host: string): boolean {
+ if (LOOPBACK_HOSTS.has(host)) return true;
+ if (host === "[::1]") return true;
+ return false;
+}
+
+/** True when a raw URL string looks like a loopback dev URL we can preview. */
+export function isPreviewableUrl(rawUrl: string): boolean {
+ try {
+ const parsed = new URL(rawUrl);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
+ return isLoopbackHost(parsed.hostname);
+ } catch {
+ return false;
+ }
+}
+
+export class PreviewUrlNormalizationError extends Error {
+ readonly rawUrl: string;
+ readonly detail: string;
+ constructor(rawUrl: string, detail: string) {
+ super(`Invalid preview URL: ${rawUrl} (${detail})`);
+ this.name = "PreviewUrlNormalizationError";
+ this.rawUrl = rawUrl;
+ this.detail = detail;
+ }
+}
+
+/**
+ * Normalise a free-form URL string into a fully-qualified `http(s)://` URL.
+ *
+ * - Bare loopback hosts (`localhost`, `localhost:5173`) become `http://...`.
+ * - Bare public hosts (`example.com`) become `https://...`.
+ * - Already-qualified URLs are validated and returned as `URL.href`.
+ *
+ * Throws `PreviewUrlNormalizationError` for empty, unparseable, or
+ * unsupported-protocol inputs.
+ */
+export function normalizePreviewUrl(rawUrl: string): string {
+ const trimmed = rawUrl.trim();
+ if (trimmed.length === 0) {
+ throw new PreviewUrlNormalizationError(rawUrl, "empty");
+ }
+ const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
+ const candidate = trimmed.includes("://")
+ ? trimmed
+ : `${useHttp ? "http" : "https"}://${trimmed}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(candidate);
+ } catch (cause) {
+ throw new PreviewUrlNormalizationError(
+ rawUrl,
+ cause instanceof Error ? cause.message : "unparseable",
+ );
+ }
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw new PreviewUrlNormalizationError(rawUrl, `unsupported protocol ${parsed.protocol}`);
+ }
+ return parsed.href;
+}