Port browser preview annotations to desktop

- Add IPC and runtime plumbing for preview annotation theming
- Generate and ship annotation CSS for the desktop overlay
- Add pointer and artifact handling for browser preview interactions
This commit is contained in:
Julius Marminge authored and Theo Browne committed 2026-06-13 22:18:37 -07:00
1 parent 6c6740e381
commit dd739c880d
72 files changed
+3639 -513

No files matched your search

+1
View File
@@ -29,6 +29,7 @@
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
@@ -0,0 +1,40 @@
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { compile } from "tailwindcss";
const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = join(directory, "..");
const sourcePath = join(appRoot, "src", "preview-annotation.css");
const preloadPath = join(appRoot, "src", "preview-pick-preload.ts");
const outputPath = join(appRoot, "src", "preview-annotation-styles.generated.ts");
const require = createRequire(import.meta.url);
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
readFile(sourcePath, "utf8"),
readFile(preloadPath, "utf8"),
readFile(join(tailwindRoot, "theme.css"), "utf8"),
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
);
const compilerInput = [
themeSource,
preflightSource,
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
].join("\n");
const compiler = await compile(compilerInput, { base: appRoot });
const css = compiler.build([...candidates]);
const encodedCss = `'${css
.replaceAll("\\", "\\\\")
.replaceAll("'", "\\'")
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await writeFile(outputPath, moduleSource);
@@ -59,6 +59,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -89,6 +90,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
}),
);
@@ -49,6 +49,7 @@ export interface DesktopEnvironmentShape {
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
@@ -183,6 +184,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
serverSettingsPath: path.join(stateDir, "settings.json"),
logDir: path.join(stateDir, "logs"),
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
@@ -1,5 +1,7 @@
import * as Effect from "effect/Effect";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { previewViewManager } from "../preview-view-manager.ts";
import * as DesktopIpc from "./DesktopIpc.ts";
import {
clearCloudAuthToken,
@@ -52,6 +54,8 @@ import { previewMethods } from "./methods/preview.ts";
export const installDesktopIpcHandlers = Effect.gen(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
previewViewManager.configureArtifactDirectory(environment.browserArtifactsDir);
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
+4
View File
@@ -54,9 +54,12 @@ 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_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
@@ -70,3 +73,4 @@ export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
+64
View File
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import type { DesktopPreviewAnnotationTheme } from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import { pathToFileURL } from "node:url";
@@ -25,6 +26,14 @@ previewViewManager.onRecordingFrame((frame) => {
}
});
previewViewManager.onPointerEvent((event) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
}
}
});
const tabIdFrom = (raw: unknown): string => {
if (typeof raw !== "object" || raw === null || !("tabId" in raw)) {
throw new Error("preview tab id is required");
@@ -43,6 +52,44 @@ const inputFrom = (raw: unknown): unknown => {
return raw.input;
};
const annotationThemeFrom = (raw: unknown): DesktopPreviewAnnotationTheme => {
if (typeof raw !== "object" || raw === null || !("theme" in raw)) {
throw new Error("preview annotation theme is required");
}
const theme = raw.theme;
if (typeof theme !== "object" || theme === null) {
throw new Error("preview annotation theme must be an object");
}
const record = theme as Record<string, unknown>;
const stringKeys = [
"radius",
"background",
"foreground",
"popover",
"popoverForeground",
"primary",
"primaryForeground",
"muted",
"mutedForeground",
"accent",
"accentForeground",
"border",
"input",
"ring",
"fontSans",
"fontMono",
] as const;
for (const key of stringKeys) {
if (typeof record[key] !== "string" || record[key].length === 0) {
throw new Error(`preview annotation theme ${key} must be a non-empty string`);
}
}
if (record["colorScheme"] !== "light" && record["colorScheme"] !== "dark") {
throw new Error("preview annotation theme colorScheme must be light or dark");
}
return record as unknown as DesktopPreviewAnnotationTheme;
};
class PreviewIpcError extends Data.TaggedError("PreviewIpcError")<{
readonly cause: unknown;
}> {}
@@ -117,6 +164,9 @@ export const previewMethods = [
preloadUrl: pathToFileURL(preloadPath).href,
};
}),
method(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, (raw) =>
previewViewManager.setAnnotationTheme(annotationThemeFrom(raw)),
),
method(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, (raw) =>
previewViewManager.pickElement(tabIdFrom(raw)),
),
@@ -126,6 +176,20 @@ export const previewMethods = [
method(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, (raw) =>
previewViewManager.captureScreenshot(tabIdFrom(raw)),
),
method(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, (raw) => {
const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
if (typeof path !== "string" || path.trim().length === 0) {
throw new Error("preview artifact path is required");
}
return previewViewManager.revealArtifact(path);
}),
method(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, (raw) => {
const path = typeof raw === "object" && raw !== null && "path" in raw ? raw.path : null;
if (typeof path !== "string" || path.trim().length === 0) {
throw new Error("preview artifact path is required");
}
return previewViewManager.copyArtifactToClipboard(path);
}),
method(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, (raw) =>
previewViewManager.automationStatus(tabIdFrom(raw)),
),
+16
View File
@@ -1,5 +1,6 @@
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
@@ -165,11 +166,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
getPreviewConfig: (environmentId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
setAnnotationTheme: (theme) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
cancelPickElement: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
captureScreenshot: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, { tabId }),
revealArtifact: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, { path }),
copyArtifactToClipboard: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, { path }),
recording: {
startScreencast: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, { tabId }),
@@ -222,5 +229,14 @@ contextBridge.exposeInMainWorld("desktopBridge", {
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
},
onPointerEvent: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, pointerEvent: unknown) => {
if (typeof pointerEvent !== "object" || pointerEvent === null) return;
listener(pointerEvent as DesktopPreviewPointerEvent);
};
ipcRenderer.on(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
},
},
} satisfies DesktopBridge);
@@ -0,0 +1,3 @@
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
export const previewAnnotationStyles =
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
+68
View File
@@ -0,0 +1,68 @@
@import "tailwindcss";
@theme inline {
--font-sans: var(--t3-font-sans);
--font-mono: var(--t3-font-mono);
--color-background: var(--t3-background);
--color-foreground: var(--t3-foreground);
--color-popover: var(--t3-popover);
--color-popover-foreground: var(--t3-popover-foreground);
--color-primary: var(--t3-primary);
--color-primary-foreground: var(--t3-primary-foreground);
--color-muted: var(--t3-muted);
--color-muted-foreground: var(--t3-muted-foreground);
--color-accent: var(--t3-accent);
--color-accent-foreground: var(--t3-accent-foreground);
--color-border: var(--t3-border);
--color-input: var(--t3-input);
--color-ring: var(--t3-ring);
--radius-sm: calc(var(--t3-radius) - 4px);
--radius-md: calc(var(--t3-radius) - 2px);
--radius-lg: var(--t3-radius);
--radius-xl: calc(var(--t3-radius) + 4px);
--radius-2xl: calc(var(--t3-radius) + 8px);
}
:host {
--t3-font-sans:
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
sans-serif;
--t3-font-mono:
"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;
--t3-radius: 0.625rem;
--t3-background: white;
--t3-foreground: oklch(0.269 0 0);
--t3-popover: white;
--t3-popover-foreground: oklch(0.269 0 0);
--t3-primary: oklch(0.488 0.217 264);
--t3-primary-foreground: white;
--t3-muted: rgb(0 0 0 / 4%);
--t3-muted-foreground: oklch(0.556 0 0);
--t3-accent: rgb(0 0 0 / 4%);
--t3-accent-foreground: oklch(0.269 0 0);
--t3-border: rgb(0 0 0 / 8%);
--t3-input: rgb(0 0 0 / 10%);
--t3-ring: oklch(0.488 0.217 264);
color: var(--t3-foreground);
font-family: var(--t3-font-sans);
}
* {
box-sizing: border-box;
border-color: var(--t3-border);
}
button,
input,
select,
textarea {
font: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);
outline-offset: 1px;
}
+275 -138
View File
@@ -2,6 +2,7 @@
import { ipcRenderer } from "electron";
import { getElementContext } from "react-grab/primitives";
import type {
DesktopPreviewAnnotationTheme,
PickedElementPayload,
PickedElementStackFrame,
PreviewAnnotationPayload,
@@ -12,16 +13,18 @@ import type {
PreviewAnnotationStyleChange,
} from "@t3tools/contracts";
import { previewAnnotationStyles } from "./preview-annotation-styles.generated.ts";
const START_PICK_CHANNEL = "preview:start-pick";
const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
const HUMAN_INPUT_CHANNEL = "preview:human-input";
const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
const Z_INDEX_OVERLAY = 2147483646;
const ACCENT = "#7c3aed";
const ACCENT_FILL = "rgba(124,58,237,0.12)";
const BLUE = "#2563eb";
const PRIMARY = "var(--t3-primary)";
const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
const MAX_MARQUEE_ELEMENTS = 20;
const CONTENT_LAYER_Z_INDEX = 1;
const CHROME_LAYER_Z_INDEX = 10;
@@ -38,17 +41,63 @@ interface SelectedElement {
interface AnnotationSession {
teardown: (notifyMain: boolean) => void;
applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
}
let activeSession: AnnotationSession | null = null;
let idSequence = 0;
let annotationTheme: DesktopPreviewAnnotationTheme | null = null;
const reportHumanInput = (event: Event): void => {
if (event.isTrusted) ipcRenderer.send(HUMAN_INPUT_CHANNEL);
const applyAnnotationTheme = (
host: HTMLElement,
theme: DesktopPreviewAnnotationTheme | null,
): void => {
if (!theme) return;
host.style.colorScheme = theme.colorScheme;
const variables = {
"--t3-radius": theme.radius,
"--t3-background": theme.background,
"--t3-foreground": theme.foreground,
"--t3-popover": theme.popover,
"--t3-popover-foreground": theme.popoverForeground,
"--t3-primary": theme.primary,
"--t3-primary-foreground": theme.primaryForeground,
"--t3-muted": theme.muted,
"--t3-muted-foreground": theme.mutedForeground,
"--t3-accent": theme.accent,
"--t3-accent-foreground": theme.accentForeground,
"--t3-border": theme.border,
"--t3-input": theme.input,
"--t3-ring": theme.ring,
"--t3-font-sans": theme.fontSans,
"--t3-font-mono": theme.fontMono,
};
for (const [name, value] of Object.entries(variables)) {
host.style.setProperty(name, value);
}
};
window.addEventListener("pointerdown", reportHumanInput, true);
window.addEventListener("keydown", reportHumanInput, true);
const reportHumanPointerInput = (event: PointerEvent): void => {
if (!event.isTrusted) return;
ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
kind: "pointer",
x: event.clientX,
y: event.clientY,
button: event.button,
});
};
const reportHumanKeyInput = (event: KeyboardEvent): void => {
if (!event.isTrusted) return;
ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
kind: "key",
key: event.key,
code: event.code,
});
};
window.addEventListener("pointerdown", reportHumanPointerInput, true);
window.addEventListener("keydown", reportHumanKeyInput, true);
const nextId = (prefix: string): string => {
idSequence += 1;
@@ -76,13 +125,15 @@ const normalizeRect = (
const isUsableRect = (rect: PreviewAnnotationRect): boolean => rect.width >= 3 && rect.height >= 3;
function unionRects(rects: ReadonlyArray<PreviewAnnotationRect>): PreviewAnnotationRect | null {
function unionRects(
rects: ReadonlyArray<PreviewAnnotationRect>,
padding = 20,
): PreviewAnnotationRect | null {
if (rects.length === 0) return null;
const left = Math.min(...rects.map((rect) => rect.x));
const top = Math.min(...rects.map((rect) => rect.y));
const right = Math.max(...rects.map((rect) => rect.x + rect.width));
const bottom = Math.max(...rects.map((rect) => rect.y + rect.height));
const padding = 20;
const x = Math.max(0, left - padding);
const y = Math.max(0, top - padding);
const maxWidth = Math.max(1, window.innerWidth - x);
@@ -151,19 +202,13 @@ function positionBox(node: HTMLElement, rect: PreviewAnnotationRect): void {
function createLabel(): HTMLDivElement {
const label = document.createElement("div");
label.setAttribute(OVERLAY_ATTRIBUTE, "");
label.className =
"fixed z-1 max-w-70 overflow-hidden rounded-md bg-primary px-2 py-1 font-sans text-xs font-semibold text-primary-foreground shadow-md";
label.style.cssText = [
"position:fixed",
"pointer-events:none",
`background:${ACCENT}`,
"color:white",
"font:600 11px/1.2 ui-sans-serif,system-ui,-apple-system,sans-serif",
"padding:2px 6px",
"border-radius:4px",
"white-space:nowrap",
"max-width:280px",
"overflow:hidden",
"text-overflow:ellipsis",
"box-shadow:0 1px 3px rgba(0,0,0,.3)",
`z-index:${CONTENT_LAYER_Z_INDEX}`,
].join(";");
return label;
@@ -222,22 +267,15 @@ function createButton(label: string, title: string): HTMLButtonElement {
button.type = "button";
button.textContent = label;
button.title = title;
button.style.cssText = [
"border:0",
"border-radius:7px",
"padding:6px 9px",
"font:600 12px/1 ui-sans-serif,system-ui,-apple-system,sans-serif",
"background:transparent",
"color:#27272a",
"cursor:pointer",
].join(";");
button.className =
"inline-flex h-7 cursor-pointer items-center justify-center rounded-md border border-transparent px-2 font-sans text-xs font-medium text-foreground outline-none hover:bg-accent disabled:pointer-events-none disabled:opacity-60";
return button;
}
function styleControl(input: HTMLInputElement | HTMLSelectElement): void {
input.setAttribute("aria-label", input.getAttribute("aria-label") ?? "Style value");
input.style.cssText +=
";min-width:0;width:100%;height:26px;border:0;border-radius:7px;background:rgba(255,255,255,.78);color:#27272a;padding:3px 8px;box-sizing:border-box;font:500 11px/1 ui-monospace,SFMono-Regular,Menlo,monospace;outline:none;box-shadow:inset 0 0 0 1px rgba(0,0,0,.09);appearance:none";
input.className =
"h-7 min-w-0 w-full appearance-none rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground shadow-xs outline-none";
}
function createUnitControl(input: HTMLInputElement): HTMLElement {
@@ -245,8 +283,8 @@ function createUnitControl(input: HTMLInputElement): HTMLElement {
wrapper.style.cssText = "position:relative;min-width:0";
const unit = document.createElement("span");
unit.textContent = input.dataset.unit ?? "";
unit.style.cssText =
"position:absolute;right:8px;top:50%;transform:translateY(-50%);pointer-events:none;color:#a1a1aa;font:500 10px/1 ui-monospace,SFMono-Regular,Menlo,monospace";
unit.className =
"pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 font-mono text-xs text-muted-foreground";
wrapper.append(input, unit);
return wrapper;
}
@@ -256,8 +294,8 @@ function createField(
input: HTMLInputElement | HTMLSelectElement,
): HTMLLabelElement {
const label = document.createElement("label");
label.style.cssText =
"display:grid;grid-template-columns:82px minmax(0,1fr);align-items:center;gap:8px;min-height:28px;font:500 11px/1.2 ui-sans-serif,system-ui;color:#52525b";
label.className =
"grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
const text = document.createElement("span");
text.textContent = labelText;
styleControl(input);
@@ -270,7 +308,7 @@ function createField(
function createStyleSection(): HTMLElement {
const section = document.createElement("section");
section.style.cssText = "display:grid;gap:3px;padding:7px 0;border-top:1px solid rgba(0,0,0,.07)";
section.className = "grid gap-1 border-t border-border py-2";
return section;
}
@@ -314,16 +352,27 @@ function strokeBounds(
function startAnnotation(): void {
activeSession?.teardown(false);
let finished = false;
const host = document.createElement("div");
host.setAttribute(OVERLAY_ATTRIBUTE, "");
host.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY};pointer-events:none`;
applyAnnotationTheme(host, annotationTheme);
const shadowRoot = host.attachShadow({ mode: "closed" });
const themeStyle = document.createElement("style");
themeStyle.textContent = previewAnnotationStyles;
shadowRoot.appendChild(themeStyle);
const root = document.createElement("div");
root.setAttribute(OVERLAY_ATTRIBUTE, "");
root.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY};pointer-events:none;font-family:ui-sans-serif,system-ui,-apple-system,sans-serif`;
root.className = "fixed inset-0 font-sans text-foreground";
root.style.cssText = "pointer-events:none";
const cursorStyle = document.createElement("style");
cursorStyle.setAttribute(OVERLAY_ATTRIBUTE, "");
cursorStyle.textContent = `html[data-t3code-annotation-tool] body, html[data-t3code-annotation-tool] body * { cursor: crosshair !important; } [${OVERLAY_ATTRIBUTE}], [${OVERLAY_ATTRIBUTE}] * { cursor: default !important; } [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-inner-spin-button, [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-outer-spin-button { appearance:none; margin:0; }`;
root.appendChild(cursorStyle);
document.documentElement.appendChild(cursorStyle);
shadowRoot.appendChild(root);
const hoverOutline = createBox(BLUE, "rgba(37,99,235,.10)");
const marqueeBox = createBox(ACCENT, ACCENT_FILL);
const hoverOutline = createBox(PRIMARY, PRIMARY_FILL);
const marqueeBox = createBox(PRIMARY, PRIMARY_FILL);
root.append(hoverOutline, marqueeBox);
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
@@ -337,58 +386,56 @@ function startAnnotation(): void {
const toolbar = document.createElement("div");
toolbar.setAttribute(OVERLAY_ATTRIBUTE, "");
toolbar.style.cssText = `position:fixed;top:10px;left:50%;transform:translateX(-50%);z-index:${CHROME_LAYER_Z_INDEX};pointer-events:auto;display:flex;gap:2px;padding:3px;border:1px solid rgba(0,0,0,.10);border-radius:9px;background:rgba(255,255,255,.94);box-shadow:0 5px 16px rgba(0,0,0,.12);backdrop-filter:blur(12px)`;
toolbar.className =
"pointer-events-auto fixed top-2.5 left-1/2 flex -translate-x-1/2 gap-0.5 rounded-lg border border-border bg-popover/95 p-1 text-popover-foreground shadow-lg backdrop-blur-xl";
toolbar.style.zIndex = String(CHROME_LAYER_Z_INDEX);
root.appendChild(toolbar);
const editor = document.createElement("div");
editor.setAttribute(OVERLAY_ATTRIBUTE, "");
editor.style.cssText = `position:fixed;right:12px;bottom:12px;z-index:${CHROME_LAYER_Z_INDEX};width:min(306px,calc(100vw - 24px));max-height:calc(100vh - 32px);overflow:hidden;pointer-events:auto;display:none;flex-direction:column;border:1px solid rgba(0,0,0,.09);border-radius:14px;background:rgba(255,255,255,.96);box-shadow:0 14px 36px rgba(0,0,0,.18);color:#18181b;box-sizing:border-box;backdrop-filter:blur(18px)`;
editor.className =
"pointer-events-auto fixed hidden max-h-[calc(100vh-16px)] w-[min(360px,calc(100vw-16px))] flex-col overflow-hidden rounded-xl border border-border bg-popover/96 text-popover-foreground shadow-2xl backdrop-blur-xl";
editor.style.zIndex = String(CHROME_LAYER_Z_INDEX);
root.appendChild(editor);
const editorHeader = document.createElement("div");
editorHeader.style.cssText =
"display:flex;align-items:center;gap:7px;padding:7px 8px;border-bottom:1px solid rgba(0,0,0,.06);cursor:grab;user-select:none";
const adjustIcon = document.createElement("div");
adjustIcon.innerHTML =
'<svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><path d="M3 6h8M15 6h2M3 14h2M9 14h8M11 3v6M7 11v6" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/><circle cx="13" cy="6" r="2" fill="white" stroke="currentColor" stroke-width="1.5"/><circle cx="7" cy="14" r="2" fill="white" stroke="currentColor" stroke-width="1.5"/></svg>';
adjustIcon.style.cssText =
"display:grid;place-items:center;width:24px;height:24px;border-radius:999px;background:#f4f4f5;color:#52525b;font:700 14px/1 ui-sans-serif";
editorHeader.appendChild(adjustIcon);
const composerRow = document.createElement("div");
composerRow.className = "flex items-start gap-2 p-2";
const status = document.createElement("div");
status.style.cssText =
"min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:600 11px/1.2 ui-sans-serif,system-ui;color:#71717a";
editorHeader.appendChild(status);
const dragHandle = document.createElement("div");
dragHandle.textContent = "⠿";
dragHandle.title = "Drag annotation editor";
dragHandle.style.cssText = "color:#a1a1aa;font:700 18px/1 ui-sans-serif";
editorHeader.appendChild(dragHandle);
editor.appendChild(editorHeader);
const adjust = createButton("", "Expand annotation editor");
adjust.setAttribute("aria-label", "Expand annotation editor");
adjust.setAttribute("aria-expanded", "false");
adjust.className +=
" h-8 w-8 shrink-0 bg-muted p-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground";
adjust.innerHTML =
'<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true"><path d="M4 5h12M4 10h12M4 15h12M7 3v4M13 8v4M9 13v4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
composerRow.appendChild(adjust);
const comment = document.createElement("textarea");
comment.placeholder = "Describe the change…";
comment.rows = 2;
comment.style.cssText =
"width:100%;resize:none;min-height:48px;border:0;padding:10px 12px;font:500 12px/1.35 ui-sans-serif,system-ui;color:#18181b;box-sizing:border-box;outline:none;background:transparent";
editor.appendChild(comment);
comment.rows = 1;
comment.className =
"min-h-8 max-h-24 min-w-0 flex-1 resize-none overflow-y-hidden border-0 border-b border-b-transparent bg-transparent px-0 py-1.5 font-sans text-sm leading-5 text-foreground outline-none ring-0 placeholder:text-muted-foreground focus:border-b-primary focus:outline-none focus:ring-0";
composerRow.appendChild(comment);
const dragHandle = document.createElement("button");
dragHandle.type = "button";
dragHandle.textContent = "⠿";
dragHandle.title = "Drag annotation editor";
dragHandle.className =
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
editor.appendChild(composerRow);
const stylePanel = document.createElement("div");
stylePanel.style.cssText =
"display:none;max-height:min(380px,calc(100vh - 180px));overflow:auto;padding:0 10px;background:rgba(250,250,250,.62);border-top:1px solid rgba(0,0,0,.06)";
stylePanel.className =
"hidden max-h-[min(176px,calc(100vh-180px))] overflow-auto border-t border-border bg-muted/40 px-3";
editor.appendChild(stylePanel);
const footer = document.createElement("div");
footer.style.cssText =
"display:flex;align-items:center;justify-content:space-between;gap:8px;padding:7px 8px;border-top:1px solid rgba(0,0,0,.06);background:rgba(255,255,255,.92)";
const adjust = createButton("Adjust", "Show style controls for selected elements");
adjust.style.cssText +=
";display:none;padding:5px 7px;color:#52525b;background:#f4f4f5;font-size:11px";
const submit = createButton("Attach", "Attach annotation and screenshot");
submit.style.cssText += `;background:${ACCENT};color:white;padding:6px 9px;font-size:11px`;
footer.append(adjust, submit);
editor.appendChild(footer);
const selected = new Map<Element, SelectedElement>();
const regions: PreviewAnnotationRegionTarget[] = [];
const strokes: PreviewAnnotationStrokeTarget[] = [];
@@ -398,28 +445,30 @@ function startAnnotation(): void {
let dragStart: PreviewAnnotationPoint | null = null;
let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null;
let pendingCapture = false;
let stylesExpanded = false;
let editorExpanded = false;
let editorWasShown = false;
let editorPosition: { left: number; top: number } | null = null;
let editorDrag: { pointerId: number; offsetX: number; offsetY: number } | null = null;
let editorLayoutFrame: number | null = null;
const resizeComment = (): void => {
const maxHeight = 96;
comment.style.height = "auto";
const nextHeight = Math.min(comment.scrollHeight, maxHeight);
comment.style.height = `${nextHeight}px`;
comment.style.overflowY = comment.scrollHeight > maxHeight ? "auto" : "hidden";
queueEditorLayout();
};
comment.addEventListener("input", resizeComment);
const updateStatus = (): void => {
const parts = [
selected.size > 0 ? `${selected.size} element${selected.size === 1 ? "" : "s"}` : "",
regions.length > 0 ? `${regions.length} region${regions.length === 1 ? "" : "s"}` : "",
strokes.length > 0 ? `${strokes.length} drawing${strokes.length === 1 ? "" : "s"}` : "",
].filter(Boolean);
const hasTargets = parts.length > 0;
status.textContent = parts.join(" · ");
const hasTargets = selected.size > 0 || regions.length > 0 || strokes.length > 0;
editor.style.display = hasTargets ? "flex" : "none";
submit.disabled = !hasTargets;
submit.style.opacity = hasTargets ? "1" : "0.45";
adjust.style.display = selected.size > 0 ? "block" : "none";
if (selected.size === 0 && stylesExpanded) {
stylesExpanded = false;
stylePanel.style.display = "none";
adjust.textContent = "Adjust";
}
adjust.disabled = !hasTargets;
stylePanel.style.display = editorExpanded && selected.size > 0 ? "grid" : "none";
queueEditorLayout();
if (hasTargets && !editorWasShown) {
editorWasShown = true;
window.setTimeout(() => comment.focus({ preventScroll: true }), 0);
@@ -429,8 +478,9 @@ function startAnnotation(): void {
const refreshToolButtons = (): void => {
for (const [candidate, button] of toolButtons) {
const active = candidate === tool;
button.style.background = active ? ACCENT_FILL : "transparent";
button.style.color = active ? ACCENT : "#27272a";
button.classList.toggle("bg-primary/10", active);
button.classList.toggle("text-primary", active);
button.classList.toggle("text-foreground", !active);
}
if (tool !== "select") hoverOutline.style.display = "none";
if (tool !== "marquee") marqueeBox.style.display = "none";
@@ -458,7 +508,7 @@ function startAnnotation(): void {
const target: SelectedElement = {
id: nextId("element"),
element,
outline: createBox(ACCENT, ACCENT_FILL),
outline: createBox(PRIMARY, PRIMARY_FILL),
label: createLabel(),
baselineStyles: new Map(),
};
@@ -466,7 +516,10 @@ function startAnnotation(): void {
root.append(target.outline, target.label);
updateSelectedVisual(target);
updateStatus();
if (stylesExpanded) syncStyleControls();
if (editorExpanded) {
stylePanel.style.display = "grid";
syncStyleControls();
}
};
const toggleSelected = (element: Element, additive: boolean): void => {
@@ -552,13 +605,13 @@ function startAnnotation(): void {
section: HTMLElement,
): { row: HTMLLabelElement; color: HTMLInputElement; text: HTMLInputElement } => {
const row = document.createElement("label");
row.style.cssText =
"display:grid;grid-template-columns:82px minmax(0,1fr);align-items:center;gap:8px;min-height:28px;font:500 11px/1.2 ui-sans-serif,system-ui;color:#52525b";
row.className =
"grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
const label = document.createElement("span");
label.textContent = labelText;
const control = document.createElement("div");
control.style.cssText =
"display:grid;grid-template-columns:22px minmax(0,1fr);align-items:center;gap:5px;height:26px;padding:2px 5px;border-radius:7px;background:rgba(255,255,255,.78);box-shadow:inset 0 0 0 1px rgba(0,0,0,.09)";
control.className =
"grid h-7 grid-cols-[22px_minmax(0,1fr)] items-center gap-1 rounded-md border border-input bg-background px-1 shadow-xs";
const color = document.createElement("input");
color.type = "color";
color.setAttribute("aria-label", labelText);
@@ -567,8 +620,8 @@ function startAnnotation(): void {
const text = document.createElement("input");
text.type = "text";
text.setAttribute("aria-label", `${labelText} value`);
text.style.cssText =
"min-width:0;width:100%;border:0;background:transparent;color:#52525b;font:500 10px/1 ui-monospace,SFMono-Regular,Menlo,monospace;outline:none";
text.className =
"min-w-0 w-full border-0 bg-transparent font-mono text-xs text-foreground outline-none";
color.addEventListener("input", () => {
text.value = color.value;
setStyleForSelected(property, color.value);
@@ -594,7 +647,7 @@ function startAnnotation(): void {
opacity.max = "1";
opacity.step = "0.05";
opacity.value = "1";
opacity.style.accentColor = ACCENT;
opacity.style.accentColor = PRIMARY;
opacity.addEventListener("input", () => setStyleForSelected("opacity", opacity.value));
colorsSection.appendChild(createField("Opacity", opacity));
@@ -623,8 +676,7 @@ function startAnnotation(): void {
dimensions.style.cssText =
"display:grid;grid-template-columns:82px minmax(0,1fr);gap:8px;align-items:center";
const dimensionLabel = document.createElement("div");
dimensionLabel.style.cssText =
"display:grid;gap:9px;font:500 11px/1.2 ui-sans-serif,system-ui;color:#52525b";
dimensionLabel.className = "grid gap-2 font-sans text-xs font-medium text-muted-foreground";
dimensionLabel.innerHTML = "<span>Width</span><span>Height</span>";
const dimensionControls = document.createElement("div");
dimensionControls.style.cssText = "position:relative;display:grid;gap:3px;padding-left:22px";
@@ -635,7 +687,8 @@ function startAnnotation(): void {
const aspectLock = createButton("", "Lock aspect ratio");
aspectLock.setAttribute("aria-pressed", "true");
aspectLock.style.cssText +=
";position:absolute;left:0;top:50%;transform:translateY(-50%);width:18px;height:38px;padding:0;border-radius:6px;background:#ede9fe;color:#6d28d9";
";position:absolute;left:0;top:50%;transform:translateY(-50%);width:18px;height:38px;padding:0";
aspectLock.className += " bg-primary/10 text-primary";
dimensionControls.append(
createUnitControl(widthInput),
createUnitControl(heightInput),
@@ -651,8 +704,10 @@ function startAnnotation(): void {
? '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="M8 6.5 9.5 5A3.5 3.5 0 0 1 14.5 10l-1.5 1.5M12 13.5 10.5 15A3.5 3.5 0 0 1 5.5 10L7 8.5M7.5 12.5l5-5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>'
: '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m6 6 8 8M8 6.5 9.5 5A3.5 3.5 0 0 1 14 9M12 13.5 10.5 15A3.5 3.5 0 0 1 6 11" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>';
aspectLock.setAttribute("aria-pressed", String(aspectLocked));
aspectLock.style.background = aspectLocked ? "#ede9fe" : "#f4f4f5";
aspectLock.style.color = aspectLocked ? "#6d28d9" : "#71717a";
aspectLock.classList.toggle("bg-primary/10", aspectLocked);
aspectLock.classList.toggle("text-primary", aspectLocked);
aspectLock.classList.toggle("bg-muted", !aspectLocked);
aspectLock.classList.toggle("text-muted-foreground", !aspectLocked);
};
aspectLock.addEventListener("click", () => {
aspectLocked = !aspectLocked;
@@ -733,7 +788,7 @@ function startAnnotation(): void {
];
for (const [candidate, label, title] of tools) {
const button = createButton(label, title);
button.style.cssText += ";padding:5px 7px;font-size:11px;border-radius:6px";
button.className += " h-8 px-2.5 text-sm";
button.addEventListener("click", () => {
tool = candidate;
refreshToolButtons();
@@ -742,14 +797,6 @@ function startAnnotation(): void {
toolbar.appendChild(button);
}
adjust.addEventListener("click", () => {
if (selected.size === 0) return;
stylesExpanded = !stylesExpanded;
stylePanel.style.display = stylesExpanded ? "grid" : "none";
adjust.textContent = stylesExpanded ? "Hide styles" : "Adjust";
if (stylesExpanded) syncStyleControls();
});
const clampEditorPosition = (left: number, top: number): { left: number; top: number } => {
const margin = 8;
const rect = editor.getBoundingClientRect();
@@ -766,23 +813,98 @@ function startAnnotation(): void {
};
const applyEditorPosition = (position: { left: number; top: number }): void => {
editorPosition = clampEditorPosition(position.left, position.top);
editor.style.left = `${editorPosition.left}px`;
editor.style.top = `${editorPosition.top}px`;
const clamped = clampEditorPosition(position.left, position.top);
editor.style.left = `${clamped.left}px`;
editor.style.top = `${clamped.top}px`;
editor.style.right = "auto";
editor.style.bottom = "auto";
if (editorExpanded) editorPosition = clamped;
};
const getAnnotationBounds = (): PreviewAnnotationRect | null =>
unionRects(
[
...Array.from(selected.values(), (target) =>
rectFromDomRect(target.element.getBoundingClientRect()),
),
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
],
0,
);
const positionCompactEditor = (): void => {
const bounds = getAnnotationBounds();
if (!bounds) return;
const editorRect = editor.getBoundingClientRect();
const gap = 8;
const candidates = [
{ left: bounds.x + bounds.width + gap, top: bounds.y },
{ left: bounds.x - editorRect.width - gap, top: bounds.y },
{
left: bounds.x + bounds.width - editorRect.width,
top: bounds.y + bounds.height + gap,
},
{
left: bounds.x + bounds.width - editorRect.width,
top: bounds.y - editorRect.height - gap,
},
];
const overflow = (position: { left: number; top: number }): number =>
Math.max(0, -position.left) +
Math.max(0, -position.top) +
Math.max(0, position.left + editorRect.width - window.innerWidth) +
Math.max(0, position.top + editorRect.height - window.innerHeight);
const best = candidates.reduce((current, candidate) =>
overflow(candidate) < overflow(current) ? candidate : current,
);
applyEditorPosition(best);
};
function queueEditorLayout(): void {
if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
editorLayoutFrame = window.requestAnimationFrame(() => {
editorLayoutFrame = null;
if (editor.style.display === "none") return;
if (editorExpanded && editorPosition) applyEditorPosition(editorPosition);
else positionCompactEditor();
});
}
adjust.addEventListener("click", () => {
if (selected.size === 0) return;
if (!editorExpanded) {
const rect = editor.getBoundingClientRect();
editorExpanded = true;
editorPosition = { left: rect.left, top: rect.top };
stylePanel.style.display = selected.size > 0 ? "grid" : "none";
dragHandle.style.display = "block";
adjust.setAttribute("aria-expanded", "true");
adjust.title = "Collapse annotation editor";
adjust.setAttribute("aria-label", "Collapse annotation editor");
if (selected.size > 0) syncStyleControls();
} else {
editorExpanded = false;
editorPosition = null;
stylePanel.style.display = "none";
dragHandle.style.display = "none";
adjust.setAttribute("aria-expanded", "false");
adjust.title = "Expand annotation editor";
adjust.setAttribute("aria-label", "Expand annotation editor");
}
queueEditorLayout();
});
const onEditorPointerDown = (event: PointerEvent): void => {
if (event.button !== 0) return;
if (event.button !== 0 || !editorExpanded) return;
const rect = editor.getBoundingClientRect();
editorDrag = {
pointerId: event.pointerId,
offsetX: event.clientX - rect.left,
offsetY: event.clientY - rect.top,
};
editorHeader.setPointerCapture(event.pointerId);
editorHeader.style.cursor = "grabbing";
dragHandle.setPointerCapture(event.pointerId);
dragHandle.style.cursor = "grabbing";
event.preventDefault();
event.stopPropagation();
};
@@ -800,20 +922,20 @@ function startAnnotation(): void {
const onEditorPointerUp = (event: PointerEvent): void => {
if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
editorDrag = null;
editorHeader.style.cursor = "grab";
if (editorHeader.hasPointerCapture(event.pointerId))
editorHeader.releasePointerCapture(event.pointerId);
dragHandle.style.cursor = "grab";
if (dragHandle.hasPointerCapture(event.pointerId))
dragHandle.releasePointerCapture(event.pointerId);
event.preventDefault();
event.stopPropagation();
};
editorHeader.addEventListener("pointerdown", onEditorPointerDown);
editorHeader.addEventListener("pointermove", onEditorPointerMove);
editorHeader.addEventListener("pointerup", onEditorPointerUp);
editorHeader.addEventListener("pointercancel", onEditorPointerUp);
dragHandle.addEventListener("pointerdown", onEditorPointerDown);
dragHandle.addEventListener("pointermove", onEditorPointerMove);
dragHandle.addEventListener("pointerup", onEditorPointerUp);
dragHandle.addEventListener("pointercancel", onEditorPointerUp);
const repaint = (): void => {
for (const target of selected.values()) updateSelectedVisual(target);
if (editorPosition) applyEditorPosition(editorPosition);
queueEditorLayout();
};
const removeTargetAtPoint = (x: number, y: number): boolean => {
@@ -941,7 +1063,7 @@ function startAnnotation(): void {
if (tool === "draw") {
const stroke: PreviewAnnotationStrokeTarget = {
id: nextId("stroke"),
color: ACCENT,
color: annotationTheme?.primary ?? "#2563eb",
width: 4,
points: [dragStart],
bounds: { x: dragStart.x, y: dragStart.y, width: 1, height: 1 },
@@ -971,7 +1093,10 @@ function startAnnotation(): void {
if (found === 0) {
const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect };
regions.push(region);
const regionBox = createBox(ACCENT, "rgba(124,58,237,.06)");
const regionBox = createBox(
PRIMARY,
"color-mix(in srgb, var(--t3-primary) 6%, transparent)",
);
regionBox.setAttribute("data-region-id", region.id);
positionBox(regionBox, rect);
root.appendChild(regionBox);
@@ -1024,14 +1149,16 @@ function startAnnotation(): void {
window.removeEventListener("keydown", onKeyDown, true);
window.removeEventListener("scroll", repaint, true);
window.removeEventListener("resize", repaint);
editorHeader.removeEventListener("pointerdown", onEditorPointerDown);
editorHeader.removeEventListener("pointermove", onEditorPointerMove);
editorHeader.removeEventListener("pointerup", onEditorPointerUp);
editorHeader.removeEventListener("pointercancel", onEditorPointerUp);
dragHandle.removeEventListener("pointerdown", onEditorPointerDown);
dragHandle.removeEventListener("pointermove", onEditorPointerMove);
dragHandle.removeEventListener("pointerup", onEditorPointerUp);
dragHandle.removeEventListener("pointercancel", onEditorPointerUp);
if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
ipcRenderer.off(CANCEL_PICK_CHANNEL, onCancel);
ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
document.documentElement.removeAttribute("data-t3code-annotation-tool");
root.remove();
cursorStyle.remove();
host.remove();
activeSession = null;
if (notifyMain) ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null);
};
@@ -1115,11 +1242,21 @@ function startAnnotation(): void {
window.addEventListener("resize", repaint, { passive: true });
ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel);
ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
document.documentElement.appendChild(root);
document.documentElement.appendChild(host);
refreshToolButtons();
updateStatus();
activeSession = { teardown };
activeSession = {
teardown,
applyTheme: (theme) => applyAnnotationTheme(host, theme),
};
}
ipcRenderer.on(START_PICK_CHANNEL, () => startAnnotation());
ipcRenderer.on(START_PICK_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme | undefined) => {
if (theme) annotationTheme = theme;
startAnnotation();
});
ipcRenderer.on(ANNOTATION_THEME_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme) => {
annotationTheme = theme;
activeSession?.applyTheme(theme);
});
ipcRenderer.on(CANCEL_PICK_CHANNEL, () => activeSession?.teardown(false));
+186 -5
View File
@@ -3,16 +3,26 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const fromId = vi.fn(() => null);
const mkdir = vi.fn(async () => undefined);
const writeFile = vi.fn(async () => undefined);
const showItemInFolder = vi.fn();
const writeImage = vi.fn();
const createFromPath = vi.fn(() => ({ isEmpty: () => false }));
const webviewSend = vi.fn();
vi.mock("node:fs/promises", () => ({ mkdir, writeFile }));
vi.mock("electron", () => ({
app: {
getPath: vi.fn(() => "/tmp/t3-code-test"),
clipboard: {
writeImage,
},
nativeImage: {
createFromPath,
},
session: {
fromPartition: vi.fn(),
},
shell: {
showItemInFolder,
},
webContents: {
fromId,
},
@@ -23,6 +33,10 @@ describe("PreviewViewManager automation status", () => {
fromId.mockClear();
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
writeImage.mockClear();
createFromPath.mockClear();
webviewSend.mockClear();
});
it("reports an unregistered webview as temporarily unavailable", async () => {
@@ -59,7 +73,7 @@ describe("PreviewViewManager automation status", () => {
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com/",
getURL: () => "https://example.com:8443/path?query=value",
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
@@ -69,6 +83,7 @@ describe("PreviewViewManager automation status", () => {
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
@@ -82,13 +97,22 @@ describe("PreviewViewManager automation status", () => {
} as never);
const { PreviewViewManager } = await import("./preview-view-manager.ts");
const manager = new PreviewViewManager();
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
manager.createTab("tab_1");
manager.registerWebview("tab_1", 42);
expect(webviewSend).toHaveBeenCalledWith(
"preview:annotation-theme",
expect.objectContaining({
colorScheme: "light",
primary: "oklch(0.488 0.217 264)",
}),
);
const artifact = await manager.captureScreenshot("tab_1");
expect(capturePage).toHaveBeenCalledOnce();
expect(mkdir).toHaveBeenCalledWith("/tmp/t3-code-test/browser-artifacts", {
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts", {
recursive: true,
});
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
@@ -97,6 +121,163 @@ describe("PreviewViewManager automation status", () => {
mimeType: "image/png",
sizeBytes: png.byteLength,
});
expect(artifact.path).toMatch(/\/browser-artifacts\/browser-screenshot-[^.]+\.png$/);
expect(artifact.path).toMatch(
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
);
});
it("reveals only files inside the configured browser artifact directory", async () => {
const { PreviewViewManager } = await import("./preview-view-manager.ts");
const manager = new PreviewViewManager();
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
expect(showItemInFolder).toHaveBeenCalledWith(
"/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
);
expect(() => manager.revealArtifact("/tmp/t3/dev/settings.json")).toThrow(
"outside the configured artifact directory",
);
});
it("copies screenshot artifacts to the system clipboard", async () => {
const { PreviewViewManager } = await import("./preview-view-manager.ts");
const manager = new PreviewViewManager();
manager.configureArtifactDirectory("/tmp/t3/dev/browser-artifacts");
const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
manager.copyArtifactToClipboard(artifactPath);
expect(createFromPath).toHaveBeenCalledWith(artifactPath);
expect(writeImage).toHaveBeenCalledOnce();
expect(() => manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json")).toThrow(
"outside the configured artifact directory",
);
});
it("emits the resolved pointer target before dispatching an automation click", async () => {
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const activity: string[] = [];
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (method === "Runtime.evaluate") {
return {
result: {
value: { width: 800, height: 600 },
},
};
}
if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
activity.push("mousePressed");
humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
}
return undefined;
});
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
const { PreviewViewManager } = await import("./preview-view-manager.ts");
const manager = new PreviewViewManager();
manager.onPointerEvent((event) => activity.push(event.phase));
manager.createTab("tab_1");
manager.registerWebview("tab_1", 42);
await manager.automationClick("tab_1", { x: 120, y: 80 });
expect(activity).toEqual(["move", "click", "mousePressed"]);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
type: "mousePressed",
x: 120,
y: 80,
button: "left",
clickCount: 1,
});
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
type: "mouseReleased",
x: 120,
y: 80,
button: "left",
clickCount: 1,
});
});
it("still interrupts agent control for a different human pointer event", async () => {
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string) => {
if (method === "Runtime.evaluate") {
return {
result: {
value: { width: 800, height: 600 },
},
};
}
if (method === "Input.dispatchMouseEvent") {
humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
}
return undefined;
});
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
const { PreviewViewManager } = await import("./preview-view-manager.ts");
const manager = new PreviewViewManager();
manager.createTab("tab_1");
manager.registerWebview("tab_1", 42);
await expect(manager.automationClick("tab_1", { x: 120, y: 80 })).rejects.toMatchObject({
name: "PreviewAutomationControlInterruptedError",
});
});
});
+224 -8
View File
@@ -8,6 +8,8 @@
* here). Single layer-scoped browser session partition.
*/
import type {
DesktopPreviewAnnotationTheme,
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
DesktopPreviewRecordingArtifact,
@@ -26,9 +28,17 @@ import type {
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { app, type BrowserWindow, type Session, session, webContents } from "electron";
import {
type BrowserWindow,
type Session,
clipboard,
nativeImage,
session,
shell,
webContents,
} from "electron";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { isAbsolute, join, relative, resolve, sep } from "node:path";
import { createHash } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";
@@ -40,6 +50,7 @@ const START_PICK_CHANNEL = "preview:start-pick";
const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
const HUMAN_INPUT_CHANNEL = "preview:human-input";
// Re-export the guest webview security posture from its dedicated module so
@@ -83,6 +94,43 @@ const MAX_VISIBLE_TEXT_LENGTH = 20_000;
const MAX_INTERACTIVE_ELEMENTS = 200;
const MAX_SCREENSHOT_WIDTH = 1280;
const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
background: "white",
foreground: "oklch(0.269 0 0)",
popover: "white",
popoverForeground: "oklch(0.269 0 0)",
primary: "oklch(0.488 0.217 264)",
primaryForeground: "white",
muted: "rgb(0 0 0 / 4%)",
mutedForeground: "oklch(0.556 0 0)",
accent: "rgb(0 0 0 / 4%)",
accentForeground: "oklch(0.269 0 0)",
border: "rgb(0 0 0 / 8%)",
input: "rgb(0 0 0 / 10%)",
ring: "oklch(0.488 0.217 264)",
fontSans: "system-ui, sans-serif",
fontMono: "ui-monospace, monospace",
};
const artifactSiteSlug = (rawUrl: string): string => {
try {
const url = new URL(rawUrl);
const slug = url.hostname
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, MAX_ARTIFACT_SITE_SLUG_LENGTH)
.replace(/-+$/g, "");
return slug || "site";
} catch {
return "site";
}
};
interface CdpEvaluationResult {
readonly result?: {
@@ -182,10 +230,14 @@ const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
type Listener = (tabId: string, state: PreviewTabState) => void;
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => void;
type PreviewInputSignal =
| { readonly kind: "pointer"; readonly x: number; readonly y: number; readonly button: number }
| { readonly kind: "key"; readonly key: string; readonly code: string };
interface ManagedListeners {
navigate: () => void;
failed: (event: Event, code: number, description: string) => void;
humanInput: () => void;
humanInput: (_event: unknown, signal?: unknown) => void;
}
interface PickSession {
@@ -205,6 +257,13 @@ interface BrowserDiagnostics {
readonly requests: Map<string, { url: string; method: string }>;
}
type PointerEventListener = (event: DesktopPreviewPointerEvent) => void;
interface ExpectedAgentInput {
readonly signal: PreviewInputSignal;
readonly expiresAt: number;
}
const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
key: string;
meta: boolean;
@@ -221,23 +280,116 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
return (
"x" in value &&
typeof value.x === "number" &&
"y" in value &&
typeof value.y === "number" &&
"button" in value &&
typeof value.button === "number"
);
}
return (
value.kind === "key" &&
"key" in value &&
typeof value.key === "string" &&
"code" in value &&
typeof value.code === "string"
);
};
const inputSignalsMatch = (left: PreviewInputSignal, right: PreviewInputSignal): boolean => {
if (left.kind !== right.kind) return false;
if (left.kind === "pointer" && right.kind === "pointer") {
return (
Math.abs(left.x - right.x) <= 1 &&
Math.abs(left.y - right.y) <= 1 &&
left.button === right.button
);
}
return (
left.kind === "key" &&
right.kind === "key" &&
left.key === right.key &&
left.code === right.code
);
};
export class PreviewViewManager {
private annotationTheme = DEFAULT_ANNOTATION_THEME;
private artifactDirectory: string | null = null;
private mainWindow: BrowserWindow | null = null;
private readonly tabs = new Map<string, PreviewTabState>();
private readonly attached = new Map<number, ManagedListeners>();
private readonly browserSessions = new Map<string, Session>();
private readonly listeners = new Set<Listener>();
private readonly pointerEventListeners = new Set<PointerEventListener>();
private readonly recordingFrameListeners = new Set<RecordingFrameListener>();
/** In-flight preview annotation sessions, keyed by tabId. */
private readonly pickSessions = new Map<string, PickSession>();
/** One long-lived CDP attachment and serialized command queue per guest. */
private readonly controlSessions = new Map<number, BrowserControlSession>();
private readonly diagnostics = new Map<number, BrowserDiagnostics>();
private readonly expectedAgentInputs = new Map<string, ExpectedAgentInput[]>();
private readonly controlEpoch = new Map<string, number>();
private readonly actionTimeline = new Map<string, PreviewAutomationActionEvent[]>();
private actionSequence = 0;
private pointerSequence = 0;
private recordingTabId: string | null = null;
configureArtifactDirectory(directory: string): void {
this.artifactDirectory = resolve(directory);
}
private requireArtifactDirectory(): string {
if (!this.artifactDirectory) {
throw new Error("Preview artifact directory is not configured.");
}
return this.artifactDirectory;
}
private resolveArtifactPath(path: string): string {
const directory = this.requireArtifactDirectory();
const resolvedPath = resolve(path);
const relativePath = relative(directory, resolvedPath);
if (
relativePath.length === 0 ||
relativePath === ".." ||
relativePath.startsWith(`..${sep}`) ||
isAbsolute(relativePath)
) {
throw new Error("Preview artifact path is outside the configured artifact directory.");
}
return resolvedPath;
}
revealArtifact(path: string): void {
const resolvedPath = this.resolveArtifactPath(path);
shell.showItemInFolder(resolvedPath);
}
copyArtifactToClipboard(path: string): void {
const resolvedPath = this.resolveArtifactPath(path);
const image = nativeImage.createFromPath(resolvedPath);
if (image.isEmpty()) {
throw new Error("Preview artifact could not be loaded as an image.");
}
clipboard.writeImage(image);
}
setAnnotationTheme(theme: DesktopPreviewAnnotationTheme): void {
this.annotationTheme = theme;
for (const tab of this.tabs.values()) {
if (tab.webContentsId == null) continue;
const wc = webContents.fromId(tab.webContentsId);
if (!wc || wc.isDestroyed()) continue;
wc.send(ANNOTATION_THEME_CHANNEL, theme);
}
}
setMainWindow(window: BrowserWindow): void {
this.mainWindow = window;
}
@@ -338,6 +490,7 @@ export class PreviewViewManager {
throw new PreviewWebContentsNotFoundError(tabId, webContentsId);
}
if (tab.webContentsId === webContentsId && this.attached.has(webContentsId)) {
wc.send(ANNOTATION_THEME_CHANNEL, this.annotationTheme);
return;
}
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
@@ -366,6 +519,7 @@ export class PreviewViewManager {
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor: tab.zoomFactor,
});
wc.send(ANNOTATION_THEME_CHANNEL, this.annotationTheme);
}
async navigate(tabId: string, rawUrl: string): Promise<void> {
@@ -513,7 +667,7 @@ export class PreviewViewManager {
// wc may be torn down; the next try/catch settles.
}
try {
wc.send(START_PICK_CHANNEL);
wc.send(START_PICK_CHANNEL, this.annotationTheme);
} catch {
settle(null);
}
@@ -561,8 +715,8 @@ export class PreviewViewManager {
async captureScreenshot(tabId: string): Promise<DesktopPreviewScreenshotArtifact> {
const wc = this.requireWebContents(tabId);
const createdAt = new Date().toISOString();
const id = `browser-screenshot-${Date.now().toString(36)}`;
const directory = join(app.getPath("userData"), "browser-artifacts");
const id = `browser-screenshot-${artifactSiteSlug(wc.getURL())}-${Date.now().toString(36)}`;
const directory = this.requireArtifactDirectory();
const path = join(directory, `${id}.png`);
const data = (await wc.capturePage()).toPNG();
await mkdir(directory, { recursive: true });
@@ -587,7 +741,7 @@ export class PreviewViewManager {
const createdAt = new Date().toISOString();
const id = `browser-recording-${Date.now().toString(36)}`;
const extension = mimeType.includes("mp4") ? "mp4" : "webm";
const directory = join(app.getPath("userData"), "browser-artifacts");
const directory = this.requireArtifactDirectory();
const path = join(directory, `${id}.${extension}`);
await mkdir(directory, { recursive: true });
await writeFile(path, data);
@@ -793,6 +947,25 @@ export class PreviewViewManager {
`Click coordinates (${x}, ${y}) are outside the preview viewport.`,
);
}
this.emitPointerEvent({
tabId,
phase: "move",
x,
y,
sequence: this.pointerSequence++,
createdAt: new Date().toISOString(),
});
await sleep(AGENT_CURSOR_MOVE_MS);
this.emitPointerEvent({
tabId,
phase: "click",
x,
y,
sequence: this.pointerSequence++,
createdAt: new Date().toISOString(),
});
await sleep(AGENT_CURSOR_CLICK_LEAD_MS);
this.expectAgentInput(tabId, { kind: "pointer", x, y, button: 0 });
await send("Input.dispatchMouseEvent", {
type: "mousePressed",
x,
@@ -886,6 +1059,7 @@ export class PreviewViewManager {
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
};
this.expectAgentInput(tabId, { kind: "key", key, code: params.code });
await send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
await send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
});
@@ -1345,11 +1519,50 @@ export class PreviewViewManager {
};
}
onPointerEvent(listener: PointerEventListener): () => void {
this.pointerEventListeners.add(listener);
return () => {
this.pointerEventListeners.delete(listener);
};
}
private emitPointerEvent(event: DesktopPreviewPointerEvent): void {
for (const listener of this.pointerEventListeners) listener(event);
}
private expectAgentInput(tabId: string, signal: PreviewInputSignal): void {
const now = Date.now();
const pending = (this.expectedAgentInputs.get(tabId) ?? []).filter(
(expected) => expected.expiresAt > now,
);
pending.push({ signal, expiresAt: now + 1_000 });
this.expectedAgentInputs.set(tabId, pending);
}
private consumeExpectedAgentInput(tabId: string, signal: PreviewInputSignal): boolean {
const now = Date.now();
const pending = (this.expectedAgentInputs.get(tabId) ?? []).filter(
(expected) => expected.expiresAt > now,
);
const index = pending.findIndex((expected) => inputSignalsMatch(expected.signal, signal));
if (index < 0) {
if (pending.length === 0) this.expectedAgentInputs.delete(tabId);
else this.expectedAgentInputs.set(tabId, pending);
return false;
}
pending.splice(index, 1);
if (pending.length === 0) this.expectedAgentInputs.delete(tabId);
else this.expectedAgentInputs.set(tabId, pending);
return true;
}
destroy(): void {
for (const tabId of Array.from(this.tabs.keys())) {
this.closeTab(tabId);
}
this.listeners.clear();
this.expectedAgentInputs.clear();
this.pointerEventListeners.clear();
this.recordingFrameListeners.clear();
}
@@ -1375,7 +1588,10 @@ export class PreviewViewManager {
},
});
};
const humanInput = (): void => {
const humanInput = (_event: unknown, rawSignal?: unknown): void => {
if (isPreviewInputSignal(rawSignal) && this.consumeExpectedAgentInput(tabId, rawSignal)) {
return;
}
this.controlEpoch.set(tabId, (this.controlEpoch.get(tabId) ?? 0) + 1);
this.update(tabId, { controller: "human" });
void sleep(750).then(() => {
+4 -3
View File
@@ -14,17 +14,18 @@ export default defineConfig({
run: {
tasks: {
build: {
command: "vp pack",
command: "node scripts/build-preview-annotation-css.mjs && vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
command:
"node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "vp pack --watch",
command: "node scripts/build-preview-annotation-css.mjs && vp pack --watch",
cache: false,
},
"dev:electron": {
+2
View File
@@ -205,6 +205,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
}),
@@ -75,14 +75,16 @@ it.effect("registers annotated tools and preserves authenticated request context
height: 5,
},
}
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
: request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
@@ -146,6 +148,16 @@ it.effect("registers annotated tools and preserves authenticated request context
expect(snapshot.structuredContent).toMatchObject({
screenshot: { mimeType: "image/png", width: 10, height: 5 },
});
const press = yield* server
.callTool({ name: "preview_press", arguments: { key: "Enter" } })
.pipe(
Effect.provideService(McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(press.isError).toBe(false);
expect(press.structuredContent).toBeUndefined();
expect(press.content).toEqual([{ type: "text", text: "null" }]);
}),
).pipe(Effect.provide(TestLayer)),
);
+5 -2
View File
@@ -143,11 +143,14 @@ export const PreviewToolkitRegistrationLive = Layer.effectDiscard(
],
});
}
const encodedResultText = JSON.stringify(result.encodedResult) ?? "null";
return new McpSchema.CallToolResult({
isError: false,
structuredContent:
typeof result.encodedResult === "object" ? result.encodedResult : undefined,
content: [{ type: "text", text: JSON.stringify(result.encodedResult) }],
result.encodedResult !== null && typeof result.encodedResult === "object"
? result.encodedResult
: undefined,
content: [{ type: "text", text: encodedResultText }],
});
},
}),
@@ -1,18 +1,20 @@
import * as net from "node:net";
import { it as effectIt } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
import { COMMON_DEV_PORTS, PreviewPortScanner } from "../Services/PortScanner.ts";
import { COMMON_DEV_PORTS, PortDiscovery } from "../Services/PortScanner.ts";
import { ProcessRunner } from "../../processRunner.ts";
import { __testing, PreviewPortScannerLive } from "./PortScanner.ts";
import { __testing, PortDiscoveryLive } from "./PortScanner.ts";
const { parseLsofOutput, parsePortFromLsofName, serversEqual } = __testing;
const { parseLsofOutput, parsePortFromLsofName, parseWindowsListenerOutput, serversEqual } =
__testing;
const TestProcessRunner = Layer.succeed(ProcessRunner, {
run: () => Effect.die("ProcessRunner should not be used by Windows TCP probe tests"),
});
const TestPreviewPortScannerLive = PreviewPortScannerLive.pipe(Layer.provide(TestProcessRunner));
const TestPortDiscoveryLive = PortDiscoveryLive.pipe(Layer.provide(TestProcessRunner));
describe("parsePortFromLsofName", () => {
it("parses *:port", () => {
@@ -70,6 +72,7 @@ describe("parseLsofOutput", () => {
url: "http://localhost:3000",
processName: "next-server",
pid: 67890,
terminal: null,
},
{
host: "localhost",
@@ -77,6 +80,7 @@ describe("parseLsofOutput", () => {
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: null,
},
{
host: "localhost",
@@ -84,6 +88,7 @@ describe("parseLsofOutput", () => {
url: "http://localhost:9229",
processName: "next-server",
pid: 67890,
terminal: null,
},
]);
});
@@ -98,6 +103,26 @@ describe("parseLsofOutput", () => {
expect(servers).toHaveLength(1);
expect(servers[0]?.port).toBe(5173);
});
it("attributes listeners to a registered terminal process", () => {
const servers = parseLsofOutput(
["p12345", "cnode", "n*:5173"].join("\n"),
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
expect(servers[0]?.terminal).toEqual({
threadId: "thread-1",
terminalId: "terminal-1",
});
});
});
describe("serversEqual", () => {
@@ -107,6 +132,7 @@ describe("serversEqual", () => {
url: "http://localhost:5173",
processName: "node",
pid: 1,
terminal: null,
};
it("returns true for identical lists", () => {
expect(serversEqual([a], [{ ...a }])).toBe(true);
@@ -119,12 +145,43 @@ describe("serversEqual", () => {
});
});
describe("parseWindowsListenerOutput", () => {
it("parses and attributes PowerShell listener records", () => {
const servers = parseWindowsListenerOutput(
"0.0.0.0|5173|12345|node",
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
expect(servers).toEqual([
{
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: {
threadId: "thread-1",
terminalId: "terminal-1",
},
},
]);
});
});
/**
* 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)", () => {
describe("PortDiscovery integration (TCP probe fallback)", () => {
let originalPlatform: NodeJS.Platform;
let server: net.Server;
let port: number;
@@ -158,18 +215,18 @@ describe("PreviewPortScanner integration (TCP probe path)", () => {
effectIt.effect("scan() returns a server we just opened on a curated dev port", () =>
Effect.gen(function* () {
const scanner = yield* PreviewPortScanner;
const scanner = yield* PortDiscovery;
const result = yield* scanner.scan();
const found = result.find((server) => server.port === port);
expect(found).toBeDefined();
expect(found?.host).toBe("localhost");
}).pipe(Effect.provide(TestPreviewPortScannerLive)),
}).pipe(Effect.provide(TestPortDiscoveryLive)),
);
effectIt.effect("retain() drives an immediate broadcast to subscribers", () => {
const received: number[] = [];
return Effect.gen(function* () {
const scanner = yield* PreviewPortScanner;
const scanner = yield* PortDiscovery;
const unsubscribe = yield* scanner.subscribe((servers) =>
Effect.sync(() => {
for (const server of servers) received.push(server.port);
@@ -179,6 +236,6 @@ describe("PreviewPortScanner integration (TCP probe path)", () => {
unsubscribe();
release();
expect(received).toContain(port);
}).pipe(Effect.provide(TestPreviewPortScannerLive));
}).pipe(Effect.provide(TestPortDiscoveryLive));
});
});
+121 -34
View File
@@ -13,32 +13,42 @@
*/
import * as net from "node:net";
import type { DiscoveredLocalServer } from "@t3tools/contracts";
import { ThreadId, 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 { Cause, Duration, Effect, Layer, Ref, Schedule } from "effect";
import { ProcessRunner, type ProcessRunnerShape } from "../../processRunner.ts";
import { ProcessRunner } from "../../processRunner.ts";
import {
COMMON_DEV_PORTS,
PreviewPortScanner,
type PreviewPortScannerShape,
PortDiscovery,
type PortDiscoveryShape,
} from "../Services/PortScanner.ts";
const POLL_INTERVAL = Duration.seconds(3);
const TCP_PROBE_TIMEOUT_MS = 200;
const LSOF_TIMEOUT_MS = 5_000;
const WINDOWS_LISTENER_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> => {
interface TerminalProcessOwner {
readonly threadId: ThreadId;
readonly terminalId: string;
}
const terminalOwnerKey = (owner: {
readonly threadId: string;
readonly terminalId: string;
}): string => `${owner.threadId}\u0000${owner.terminalId}`;
const parseLsofOutput = (
raw: string,
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
): ReadonlyArray<DiscoveredLocalServer> => {
const seen = new Map<string, DiscoveredLocalServer>();
let pid: number | null = null;
let processName: string | null = null;
@@ -69,6 +79,7 @@ const parseLsofOutput = (raw: string): ReadonlyArray<DiscoveredLocalServer> => {
url,
processName,
pid,
terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
});
}
}
@@ -91,22 +102,31 @@ const parsePortFromLsofName = (name: string): number | null => {
return port;
};
const probeLsof = (
processRunner: ProcessRunnerShape,
): Effect.Effect<ReadonlyArray<DiscoveredLocalServer> | null> =>
processRunner
.run({
command: "lsof",
args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
timeout: Duration.millis(LSOF_TIMEOUT_MS),
maxOutputBytes: 1024 * 1024,
outputMode: "truncate",
})
.pipe(
Effect.mapError((cause) => new LsofProbeError({ cause })),
Effect.map((result) => parseLsofOutput(result.stdout)),
Effect.orElseSucceed(() => null),
);
const parseWindowsListenerOutput = (
raw: string,
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
): ReadonlyArray<DiscoveredLocalServer> => {
const seen = new Map<number, DiscoveredLocalServer>();
for (const line of raw.split(/\r?\n/g)) {
const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
const host = hostRaw?.trim() ?? "";
if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
const port = Number(portRaw);
const pid = Number(pidRaw);
if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
if (seen.has(port)) continue;
seen.set(port, {
host: "localhost",
port,
url: `http://localhost:${port}`,
processName: processNameRaw?.trim() || null,
pid: normalizedPid,
terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
});
}
return [...seen.values()].toSorted((left, right) => left.port - right.port);
};
const probeTcpPort = (port: number): Promise<boolean> =>
new Promise((resolve) => {
@@ -138,6 +158,7 @@ const probeCommonPorts = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>
url: `http://localhost:${r.port}`,
processName: null,
pid: null,
terminal: null,
}));
});
@@ -155,7 +176,9 @@ const serversEqual = (
a.port !== b.port ||
a.url !== b.url ||
a.processName !== b.processName ||
a.pid !== b.pid
a.pid !== b.pid ||
a.terminal?.threadId !== b.terminal?.threadId ||
a.terminal?.terminalId !== b.terminal?.terminalId
) {
return false;
}
@@ -163,12 +186,19 @@ const serversEqual = (
return true;
};
export const makePreviewPortScanner = Effect.gen(function* () {
export const makePortDiscovery = Effect.gen(function* () {
const processRunner = yield* ProcessRunner;
const stateRef = yield* Ref.make<ScannerState>({
lastSnapshot: [],
});
const listeners = new Set<Listener>();
const terminalProcesses = new Map<
string,
{
readonly owner: TerminalProcessOwner;
readonly processIds: ReadonlySet<number>;
}
>();
// 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.
@@ -176,11 +206,43 @@ export const makePreviewPortScanner = Effect.gen(function* () {
const scanOnce = (): Effect.Effect<ReadonlyArray<DiscoveredLocalServer>> =>
Effect.gen(function* () {
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
for (const registration of terminalProcesses.values()) {
for (const processId of registration.processIds) {
terminalByProcessId.set(processId, registration.owner);
}
}
if (process.platform === "win32") {
const command =
'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
const listeners = yield* processRunner
.run({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),
maxOutputBytes: 1024 * 1024,
outputMode: "truncate",
})
.pipe(
Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
Effect.catchCause(() => Effect.succeed(null)),
);
if (listeners !== null) return listeners;
return yield* probeCommonPorts();
}
const lsof = yield* probeLsof(processRunner);
if (lsof !== null) return lsof;
const lsofResult = yield* processRunner
.run({
command: "lsof",
args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
timeout: Duration.millis(LSOF_TIMEOUT_MS),
maxOutputBytes: 1024 * 1024,
outputMode: "truncate",
})
.pipe(
Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
Effect.catchCause(() => Effect.succeed(null)),
);
if (lsofResult !== null) return lsofResult;
return yield* probeCommonPorts();
});
@@ -204,7 +266,7 @@ export const makePreviewPortScanner = Effect.gen(function* () {
// 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"] = () =>
const retain: PortDiscoveryShape["retain"] = () =>
Effect.gen(function* () {
const wasIdle = retainCount === 0;
retainCount += 1;
@@ -221,7 +283,7 @@ export const makePreviewPortScanner = Effect.gen(function* () {
};
});
const subscribe: PreviewPortScannerShape["subscribe"] = (listener) =>
const subscribe: PortDiscoveryShape["subscribe"] = (listener) =>
Effect.sync(() => {
listeners.add(listener);
return () => {
@@ -229,18 +291,43 @@ export const makePreviewPortScanner = Effect.gen(function* () {
};
});
const registerTerminalProcesses: PortDiscoveryShape["registerTerminalProcesses"] = (input) =>
Effect.sync(() => {
const owner = {
threadId: ThreadId.make(input.threadId),
terminalId: input.terminalId,
};
const processIds = new Set(
input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
);
const key = terminalOwnerKey(owner);
if (processIds.size === 0) {
terminalProcesses.delete(key);
return;
}
terminalProcesses.set(key, { owner, processIds });
});
const unregisterTerminal: PortDiscoveryShape["unregisterTerminal"] = (input) =>
Effect.sync(() => {
terminalProcesses.delete(terminalOwnerKey(input));
});
return {
scan: scanOnce,
subscribe,
retain,
} satisfies PreviewPortScannerShape;
registerTerminalProcesses,
unregisterTerminal,
} satisfies PortDiscoveryShape;
});
export const PreviewPortScannerLive = Layer.effect(PreviewPortScanner, makePreviewPortScanner);
export const PortDiscoveryLive = Layer.effect(PortDiscovery, makePortDiscovery);
/** Exposed for tests. */
export const __testing = {
parseLsofOutput,
parsePortFromLsofName,
parseWindowsListenerOutput,
serversEqual,
};
@@ -1,17 +1,17 @@
/**
* PreviewPortScanner - Discovers listening localhost ports for the preview
* empty-state recommendations.
* PortDiscovery - Discovers listening localhost ports and attributes them to
* registered terminal process families.
*
* 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
* @module PortDiscovery
*/
import type { DiscoveredLocalServer } from "@t3tools/contracts";
import { Context, type Effect } from "effect";
export interface PreviewPortScannerShape {
export interface PortDiscoveryShape {
/** 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. */
@@ -23,12 +23,22 @@ export interface PreviewPortScannerShape {
* release fn. When release count hits 0, polling stops.
*/
readonly retain: () => Effect.Effect<() => void>;
/** Associate a terminal with its current process family for port attribution. */
readonly registerTerminalProcesses: (input: {
readonly threadId: string;
readonly terminalId: string;
readonly processIds: ReadonlyArray<number>;
}) => Effect.Effect<void>;
/** Remove process attribution for a terminal that stopped or closed. */
readonly unregisterTerminal: (input: {
readonly threadId: string;
readonly terminalId: string;
}) => Effect.Effect<void>;
}
export class PreviewPortScanner extends Context.Service<
PreviewPortScanner,
PreviewPortScannerShape
>()("t3/preview/Services/PortScanner/PreviewPortScanner") {}
export class PortDiscovery extends Context.Service<PortDiscovery, PortDiscoveryShape>()(
"t3/preview/Services/PortScanner/PortDiscovery",
) {}
/** Curated list of common dev-server ports for the Windows TCP-probe fallback. */
export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
+4 -2
View File
@@ -100,7 +100,7 @@ import { ServerRuntimeStartup, type ServerRuntimeStartupShape } from "./serverRu
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 { PortDiscovery } from "./preview/Services/PortScanner.ts";
import {
BrowserTraceCollector,
type BrowserTraceCollectorShape,
@@ -681,10 +681,12 @@ const buildAppUnderTest = (options?: {
PubSub.subscribe(pubsub),
),
}),
Layer.mock(PreviewPortScanner)({
Layer.mock(PortDiscovery)({
scan: () => Effect.succeed([]),
subscribe: () => Effect.succeed(() => {}),
retain: () => Effect.succeed(() => {}),
registerTerminalProcesses: () => Effect.void,
unregisterTerminal: () => Effect.void,
}),
),
),
+7 -5
View File
@@ -36,7 +36,7 @@ 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 { PortDiscoveryLive } from "./preview/Layers/PortScanner.ts";
import { McpHttpServerLive } from "./mcp/Layers/McpHttpServer.ts";
import { McpSessionRegistryLive } from "./mcp/Layers/McpSessionRegistry.ts";
import * as ProcessRunner from "./processRunner.ts";
@@ -236,13 +236,15 @@ const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
);
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
const PortScannerLayerLive = PortDiscoveryLive.pipe(Layer.provide(ProcessRunner.layer));
const PreviewLayerLive = Layer.mergeAll(
PreviewManagerLive,
PreviewPortScannerLive.pipe(Layer.provide(ProcessRunner.layer)),
const TerminalLayerLive = TerminalManagerLive.pipe(
Layer.provide(PtyAdapterLive),
Layer.provide(PortScannerLayerLive),
);
const PreviewLayerLive = Layer.mergeAll(PreviewManagerLive, PortScannerLayerLive);
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistryLayerLive),
@@ -204,6 +204,7 @@ interface CreateManagerOptions {
subprocessInspector?: (terminalPid: number) => Effect.Effect<{
readonly hasRunningSubprocess: boolean;
readonly childCommand: string | null;
readonly processIds: ReadonlyArray<number>;
}>;
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
@@ -745,7 +746,8 @@ it.layer(
let inspect: {
readonly hasRunningSubprocess: boolean;
readonly childCommand: string | null;
} = { hasRunningSubprocess: false, childCommand: null };
readonly processIds: ReadonlyArray<number>;
} = { hasRunningSubprocess: false, childCommand: null, processIds: [] };
const { manager, getEvents } = yield* createManager(5, {
subprocessInspector: () => Effect.succeed(inspect),
subprocessPollIntervalMs: 20,
@@ -754,7 +756,7 @@ it.layer(
yield* manager.open(openInput());
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
inspect = { hasRunningSubprocess: true, childCommand: "vim" };
inspect = { hasRunningSubprocess: true, childCommand: "vim", processIds: [100, 101] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
@@ -767,7 +769,7 @@ it.layer(
"1200 millis",
);
inspect = { hasRunningSubprocess: false, childCommand: null };
inspect = { hasRunningSubprocess: false, childCommand: null, processIds: [] };
yield* waitFor(
Effect.map(getEvents, (events) =>
events.some(
@@ -788,7 +790,11 @@ it.layer(
const { manager } = yield* createManager(5, {
subprocessInspector: () => {
checks += 1;
return Effect.succeed({ hasRunningSubprocess: false, childCommand: null });
return Effect.succeed({
hasRunningSubprocess: false,
childCommand: null,
processIds: [],
});
},
subprocessPollIntervalMs: 20,
});
+97 -15
View File
@@ -33,6 +33,7 @@ import {
terminalSessionsTotal,
} from "../../observability/Metrics.ts";
import * as ProcessRunner from "../../processRunner.ts";
import { PortDiscovery } from "../../preview/Services/PortScanner.ts";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -82,6 +83,7 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
interface TerminalSubprocessInspectResult {
readonly hasRunningSubprocess: boolean;
readonly childCommand: string | null;
readonly processIds: ReadonlyArray<number>;
}
interface TerminalSubprocessInspector {
@@ -505,12 +507,8 @@ function windowsInspectSubprocess(
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const command = [
`$c = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue | Select-Object -First 1`,
"if ($null -eq $c) { exit 1 }",
"Write-Output $c.Name",
"exit 0",
].join("; ");
const command =
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
@@ -524,16 +522,41 @@ function windowsInspectSubprocess(
}).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null } as const;
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const name = result.stdout.trim().split(/\r?\n/)[0]?.trim() ?? "";
if (name.length === 0) {
return { hasRunningSubprocess: true, childCommand: null } as const;
const processNameById = new Map<number, string>();
const childrenByParent = new Map<number, number[]>();
for (const line of result.stdout.split(/\r?\n/g)) {
const [pidRaw, parentPidRaw, nameRaw] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const parentPid = Number(parentPidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
processNameById.set(pid, nameRaw?.trim() ?? "");
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
const normalized = normalizeChildCommandName(name, platform);
const directChildren = childrenByParent.get(terminalPid) ?? [];
const childPid = directChildren[0];
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;
}
const processIds = new Set<number>([terminalPid]);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
}
const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? "", platform);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
} as const;
}),
Effect.mapError(
@@ -606,14 +629,14 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
if (pgrepResult.value.code === 0) {
childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout);
} else if (pgrepResult.value.code === 1) {
return { hasRunningSubprocess: false, childCommand: null };
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
}
if (childPid === null) {
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
return { hasRunningSubprocess: false, childCommand: null };
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
@@ -628,7 +651,7 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
}
if (childPid === null) {
return { hasRunningSubprocess: false, childCommand: null };
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
const runComm = processRunner.run({
@@ -663,16 +686,43 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
}
const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null;
const processIds = new Set<number>([terminalPid]);
const psResult = yield* Effect.exit(runPs);
if (psResult._tag === "Success" && psResult.value.code === 0) {
const childrenByParent = new Map<number, number[]>();
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
const children = childrenByParent.get(ppid) ?? [];
children.push(pid);
childrenByParent.set(ppid, children);
}
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const child of childrenByParent.get(parentPid) ?? []) {
if (processIds.has(child)) continue;
processIds.add(child);
pending.push(child);
}
}
} else {
processIds.add(childPid);
}
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
};
});
function defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) {
return Effect.fn("terminal.defaultSubprocessInspector")(function* (terminalPid: number) {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return { hasRunningSubprocess: false, childCommand: null };
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
if (platform === "win32") {
return yield* windowsInspectSubprocess(terminalPid, platform);
@@ -932,14 +982,26 @@ interface TerminalManagerOptions {
subprocessPollIntervalMs?: number;
processKillGraceMs?: number;
maxRetainedInactiveSessions?: number;
registerTerminalProcesses?: (input: {
readonly threadId: string;
readonly terminalId: string;
readonly processIds: ReadonlyArray<number>;
}) => Effect.Effect<void>;
unregisterTerminal?: (input: {
readonly threadId: string;
readonly terminalId: string;
}) => Effect.Effect<void>;
}
const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () {
const { terminalLogsDir } = yield* ServerConfig;
const ptyAdapter = yield* PtyAdapter;
const portDiscovery = yield* PortDiscovery;
return yield* makeTerminalManagerWithOptions({
logsDir: terminalLogsDir,
ptyAdapter,
registerTerminalProcesses: portDiscovery.registerTerminalProcesses,
unregisterTerminal: portDiscovery.unregisterTerminal,
});
});
@@ -967,6 +1029,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
const maxRetainedInactiveSessions =
options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void);
const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void);
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
@@ -1495,6 +1559,10 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
yield* clearKillFiber(action.process);
yield* unregisterTerminal({
threadId: action.threadId,
terminalId: action.terminalId,
});
yield* publishEvent({
type: "exited",
threadId: action.threadId,
@@ -1531,6 +1599,10 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
});
yield* clearKillFiber(process);
yield* unregisterTerminal({
threadId: session.threadId,
terminalId: session.terminalId,
});
yield* startKillEscalation(process, session.threadId, session.terminalId);
yield* evictInactiveSessionsIfNeeded();
});
@@ -1700,6 +1772,10 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
advanceEventSequence(session);
return [undefined, state] as const;
});
yield* unregisterTerminal({
threadId: session.threadId,
terminalId: session.terminalId,
});
yield* evictInactiveSessionsIfNeeded();
@@ -1731,6 +1807,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
if (Option.isSome(session)) {
yield* stopProcess(session.value);
yield* unregisterTerminal({ threadId, terminalId });
yield* persistHistory(threadId, terminalId, session.value.history);
}
@@ -1791,6 +1868,11 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
const next = inspectResult.value;
yield* registerTerminalProcesses({
threadId: session.threadId,
terminalId: session.terminalId,
processIds: next.processIds,
});
const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
+5 -5
View File
@@ -72,7 +72,7 @@ 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 { PortDiscovery } from "./preview/Services/PortScanner.ts";
import { previewAutomationBroker } from "./mcp/Layers/PreviewAutomationBroker.ts";
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
@@ -257,7 +257,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const terminalManager = yield* TerminalManager;
const previewManager = yield* PreviewManager;
const previewPortScanner = yield* PreviewPortScanner;
const portDiscovery = yield* PortDiscovery;
const providerRegistry = yield* ProviderRegistry;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const config = yield* ServerConfig;
@@ -1426,14 +1426,14 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) =>
Stream.callback<DiscoveredLocalServerList>((queue) =>
Effect.acquireRelease(
Effect.gen(function* () {
const release = yield* previewPortScanner.retain();
const initial = yield* previewPortScanner.scan();
const release = yield* portDiscovery.retain();
const initial = yield* portDiscovery.scan();
const initialScannedAt = DateTime.formatIso(yield* DateTime.now);
yield* Queue.offer(queue, {
servers: initial,
scannedAt: initialScannedAt,
});
const unsubscribe = yield* previewPortScanner.subscribe((servers) =>
const unsubscribe = yield* portDiscovery.subscribe((servers) =>
Effect.gen(function* () {
const scannedAt = DateTime.formatIso(yield* DateTime.now);
yield* Queue.offer(queue, { servers, scannedAt });
+46 -1
View File
@@ -1,14 +1,18 @@
"use client";
import { parseScopedThreadKey } from "@t3tools/client-runtime";
import { useMemo } from "react";
import { useEffect, useMemo } from "react";
import { isElectron } from "~/env";
import { useTheme } from "~/hooks/useTheme";
import { usePreviewStateStore } from "~/previewStateStore";
import { readPreviewAnnotationTheme } from "./annotationTheme";
import { useBrowserPointerStore } from "./browserPointerStore";
import { HostedBrowserWebview } from "./HostedBrowserWebview";
export function ElectronBrowserHost() {
const { resolvedTheme } = useTheme();
const previewByThreadKey = usePreviewStateStore((state) => state.byThreadKey);
const sessions = useMemo(
() =>
@@ -25,6 +29,47 @@ export function ElectronBrowserHost() {
[previewByThreadKey],
);
useEffect(() => {
const preview = window.desktopBridge?.preview;
if (!preview) return;
let lastSerializedTheme = "";
const syncTheme = () => {
const theme = readPreviewAnnotationTheme();
const serializedTheme = JSON.stringify(theme);
if (serializedTheme === lastSerializedTheme) return;
lastSerializedTheme = serializedTheme;
void preview.setAnnotationTheme(theme).catch(() => {
lastSerializedTheme = "";
});
};
const frameId = window.requestAnimationFrame(syncTheme);
const observer = new MutationObserver(syncTheme);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["class", "style"],
});
const headObserver = new MutationObserver(syncTheme);
headObserver.observe(document.head, {
childList: true,
subtree: true,
characterData: true,
});
return () => {
window.cancelAnimationFrame(frameId);
observer.disconnect();
headObserver.disconnect();
};
}, [resolvedTheme]);
useEffect(() => {
const preview = window.desktopBridge?.preview;
if (!preview) return;
return preview.onPointerEvent((event) => {
useBrowserPointerStore.getState().apply(event);
});
}, []);
if (!isElectron) return null;
return (
<div className="contents" data-electron-browser-host>
+28
View File
@@ -0,0 +1,28 @@
import type { DesktopPreviewAnnotationTheme } from "@t3tools/contracts";
const readVariable = (styles: CSSStyleDeclaration, name: string, fallback: string): string =>
styles.getPropertyValue(name).trim() || fallback;
export function readPreviewAnnotationTheme(): DesktopPreviewAnnotationTheme {
const root = document.documentElement;
const styles = getComputedStyle(root);
return {
colorScheme: root.classList.contains("dark") ? "dark" : "light",
radius: readVariable(styles, "--radius", "0.625rem"),
background: readVariable(styles, "--background", "white"),
foreground: readVariable(styles, "--foreground", "oklch(0.269 0 0)"),
popover: readVariable(styles, "--popover", "white"),
popoverForeground: readVariable(styles, "--popover-foreground", "oklch(0.269 0 0)"),
primary: readVariable(styles, "--primary", "oklch(0.488 0.217 264)"),
primaryForeground: readVariable(styles, "--primary-foreground", "white"),
muted: readVariable(styles, "--muted", "rgb(0 0 0 / 4%)"),
mutedForeground: readVariable(styles, "--muted-foreground", "oklch(0.556 0 0)"),
accent: readVariable(styles, "--accent", "rgb(0 0 0 / 4%)"),
accentForeground: readVariable(styles, "--accent-foreground", "oklch(0.269 0 0)"),
border: readVariable(styles, "--border", "rgb(0 0 0 / 8%)"),
input: readVariable(styles, "--input", "rgb(0 0 0 / 10%)"),
ring: readVariable(styles, "--ring", "oklch(0.488 0.217 264)"),
fontSans: readVariable(styles, "--font-sans", styles.fontFamily || "system-ui, sans-serif"),
fontMono: readVariable(styles, "--font-mono", "ui-monospace, monospace"),
};
}
@@ -0,0 +1,68 @@
import { beforeEach, describe, expect, it } from "vite-plus/test";
import { useBrowserPointerStore } from "./browserPointerStore";
beforeEach(() => {
useBrowserPointerStore.setState({ byTabId: {} });
});
describe("browserPointerStore", () => {
it("tracks the latest pointer target independently for each tab", () => {
const store = useBrowserPointerStore.getState();
store.apply({
tabId: "tab_a",
phase: "move",
x: 20,
y: 30,
sequence: 0,
createdAt: "2026-06-12T00:00:00.000Z",
});
store.apply({
tabId: "tab_b",
phase: "move",
x: 40,
y: 50,
sequence: 1,
createdAt: "2026-06-12T00:00:01.000Z",
});
store.apply({
tabId: "tab_a",
phase: "click",
x: 60,
y: 70,
sequence: 2,
createdAt: "2026-06-12T00:00:02.000Z",
});
expect(useBrowserPointerStore.getState().byTabId).toMatchObject({
tab_a: { phase: "click", x: 60, y: 70, sequence: 2 },
tab_b: { phase: "move", x: 40, y: 50, sequence: 1 },
});
});
it("clears one tab without affecting the others", () => {
const store = useBrowserPointerStore.getState();
store.apply({
tabId: "tab_a",
phase: "move",
x: 20,
y: 30,
sequence: 0,
createdAt: "2026-06-12T00:00:00.000Z",
});
store.apply({
tabId: "tab_b",
phase: "move",
x: 40,
y: 50,
sequence: 1,
createdAt: "2026-06-12T00:00:01.000Z",
});
store.clear("tab_a");
expect(useBrowserPointerStore.getState().byTabId).toEqual({
tab_b: expect.objectContaining({ x: 40, y: 50 }),
});
});
});
@@ -0,0 +1,25 @@
import type { DesktopPreviewPointerEvent } from "@t3tools/contracts";
import { create } from "zustand";
interface BrowserPointerStoreState {
readonly byTabId: Record<string, DesktopPreviewPointerEvent>;
readonly apply: (event: DesktopPreviewPointerEvent) => void;
readonly clear: (tabId: string) => void;
}
export const useBrowserPointerStore = create<BrowserPointerStoreState>()((set) => ({
byTabId: {},
apply: (event) =>
set((state) => ({
byTabId: {
...state.byTabId,
[event.tabId]: event,
},
})),
clear: (tabId) =>
set((state) => {
if (!(tabId in state.byTabId)) return state;
const { [tabId]: _removed, ...byTabId } = state.byTabId;
return { byTabId };
}),
}));
+138 -5
View File
@@ -65,6 +65,7 @@ import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { terminalSessionManager } from "../terminalSessionState";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
@@ -1801,6 +1802,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
useTerminalUiStateStore.setState({
terminalUiStateByThreadKey: {},
});
useRightPanelStore.persist.clearStorage();
useRightPanelStore.setState({ byThreadKey: {} });
});
afterEach(() => {
@@ -2054,12 +2057,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const toggle = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>('button[aria-label="Toggle terminal drawer"]'),
"Unable to find terminal drawer toggle.",
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "j",
metaKey: isMacPlatform(navigator.platform),
ctrlKey: !isMacPlatform(navigator.platform),
bubbles: true,
cancelable: true,
}),
);
toggle.click();
await vi.waitFor(
() => {
@@ -2072,6 +2078,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
terminalId: DEFAULT_TERMINAL_ID,
cwd: "/repo/project",
});
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF)
.isOpen,
).toBe(false);
},
{ timeout: 8_000, interval: 16 },
);
@@ -2080,6 +2090,129 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps multiple terminal panel surfaces separate from the bottom drawer", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-open-inline-terminal-panel" as MessageId,
targetText: "open inline terminal panel",
}),
});
try {
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "b",
altKey: true,
metaKey: isMacPlatform(navigator.platform),
ctrlKey: !isMacPlatform(navigator.platform),
bubbles: true,
cancelable: true,
}),
);
const addSurface = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Add panel surface"]'),
"Unable to find add panel surface button.",
);
expect(document.body.textContent).toContain("Open a surface");
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF),
).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
expect(wsRequests.some((request) => request._tag === WS_METHODS.terminalOpen)).toBe(false);
addSurface.click();
const terminalItem = await waitForElement(
() =>
Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(
(item) => item.textContent?.trim() === "Terminal",
) ?? null,
"Unable to find Terminal panel menu item.",
);
terminalItem.click();
await vi.waitFor(() => {
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF)
.surfaces.filter((surface) => surface.kind === "terminal")
.map((surface) => surface.resourceId),
).toEqual(["term-1"]);
});
addSurface.click();
const secondTerminalItem = await waitForElement(
() =>
Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(
(item) => item.textContent?.trim() === "Terminal",
) ?? null,
"Unable to find Terminal panel menu item.",
);
secondTerminalItem.click();
await vi.waitFor(
() => {
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, THREAD_REF)
.surfaces.filter((surface) => surface.kind === "terminal")
.map((surface) => surface.resourceId),
).toEqual(["term-1", "term-2"]);
expect(
document.querySelector('[data-preview-panel-mode="inline"] .thread-terminal-drawer'),
).not.toBeNull();
expect(
wsRequests
.filter((request) => request._tag === WS_METHODS.terminalOpen)
.map((request) => ("terminalId" in request ? request.terminalId : null)),
).toEqual(expect.arrayContaining(["term-1", "term-2"]));
const attachRequest = wsRequests.find(
(request) =>
request._tag === WS_METHODS.terminalAttach &&
"terminalId" in request &&
request.terminalId === "term-2",
);
expect(attachRequest).toMatchObject({
_tag: WS_METHODS.terminalAttach,
threadId: THREAD_ID,
terminalId: "term-2",
cwd: "/repo/project",
});
},
{ timeout: 8_000, interval: 16 },
);
const drawerToggle = await waitForElement(
() =>
document.querySelector<HTMLButtonElement>('button[aria-label="Toggle terminal drawer"]'),
"Unable to find terminal drawer toggle.",
);
drawerToggle.click();
await vi.waitFor(() => {
expect(
useTerminalUiStateStore.getState().terminalUiStateByThreadKey[THREAD_KEY],
).toMatchObject({
terminalOpen: true,
terminalIds: ["term-3"],
});
expect(
wsRequests.some(
(request) =>
request._tag === WS_METHODS.terminalAttach &&
"terminalId" in request &&
request.terminalId === "term-3",
),
).toBe(true);
});
} finally {
await mounted.cleanup();
}
});
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
setDraftThreadWithoutWorktree();
File diff suppressed because it is too large. Load diff
+105 -6
View File
@@ -1,7 +1,9 @@
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import { ClipboardList, FileDiff, Globe2, Plus, TerminalSquare, X } from "lucide-react";
import { type ReactNode, useState } from "react";
import { isElectron } from "~/env";
import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
@@ -12,25 +14,97 @@ import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanel
interface RightPanelTabsProps {
mode: PreviewPanelMode;
surfaces: readonly RightPanelSurface[];
activeSurfaceId: string;
activeSurfaceId: string | null;
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
terminalLabelsById: ReadonlyMap<string, string>;
onActivate: (surface: RightPanelSurface) => void;
onCloseSurface: (surface: RightPanelSurface) => void;
onAddBrowser: () => void;
onAddTerminal: () => void;
onAddDiff: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
children: ReactNode;
}
function RightPanelEmptyState(props: {
onAddBrowser: () => void;
onAddTerminal: () => void;
onAddDiff: () => void;
browserAvailable: boolean;
diffAvailable: boolean;
}) {
const actions = [
{
label: "Browser",
description: "Open a local app or URL.",
icon: Globe2,
available: props.browserAvailable,
onClick: props.onAddBrowser,
},
{
label: "Terminal",
description: "Start a shell in this workspace.",
icon: TerminalSquare,
available: true,
onClick: props.onAddTerminal,
},
{
label: "Diff",
description: "Review changes in this thread.",
icon: FileDiff,
available: props.diffAvailable,
onClick: props.onAddDiff,
},
] as const;
return (
<div className="flex min-h-0 flex-1 items-center justify-center p-6">
<div className="w-full max-w-xl">
<div className="mb-5 text-center">
<h3 className="text-sm font-medium text-foreground">Open a surface</h3>
<p className="mt-1 text-xs text-muted-foreground">
Choose what to show in the right panel.
</p>
</div>
<div className="grid gap-2 sm:grid-cols-3">
{actions.map((action) => {
const Icon = action.icon;
return (
<button
key={action.label}
type="button"
disabled={!action.available}
onClick={action.onClick}
className="flex min-h-28 flex-col items-start rounded-lg border border-border/80 bg-card/40 p-4 text-left transition hover:border-border hover:bg-accent/60 disabled:cursor-not-allowed disabled:opacity-40"
>
<Icon className="mb-3 size-5" />
<span className="text-sm font-medium">{action.label}</span>
<span className="mt-1 text-xs leading-relaxed text-muted-foreground">
{action.description}
</span>
</button>
);
})}
</div>
</div>
</div>
);
}
function surfaceTitle(
surface: RightPanelSurface,
sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
terminalLabelsById: ReadonlyMap<string, string>,
): string {
switch (surface.kind) {
case "diff":
return "Diff";
case "terminal":
return "Terminal";
return (
terminalLabelsById.get(surface.activeTerminalId) ??
getTerminalLabel(surface.activeTerminalId)
);
case "plan":
return "Plan";
case "preview": {
@@ -85,13 +159,22 @@ function SurfaceIcon({
}
export function RightPanelTabs(props: RightPanelTabsProps) {
const ownsDesktopTitleBar = isElectron && props.mode === "inline";
return (
<PreviewPanelShell mode={props.mode}>
<div className="flex h-10 shrink-0 items-center px-2">
<div
className={cn(
"flex shrink-0 items-center px-2",
ownsDesktopTitleBar
? "drag-region h-[52px] wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]"
: "h-10",
)}
>
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
{props.surfaces.map((surface) => {
const active = surface.id === props.activeSurfaceId;
const title = surfaceTitle(surface, props.previewSessions);
const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
return (
<div
key={surface.id}
@@ -131,10 +214,14 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<Plus className="size-4" />
</MenuTrigger>
<MenuPopup align="start" side="bottom" sideOffset={6} className="min-w-44">
<MenuItem onClick={props.onAddBrowser}>
<MenuItem onClick={props.onAddBrowser} disabled={!props.browserAvailable}>
<Globe2 />
Browser
</MenuItem>
<MenuItem onClick={props.onAddTerminal}>
<TerminalSquare />
Terminal
</MenuItem>
<MenuItem onClick={props.onAddDiff} disabled={!props.diffAvailable}>
<FileDiff />
Diff
@@ -142,7 +229,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
</MenuPopup>
</Menu>
</div>
<div className="flex min-h-0 flex-1 flex-col">{props.children}</div>
<div className="flex min-h-0 flex-1 flex-col">
{props.activeSurfaceId === null ? (
<RightPanelEmptyState
onAddBrowser={props.onAddBrowser}
onAddTerminal={props.onAddTerminal}
onAddDiff={props.onAddDiff}
browserAvailable={props.browserAvailable}
diffAvailable={props.diffAvailable}
/>
) : (
props.children
)}
</div>
</PreviewPanelShell>
);
}
+38
View File
@@ -4,6 +4,7 @@ import {
ChevronRightIcon,
CloudIcon,
FolderPlusIcon,
Globe2Icon,
SearchIcon,
SettingsIcon,
SquarePenIcon,
@@ -75,6 +76,7 @@ import {
} from "../store";
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
import { useThreadRunningTerminalIds } from "../terminalSessionState";
import { useThreadDiscoveredPorts } from "../portDiscoveryState";
import { useUiStateStore } from "../uiStateStore";
import {
resolveShortcutCommand,
@@ -198,6 +200,7 @@ import {
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { SidebarProviderUpdatePill } from "./sidebar/SidebarProviderUpdatePill";
import { openDiscoveredPort } from "./preview/openDiscoveredPort";
const SIDEBAR_SORT_LABELS: Record<SidebarProjectSortOrder, string> = {
updated_at: "Last user message",
created_at: "Created at",
@@ -349,6 +352,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
environmentId: thread.environmentId,
threadId: thread.id,
});
const discoveredPorts = useThreadDiscoveredPorts({
environmentId: thread.environmentId,
threadId: thread.id,
});
const primaryEnvironmentId = usePrimaryEnvironmentId();
const isRemoteThread =
primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
@@ -419,6 +426,17 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
},
[handleThreadClick, orderedProjectThreadKeys, threadRef],
);
const handleOpenDiscoveredPort = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
const port = discoveredPorts[0];
if (!port) return;
event.preventDefault();
event.stopPropagation();
navigateToThread(threadRef);
void openDiscoveredPort({ threadRef, port });
},
[discoveredPorts, navigateToThread, threadRef],
);
const handleRowKeyDown = useCallback(
(event: React.KeyboardEvent) => {
if (event.key !== "Enter" && event.key !== " ") return;
@@ -609,6 +627,26 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
)}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{discoveredPorts.length > 0 && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={`Open localhost:${discoveredPorts[0]?.port ?? ""}`}
className="inline-flex cursor-pointer items-center justify-center text-emerald-600 outline-hidden focus-visible:ring-1 focus-visible:ring-ring dark:text-emerald-400"
onClick={handleOpenDiscoveredPort}
/>
}
>
<Globe2Icon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
Open localhost:{discoveredPorts[0]?.port}
{discoveredPorts.length > 1 ? ` (+${discoveredPorts.length - 1})` : ""}
</TooltipPopup>
</Tooltip>
)}
{terminalStatus && (
<Tooltip>
<TooltipTrigger
@@ -1,5 +1,13 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
import {
Globe2,
Plus,
SquareSplitHorizontal,
SquareSplitVertical,
TerminalSquare,
Trash2,
XIcon,
} from "lucide-react";
import {
type ResolvedKeybindingsConfig,
type ScopedThreadRef,
@@ -37,6 +45,7 @@ import {
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
isTerminalToggleShortcut,
terminalDeleteShortcutData,
terminalNavigationShortcutData,
@@ -50,6 +59,8 @@ import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { attachTerminalSession } from "../terminalSessionState";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useDiscoveredPorts } from "../portDiscoveryState";
import { openDiscoveredPort } from "./preview/openDiscoveredPort";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -437,6 +448,7 @@ export function TerminalViewport({
if (
isTerminalToggleShortcut(event, currentKeybindings, options) ||
isTerminalSplitShortcut(event, currentKeybindings, options) ||
isTerminalSplitVerticalShortcut(event, currentKeybindings, options) ||
isTerminalNewShortcut(event, currentKeybindings, options) ||
isTerminalCloseShortcut(event, currentKeybindings, options) ||
isDiffToggleShortcut(event, currentKeybindings, options)
@@ -723,12 +735,44 @@ export function TerminalViewport({
.catch(() => undefined);
}, 30);
attachTerminal();
let resizeFrame = 0;
const resizeObserver =
typeof ResizeObserver === "undefined"
? null
: new ResizeObserver(() => {
if (resizeFrame !== 0) return;
resizeFrame = window.requestAnimationFrame(() => {
resizeFrame = 0;
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
fitTerminalSafely(activeFitAddon);
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
});
});
resizeObserver?.observe(mount);
return () => {
disposed = true;
unsubscribeAttach?.();
unsubscribeAttach = null;
window.clearTimeout(fitTimer);
if (resizeFrame !== 0) {
window.cancelAnimationFrame(resizeFrame);
}
resizeObserver?.disconnect();
inputDisposable.dispose();
selectionDisposable.dispose();
terminalLinksDisposable.dispose();
@@ -806,8 +850,10 @@ interface ThreadTerminalDrawerProps {
activeTerminalGroupId: string;
focusRequestId: number;
onSplitTerminal: () => void;
onSplitTerminalVertical: () => void;
onNewTerminal: () => void;
splitShortcutLabel?: string | undefined;
splitVerticalShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void;
@@ -865,8 +911,10 @@ export default function ThreadTerminalDrawer({
activeTerminalGroupId,
focusRequestId,
onSplitTerminal,
onSplitTerminalVertical,
onNewTerminal,
splitShortcutLabel,
splitVerticalShortcutLabel,
newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange,
@@ -957,6 +1005,9 @@ export default function ThreadTerminalDrawer({
nextGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
...(terminalGroup.splitDirection === "vertical"
? { splitDirection: "vertical" as const }
: {}),
});
}
@@ -994,6 +1045,8 @@ export default function ThreadTerminalDrawer({
const visibleTerminalIds =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ??
(normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []);
const splitDirection =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.splitDirection ?? "horizontal";
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
@@ -1007,6 +1060,17 @@ export default function ThreadTerminalDrawer({
}
return next;
}, [normalizedTerminalIds, terminalLabelsById]);
const discoveredPorts = useDiscoveredPorts(threadRef.environmentId);
const discoveredPortByTerminalId = useMemo(() => {
const next = new Map<string, (typeof discoveredPorts)[number]>();
for (const port of discoveredPorts) {
if (port.terminal?.threadId !== threadId) continue;
if (!next.has(port.terminal.terminalId)) {
next.set(port.terminal.terminalId, port);
}
}
return next;
}, [discoveredPorts, threadId]);
const resolveTerminalLaunchLocation = useCallback(
(terminalId: string): TerminalLaunchLocation => {
return (
@@ -1020,10 +1084,15 @@ export default function ThreadTerminalDrawer({
[cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
);
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
? `Split Terminal Horizontally (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
? `Split Terminal (${splitShortcutLabel})`
: "Split Terminal";
? `Split Terminal Horizontally (${splitShortcutLabel})`
: "Split Terminal Horizontally";
const splitTerminalVerticalActionLabel = hasReachedSplitLimit
? `Split Terminal Vertically (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitVerticalShortcutLabel
? `Split Terminal Vertically (${splitVerticalShortcutLabel})`
: "Split Terminal Vertically";
const newTerminalActionLabel = newShortcutLabel
? `New Terminal (${newShortcutLabel})`
: "New Terminal";
@@ -1034,6 +1103,10 @@ export default function ThreadTerminalDrawer({
if (hasReachedSplitLimit) return;
onSplitTerminal();
}, [hasReachedSplitLimit, onSplitTerminal]);
const onSplitTerminalVerticalAction = useCallback(() => {
if (hasReachedSplitLimit) return;
onSplitTerminalVertical();
}, [hasReachedSplitLimit, onSplitTerminalVertical]);
const onNewTerminalAction = useCallback(() => {
onNewTerminal();
}, [onNewTerminal]);
@@ -1143,6 +1216,7 @@ export default function ThreadTerminalDrawer({
if (normalizedTerminalIds.length === 0) {
return (
<aside
data-terminal-owner={isPanel ? "right-panel" : "drawer"}
className={cn(
"thread-terminal-drawer relative flex min-w-0 flex-col overflow-hidden bg-background",
isPanel ? "h-full flex-1" : "shrink-0 border-t border-border/80",
@@ -1176,6 +1250,7 @@ export default function ThreadTerminalDrawer({
return (
<aside
data-terminal-owner={isPanel ? "right-panel" : "drawer"}
className={cn(
"thread-terminal-drawer relative flex min-w-0 flex-col overflow-hidden bg-background",
isPanel ? "h-full flex-1" : "shrink-0 border-t border-border/80",
@@ -1207,6 +1282,18 @@ export default function ThreadTerminalDrawer({
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className={`p-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent"
}`}
onClick={onSplitTerminalVerticalAction}
label={splitTerminalVerticalActionLabel}
>
<SquareSplitVertical className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminalAction}
@@ -1232,16 +1319,26 @@ export default function ThreadTerminalDrawer({
{isSplitView ? (
<div
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}}
style={
splitDirection === "vertical"
? {
gridTemplateRows: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
: {
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}
}
>
{visibleTerminalIds.map((terminalId) => {
const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
return (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
className={`min-h-0 min-w-0 ${
splitDirection === "vertical"
? "border-t first:border-t-0"
: "border-l first:border-l-0"
} ${
terminalId === resolvedActiveTerminalId
? "border-border"
: "border-border/70"
@@ -1320,6 +1417,17 @@ export default function ThreadTerminalDrawer({
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
hasReachedSplitLimit
? "cursor-not-allowed opacity-45 hover:bg-transparent"
: "hover:bg-accent/70"
}`}
onClick={onSplitTerminalVerticalAction}
label={splitTerminalVerticalActionLabel}
>
<SquareSplitVertical className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminalAction}
@@ -1366,6 +1474,7 @@ export default function ThreadTerminalDrawer({
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
const discoveredPort = discoveredPortByTerminalId.get(terminalId);
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
@@ -1391,6 +1500,37 @@ export default function ThreadTerminalDrawer({
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{discoveredPort && (
<Popover>
<PopoverTrigger
openOnHover
render={
<button
type="button"
className="inline-flex size-4 items-center justify-center rounded text-emerald-600 transition hover:bg-accent dark:text-emerald-400"
onClick={() =>
void openDiscoveredPort({
threadRef,
port: discoveredPort,
})
}
aria-label={`Open localhost:${discoveredPort.port}`}
/>
}
>
<Globe2 className="size-3" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
Open localhost:{discoveredPort.port}
</PopoverPopup>
</Popover>
)}
{normalizedTerminalIds.length > 1 && (
<Popover>
<PopoverTrigger
+5 -1
View File
@@ -16,6 +16,7 @@ import { Toggle } from "../ui/toggle";
import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../environments/primary";
import { shortcutLabelForCommand } from "../../keybindings";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
@@ -76,6 +77,7 @@ export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
primaryEnvironmentId,
});
const rightPanelShortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");
return (
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
@@ -138,7 +140,9 @@ export const ChatHeader = memo(function ChatHeader({
}
/>
<TooltipPopup side="bottom">
{rightPanelAvailable ? "Toggle right panel" : "Right panel is unavailable"}
{rightPanelAvailable
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}`
: "Right panel is unavailable"}
</TooltipPopup>
</Tooltip>
</div>
@@ -0,0 +1,52 @@
"use client";
import { MousePointer2 } from "lucide-react";
import { useEffect, useState } from "react";
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
import { agentBrowserCursorOpacity, type BrowserController } from "./agentBrowserCursorLogic";
const CURSOR_ACTIVE_MS = 700;
export function AgentBrowserCursor(props: {
readonly tabId: string;
readonly zoomFactor: number;
readonly controller: BrowserController;
}) {
const { tabId, zoomFactor, controller } = props;
const event = useBrowserPointerStore((state) => state.byTabId[tabId] ?? null);
const [active, setActive] = useState(false);
useEffect(() => {
if (!event) return;
setActive(true);
const timeout = window.setTimeout(() => setActive(false), CURSOR_ACTIVE_MS);
return () => window.clearTimeout(timeout);
}, [event]);
if (!event) return null;
return (
<div
className="pointer-events-none absolute left-0 top-0 z-40 transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none"
style={{
opacity: agentBrowserCursorOpacity(active, controller),
transform: `translate3d(${event.x * zoomFactor}px, ${event.y * zoomFactor}px, 0)`,
}}
aria-hidden="true"
data-agent-browser-cursor
>
{event.phase === "click" ? (
<span
key={event.sequence}
className="absolute left-0.5 top-0.5 size-4 animate-ping rounded-full bg-primary/25 motion-reduce:animate-none"
/>
) : null}
<MousePointer2
className="relative size-5 -translate-x-0.5 -translate-y-0.5 fill-background text-primary drop-shadow-sm"
strokeWidth={2}
/>
</div>
);
}
@@ -0,0 +1,41 @@
import "../../index.css";
import { page } from "vite-plus/test/browser";
import { describe, expect, it, vi } from "vite-plus/test";
import { render } from "vitest-browser-react";
import { PreviewChromeRow } from "./PreviewChromeRow";
const defaultProps = {
url: "https://example.com/",
loading: false,
loadProgress: 0,
canGoBack: false,
canGoForward: false,
refreshDisabled: false,
onBack: vi.fn(),
onForward: vi.fn(),
onRefresh: vi.fn(),
onSubmit: vi.fn(),
};
describe("PreviewChromeRow", () => {
it("only focuses the URL input after an explicit focus request", async () => {
const previouslyFocused = document.createElement("button");
document.body.append(previouslyFocused);
previouslyFocused.focus();
const screen = await render(<PreviewChromeRow {...defaultProps} focusUrlNonce={undefined} />);
const input = page.getByRole("textbox").element() as HTMLInputElement;
expect(document.activeElement).toBe(previouslyFocused);
await screen.rerender(<PreviewChromeRow {...defaultProps} focusUrlNonce={1} />);
expect(document.activeElement).toBe(input);
expect(input.selectionStart).toBe(0);
expect(input.selectionEnd).toBe(input.value.length);
previouslyFocused.remove();
});
});
+215 -17
View File
@@ -22,16 +22,19 @@ import { PreviewChromeRow } from "./PreviewChromeRow";
import { PreviewEmptyState } from "./PreviewEmptyState";
import { PreviewMoreMenu } from "./PreviewMoreMenu";
import { PreviewUnreachable } from "./PreviewUnreachable";
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
import { useLoadingProgress } from "./useLoadingProgress";
import { usePreviewSession } from "./usePreviewSession";
import { ZoomIndicator } from "./ZoomIndicator";
import { AgentBrowserCursor } from "./AgentBrowserCursor";
import {
startBrowserRecording,
stopBrowserRecording,
useBrowserRecordingStore,
} from "~/browser/browserRecording";
import { toastManager } from "~/components/ui/toast";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
interface Props {
threadRef: ScopedThreadRef;
@@ -47,7 +50,7 @@ const localApi = typeof window === "undefined" ? null : ensureLocalApi();
* state when no session exists for the thread.
*/
export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls, visible }: Props) {
const [focusUrlNonce, setFocusUrlNonce] = useState(0);
const [focusUrlNonce, setFocusUrlNonce] = useState<number | undefined>(undefined);
const [pickActive, setPickActive] = useState(false);
const activeRecordingTabId = useBrowserRecordingStore((state) => state.activeTabId);
const pickActiveRef = useRef(false);
@@ -81,6 +84,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const canGoForward = desktopOverlay?.canGoForward ?? snapshot?.canGoForward ?? false;
const refreshDisabled = navStatus._tag === "Idle";
const isUnreachable = navStatus._tag === "LoadFailed";
const showEmptyState = shouldShowPreviewEmptyState(snapshot);
const controller = desktopOverlay?.controller ?? "none";
const loadProgress = useLoadingProgress(loading);
@@ -142,16 +146,89 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const handleCapture = useCallback(
(record: boolean) => {
if (!previewBridge || !tabId) return;
const bridge = previewBridge;
const recordingThisTab = activeRecordingTabId === tabId;
if (recordingThisTab) {
void stopBrowserRecording(tabId).then(
(artifact) => {
if (!artifact) return;
toastManager.add({
type: "success",
title: "Recording saved",
description: artifact.path,
});
let pathCopied = false;
let toastId: ReturnType<typeof toastManager.add>;
const copyPath = () => {
if (!navigator.clipboard?.writeText) {
toastManager.update(
toastId,
stackedThreadToast({
type: "error",
title: "Unable to copy recording path",
description: "Clipboard API unavailable.",
actionProps: revealAction,
}),
);
return;
}
void navigator.clipboard.writeText(artifact.path).then(
() => {
pathCopied = true;
updateRecordingToast();
window.setTimeout(() => {
pathCopied = false;
updateRecordingToast();
}, 2_000);
},
(error) => {
toastManager.update(
toastId,
stackedThreadToast({
type: "error",
title: "Unable to copy recording path",
description: error instanceof Error ? error.message : "An error occurred.",
actionProps: revealAction,
}),
);
},
);
};
const revealAction = {
children: revealInFileExplorerLabel(navigator.platform),
onClick: () => void bridge.revealArtifact(artifact.path),
};
const updateRecordingToast = () => {
toastManager.update(
toastId,
stackedThreadToast({
type: "success",
title: "Recording saved",
actionProps: revealAction,
data: {
secondaryActionProps: {
children: pathCopied ? "Copied!" : "Copy path",
disabled: pathCopied,
onClick: copyPath,
},
secondaryActionVariant: "outline",
},
}),
);
};
toastId = toastManager.add(
stackedThreadToast({
type: "success",
title: "Recording saved",
actionProps: revealAction,
data: {
secondaryActionProps: {
children: "Copy path",
onClick: copyPath,
},
secondaryActionVariant: "outline",
},
}),
);
},
(error) => {
toastManager.add({
@@ -181,13 +258,126 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
});
return;
}
void previewBridge.captureScreenshot(tabId).then(
void bridge.captureScreenshot(tabId).then(
(artifact) => {
toastManager.add({
type: "success",
title: "Screenshot saved",
description: artifact.path,
});
const revealAction = {
children: revealInFileExplorerLabel(navigator.platform),
onClick: () => void bridge.revealArtifact(artifact.path),
};
let pathCopied = false;
let imageCopied = false;
let toastId: ReturnType<typeof toastManager.add>;
const updateScreenshotToast = (
type: "success" | "error" = "success",
title = "Screenshot saved",
description?: string,
) => {
toastManager.update(
toastId,
stackedThreadToast({
type,
title,
description,
actionProps: {
children: imageCopied ? "Copied!" : "Copy image",
disabled: imageCopied,
onClick: copyImage,
},
data: {
additionalActions: [
{
id: "copy-path",
props: {
children: pathCopied ? "Copied!" : "Copy path",
disabled: pathCopied,
onClick: copyPath,
},
},
],
secondaryActionProps: {
...revealAction,
},
secondaryActionVariant: "outline",
},
}),
);
};
const copyPath = () => {
if (!navigator.clipboard?.writeText) {
updateScreenshotToast(
"error",
"Unable to copy screenshot path",
"Clipboard API unavailable.",
);
return;
}
void navigator.clipboard.writeText(artifact.path).then(
() => {
pathCopied = true;
updateScreenshotToast();
window.setTimeout(() => {
pathCopied = false;
updateScreenshotToast();
}, 2_000);
},
(error) => {
updateScreenshotToast(
"error",
"Unable to copy screenshot path",
error instanceof Error ? error.message : "An error occurred.",
);
},
);
};
const copyImage = () => {
void bridge.copyArtifactToClipboard(artifact.path).then(
() => {
imageCopied = true;
updateScreenshotToast();
window.setTimeout(() => {
imageCopied = false;
updateScreenshotToast();
}, 2_000);
},
(error) => {
updateScreenshotToast(
"error",
"Unable to copy screenshot",
error instanceof Error ? error.message : "An error occurred.",
);
},
);
};
toastId = toastManager.add(
stackedThreadToast({
type: "success",
title: "Screenshot saved",
actionProps: {
children: "Copy image",
onClick: copyImage,
},
data: {
additionalActions: [
{
id: "copy-path",
props: {
children: "Copy path",
onClick: copyPath,
},
},
],
secondaryActionProps: {
...revealAction,
},
secondaryActionVariant: "outline",
},
}),
);
},
(error) => {
toastManager.add({
@@ -287,7 +477,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
handleRefresh();
return;
case "focus-url":
setFocusUrlNonce((value) => value + 1);
setFocusUrlNonce((value) => (value ?? 0) + 1);
return;
case "zoom-in":
handleZoomIn();
@@ -346,24 +536,32 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
/>
<div className="relative min-h-0 flex-1 overflow-hidden">
{tabId && snapshot ? (
{tabId && snapshot && !showEmptyState ? (
<BrowserSurfaceSlot
key={tabId}
tabId={tabId}
visible={visible && !isUnreachable}
className="absolute inset-0 h-full w-full"
/>
) : (
) : null}
{showEmptyState ? (
<PreviewEmptyState
environmentId={threadRef.environmentId}
configuredUrls={configuredUrls}
recentlySeenUrls={previewState.recentlySeenUrls}
onOpenUrl={(next) => void handleSubmitUrl(next)}
/>
)}
) : null}
{snapshot && desktopOverlay ? (
<ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
) : null}
{tabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
<AgentBrowserCursor
tabId={tabId}
zoomFactor={desktopOverlay.zoomFactor}
controller={controller}
/>
) : null}
{controller !== "none" ? (
<div className="pointer-events-none absolute left-3 top-3 z-40 rounded-full border border-border/70 bg-background/90 px-2.5 py-1 text-[11px] font-medium shadow-sm backdrop-blur">
{controller === "agent" ? "Agent controlling browser" : "Human control"}
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vite-plus/test";
import { agentBrowserCursorOpacity } from "./agentBrowserCursorLogic";
describe("agentBrowserCursorOpacity", () => {
it("keeps active movement fully visible", () => {
expect(agentBrowserCursorOpacity(true, "agent")).toBe(1);
expect(agentBrowserCursorOpacity(true, "human")).toBe(1);
});
it("settles to a visible idle state", () => {
expect(agentBrowserCursorOpacity(false, "none")).toBe(0.35);
expect(agentBrowserCursorOpacity(false, "agent")).toBe(0.35);
});
it("dims further while the human controls the page", () => {
expect(agentBrowserCursorOpacity(false, "human")).toBe(0.18);
});
});
@@ -0,0 +1,6 @@
export type BrowserController = "human" | "agent" | "none";
export function agentBrowserCursorOpacity(active: boolean, controller: BrowserController): number {
if (active) return 1;
return controller === "human" ? 0.18 : 0.35;
}
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
describe("revealInFileExplorerLabel", () => {
it.each([
["MacIntel", "Reveal in Finder"],
["Win32", "Reveal in File Explorer"],
["Linux x86_64", "Reveal in Files"],
])("maps %s to %s", (platform, expected) => {
expect(revealInFileExplorerLabel(platform)).toBe(expected);
});
});
@@ -0,0 +1,6 @@
export function revealInFileExplorerLabel(platform: string): string {
const normalized = platform.toLowerCase();
if (normalized.includes("mac")) return "Reveal in Finder";
if (normalized.includes("win")) return "Reveal in File Explorer";
return "Reveal in Files";
}
@@ -0,0 +1,24 @@
import type { DiscoveredLocalServer, ScopedThreadRef } from "@t3tools/contracts";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { ensureEnvironmentApi } from "~/environmentApi";
import { usePreviewStateStore } from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { openPreviewSession } from "./openPreviewSession";
export async function openDiscoveredPort(input: {
readonly threadRef: ScopedThreadRef;
readonly port: DiscoveredLocalServer;
}): Promise<void> {
const api = ensureEnvironmentApi(input.threadRef.environmentId);
const resolvedUrl = resolveDiscoveredServerUrl(input.threadRef.environmentId, input.port.url);
const previewState = usePreviewStateStore.getState();
const snapshot = await openPreviewSession({
previewApi: api.preview,
threadRef: input.threadRef,
url: resolvedUrl,
applyServerSnapshot: previewState.applyServerSnapshot,
rememberUrl: previewState.rememberUrl,
});
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
}
@@ -1,4 +1,4 @@
import type { EnvironmentApi, ScopedThreadRef } from "@t3tools/contracts";
import type { EnvironmentApi, PreviewSessionSnapshot, ScopedThreadRef } from "@t3tools/contracts";
import type { PreviewStateStoreState } from "~/previewStateStore";
@@ -10,7 +10,9 @@ interface OpenPreviewSessionInput {
rememberUrl: PreviewStateStoreState["rememberUrl"];
}
export async function openPreviewSession(input: OpenPreviewSessionInput): Promise<void> {
export async function openPreviewSession(
input: OpenPreviewSessionInput,
): Promise<PreviewSessionSnapshot> {
const snapshot = await input.previewApi.open({
threadId: input.threadRef.threadId,
url: input.url,
@@ -20,4 +22,5 @@ export async function openPreviewSession(input: OpenPreviewSessionInput): Promis
input.threadRef,
snapshot.navStatus._tag === "Idle" ? input.url : snapshot.navStatus.url,
);
return snapshot;
}
@@ -0,0 +1,42 @@
import type { PreviewSessionSnapshot, ProjectScript } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { getConfiguredPreviewUrls, shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
const snapshot = (navStatus: PreviewSessionSnapshot["navStatus"]): PreviewSessionSnapshot => ({
threadId: "thread-1",
tabId: "tab-1",
navStatus,
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-12T20:00:00.000Z",
});
describe("shouldShowPreviewEmptyState", () => {
it("shows quick-open options for a new idle browser tab", () => {
expect(shouldShowPreviewEmptyState(snapshot({ _tag: "Idle" }))).toBe(true);
});
it("shows browser content once navigation starts", () => {
expect(
shouldShowPreviewEmptyState(
snapshot({ _tag: "Loading", url: "http://localhost:5173", title: "" }),
),
).toBe(false);
});
});
describe("getConfiguredPreviewUrls", () => {
it("collects configured preview URLs from project scripts", () => {
const scripts = [
{ previewUrl: "http://localhost:5173" },
{},
{ previewUrl: "http://localhost:3000" },
] as ProjectScript[];
expect(getConfiguredPreviewUrls(scripts)).toEqual([
"http://localhost:5173",
"http://localhost:3000",
]);
});
});
@@ -0,0 +1,11 @@
import type { PreviewSessionSnapshot, ProjectScript } from "@t3tools/contracts";
export function shouldShowPreviewEmptyState(snapshot: PreviewSessionSnapshot | null): boolean {
return snapshot === null || snapshot.navStatus._tag === "Idle";
}
export function getConfiguredPreviewUrls(
scripts: ReadonlyArray<ProjectScript> | undefined,
): ReadonlyArray<string> {
return scripts?.flatMap((script) => (script.previewUrl ? [script.previewUrl] : [])) ?? [];
}
@@ -9,6 +9,7 @@ const scannerServer = (overrides: Partial<DiscoveredLocalServer>): DiscoveredLoc
url: "http://localhost:5173",
processName: "vite",
pid: 1234,
terminal: null,
...overrides,
});
@@ -1,10 +1,10 @@
import type { DiscoveredLocalServer } from "@t3tools/contracts";
import { isLoopbackHost } from "@t3tools/shared/preview";
import { useEffect, useMemo, useState } from "react";
import { useMemo } from "react";
import { ensureEnvironmentApi } from "~/environmentApi";
import type { EnvironmentId } from "@t3tools/contracts";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useDiscoveredPorts } from "~/portDiscoveryState";
export interface PreviewableServer extends DiscoveredLocalServer {
source: "scanner" | "configured" | "recent";
@@ -22,23 +22,13 @@ interface UseDiscoveredLocalServersInput {
}
/**
* Subscribe to live localhost port scans, merge in configured /
* recently-seen URLs, and return a stable sorted list. Retains the scanner
* while mounted.
* Merge the environment-level port snapshot with configured / recently-seen
* URLs and return a stable sorted list.
*/
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]);
const scannerSnapshot = useDiscoveredPorts(input.environmentId);
return useMemo(
() =>
@@ -72,6 +62,7 @@ export function mergeServers(input: {
url: parsed.url,
processName: null,
pid: null,
terminal: null,
source: "configured",
listening: false,
});
@@ -87,6 +78,7 @@ export function mergeServers(input: {
...existing,
processName: server.processName ?? existing.processName,
pid: server.pid ?? existing.pid,
terminal: server.terminal ?? existing.terminal,
listening: true,
});
continue;
@@ -105,6 +97,7 @@ export function mergeServers(input: {
url: parsed.url,
processName: null,
pid: null,
terminal: null,
source: "recent",
listening: false,
});
@@ -8,6 +8,7 @@ import type {
} from "@t3tools/contracts";
import { useEffect, useRef } from "react";
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
import { ensureEnvironmentApi } from "~/environmentApi";
import { type DesktopPreviewOverlay, usePreviewStateStore } from "~/previewStateStore";
@@ -20,19 +21,26 @@ import { previewBridge } from "./previewBridge";
export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: string }): void {
const { threadRef, tabId } = input;
const applyDesktopState = usePreviewStateStore((state) => state.applyDesktopState);
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
const bridge = previewBridge;
// 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);
const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
useEffect(() => {
if (!bridge || typeof window === "undefined") return;
const api = ensureEnvironmentApi(threadRef.environmentId);
lastReportedUrl.current = null;
lastReportedKind.current = null;
lastDesktopNavStatus.current = null;
const unsubscribe = bridge.onStateChange((changedTabId, state) => {
if (changedTabId !== tabId) return;
if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
clearBrowserPointer(tabId);
}
lastDesktopNavStatus.current = state.navStatus;
applyDesktopState(threadRef, tabId, projectDesktopState(state));
const reported = buildReportInput({
threadId: threadRef.threadId,
@@ -47,7 +55,17 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
void api.preview.reportStatus(reported.input).catch(() => undefined);
});
return unsubscribe;
}, [applyDesktopState, bridge, tabId, threadRef]);
}, [applyDesktopState, bridge, clearBrowserPointer, tabId, threadRef]);
}
function shouldClearBrowserPointer(
previous: DesktopPreviewTabState["navStatus"] | null,
current: DesktopPreviewTabState["navStatus"],
): boolean {
if (!previous) return false;
if (current.kind === "Loading" && previous.kind !== "Loading") return true;
if (current.kind === "Idle" || previous.kind === "Idle") return false;
return current.url !== previous.url;
}
function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
+21 -1
View File
@@ -45,6 +45,10 @@ export type ThreadToastData = {
onClose?: (() => void) | undefined;
dismissAfterVisibleMs?: number;
hideCopyButton?: boolean;
additionalActions?: ReadonlyArray<{
id: string;
props: ComponentPropsWithoutRef<"button">;
}>;
secondaryActionProps?: ComponentPropsWithoutRef<"button">;
secondaryActionVariant?:
| "default"
@@ -292,9 +296,13 @@ function deriveToastBodyDescriptor(toast: {
toast.type === "error" && typeof toast.description === "string" && !toast.data?.hideCopyButton
? toast.description
: null;
const hasAdditionalActions = (toast.data?.additionalActions?.length ?? 0) > 0;
const hasSecondaryAction = toast.data?.secondaryActionProps !== undefined;
const hasTrailingControls =
copyErrorText !== null || toast.actionProps !== undefined || hasSecondaryAction;
copyErrorText !== null ||
toast.actionProps !== undefined ||
hasAdditionalActions ||
hasSecondaryAction;
const inlineContentEndPad = hasTrailingControls ? "pr-6" : "pr-10";
return {
Icon,
@@ -326,6 +334,7 @@ function ToastBodyContent({
toastDescription,
toastType,
}: ToastBodyContentProps) {
const additionalActions = toastData?.additionalActions ?? [];
const secondaryActionProps = toastData?.secondaryActionProps;
const leadingIcon = toastData?.leadingIcon;
const { className: secondaryActionClassName, ...secondaryActionRest } =
@@ -371,6 +380,17 @@ function ToastBodyContent({
)}
>
{copyErrorText !== null ? <CopyErrorButton text={copyErrorText} /> : null}
{additionalActions.map(({ id, props: { className, ...props } }) => (
<button
{...props}
className={cn(
buttonVariants({ size: "xs", variant: secondaryActionVariant }),
className,
)}
key={id}
type="button"
/>
))}
{secondaryActionProps ? (
<button
{...secondaryActionRest}
@@ -90,6 +90,7 @@ import {
const decodeIssuedBearerScopes = Schema.decodeUnknownSync(Schema.Array(AuthEnvironmentScope));
import { getClientSettings } from "~/hooks/useSettings";
import { subscribeTerminalMetadata, terminalSessionManager } from "../../terminalSessionState";
import { subscribePortDiscovery, usePortDiscoveryStore } from "../../portDiscoveryState";
import { resetWsReconnectBackoff } from "~/rpc/wsConnectionState";
import { resolveRemotePairingTarget } from "@t3tools/shared/remote";
@@ -140,6 +141,7 @@ const lastAppliedProjectionVersionByEnvironment = new Map<
}
>();
const terminalMetadataSubscriptions = new Map<EnvironmentId, () => void>();
const portDiscoverySubscriptions = new Map<EnvironmentId, () => void>();
let activeService: EnvironmentServiceState | null = null;
let needsProviderInvalidation = false;
@@ -1397,6 +1399,14 @@ function registerConnection(connection: EnvironmentConnection): EnvironmentConne
client: connection.client,
}),
);
portDiscoverySubscriptions.get(connection.environmentId)?.();
portDiscoverySubscriptions.set(
connection.environmentId,
subscribePortDiscovery({
environmentId: connection.environmentId,
previewApi: connection.client.preview,
}),
);
attachThreadDetailSubscriptionsForEnvironment(connection.environmentId);
emitEnvironmentConnectionRegistryChange();
return connection;
@@ -1412,6 +1422,9 @@ async function removeConnection(environmentId: EnvironmentId): Promise<boolean>
environmentConnections.delete(environmentId);
terminalMetadataSubscriptions.get(environmentId)?.();
terminalMetadataSubscriptions.delete(environmentId);
portDiscoverySubscriptions.get(environmentId)?.();
portDiscoverySubscriptions.delete(environmentId);
usePortDiscoveryStore.getState().clearEnvironment(environmentId);
terminalSessionManager.invalidateEnvironment(environmentId);
emitEnvironmentConnectionRegistryChange();
detachThreadDetailSubscriptionsForEnvironment(environmentId);
@@ -2048,6 +2061,11 @@ export async function resetEnvironmentServiceForTests(): Promise<void> {
unsubscribe();
}
terminalMetadataSubscriptions.clear();
for (const unsubscribe of portDiscoverySubscriptions.values()) {
unsubscribe();
}
portDiscoverySubscriptions.clear();
usePortDiscoveryStore.getState().reset();
terminalSessionManager.reset();
await Promise.all(
[...environmentConnections.keys()].map((environmentId) => removeConnection(environmentId)),
+33 -2
View File
@@ -18,6 +18,7 @@ import {
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalSplitVerticalShortcut,
isTerminalToggleShortcut,
resolveShortcutCommand,
shouldShowModelPickerJumpHints,
@@ -85,6 +86,7 @@ function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
const DEFAULT_BINDINGS = compile([
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
{ shortcut: modShortcut("b", { altKey: true }), command: "rightPanel.toggle" },
{
shortcut: modShortcut("d"),
command: "terminal.split",
@@ -92,6 +94,11 @@ const DEFAULT_BINDINGS = compile([
},
{
shortcut: modShortcut("d", { shiftKey: true }),
command: "terminal.splitVertical",
whenAst: whenIdentifier("terminalFocus"),
},
{
shortcut: modShortcut("n"),
command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"),
},
@@ -174,7 +181,17 @@ describe("split/new/close terminal shortcuts", () => {
}),
);
assert.isFalse(
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
isTerminalSplitVerticalShortcut(
event({ key: "d", metaKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "MacIntel",
context: { terminalFocus: false },
},
),
);
assert.isFalse(
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
@@ -195,7 +212,17 @@ describe("split/new/close terminal shortcuts", () => {
}),
);
assert.isTrue(
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
isTerminalSplitVerticalShortcut(
event({ key: "d", metaKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "MacIntel",
context: { terminalFocus: true },
},
),
);
assert.isTrue(
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
@@ -287,6 +314,10 @@ describe("shortcutLabelForCommand", () => {
it("returns effective labels for non-terminal commands", () => {
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "rightPanel.toggle", "MacIntel"),
"⌥⌘B",
);
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "commandPalette.toggle", "MacIntel"),
"⌘K",
+8
View File
@@ -359,6 +359,14 @@ export function isTerminalSplitShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.split", options);
}
export function isTerminalSplitVerticalShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.splitVertical", options);
}
export function isTerminalNewShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
+15 -7
View File
@@ -1,10 +1,12 @@
import { afterEach, describe, expect, it } from "vite-plus/test";
import { isTerminalFocused } from "./terminalFocus";
import { getTerminalFocusOwner, isTerminalFocused } from "./terminalFocus";
class MockHTMLElement {
isConnected = false;
className = "";
terminalOwner: string | null = null;
readonly dataset: { terminalOwner?: string } = {};
readonly classList = {
contains: (value: string) => this.className.split(/\s+/).includes(value),
@@ -14,7 +16,7 @@ class MockHTMLElement {
if (!this.isConnected) {
return null;
}
if (selector === ".thread-terminal-drawer .xterm" || selector === ".thread-terminal-drawer") {
if (selector === "[data-terminal-owner]" && this.terminalOwner !== null) {
return this;
}
return null;
@@ -44,30 +46,36 @@ describe("isTerminalFocused", () => {
detached.className = "xterm-helper-textarea";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: detached } as Document;
globalThis.document = { activeElement: detached } as unknown as Document;
expect(isTerminalFocused()).toBe(false);
});
it("returns true for connected xterm helper textareas", () => {
it("returns the drawer owner for connected xterm helper textareas", () => {
const attached = new MockHTMLElement();
attached.className = "xterm-helper-textarea";
attached.isConnected = true;
attached.terminalOwner = "drawer";
attached.dataset.terminalOwner = "drawer";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: attached } as Document;
globalThis.document = { activeElement: attached } as unknown as Document;
expect(getTerminalFocusOwner()).toBe("drawer");
expect(isTerminalFocused()).toBe(true);
});
it("returns true for focus inside the terminal drawer (e.g. sidebar)", () => {
it("returns the right panel owner for focus inside its terminal UI", () => {
const sidebarButton = new MockHTMLElement();
sidebarButton.className = "terminal-sidebar-button";
sidebarButton.isConnected = true;
sidebarButton.terminalOwner = "right-panel";
sidebarButton.dataset.terminalOwner = "right-panel";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: sidebarButton } as Document;
globalThis.document = { activeElement: sidebarButton } as unknown as Document;
expect(getTerminalFocusOwner()).toBe("right-panel");
expect(isTerminalFocused()).toBe(true);
});
});
+12 -7
View File
@@ -1,9 +1,14 @@
export function isTerminalFocused(): boolean {
export type TerminalFocusOwner = "drawer" | "right-panel";
export function getTerminalFocusOwner(): TerminalFocusOwner | null {
const activeElement = document.activeElement;
if (!(activeElement instanceof HTMLElement)) return false;
if (!activeElement.isConnected) return false;
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
if (activeElement.closest(".thread-terminal-drawer .xterm") !== null) return true;
// Sidebar / toolbar / resize affordances: still "terminal UI" for split vs diff.toggle (⌘D).
return activeElement.closest(".thread-terminal-drawer") !== null;
if (!(activeElement instanceof HTMLElement)) return null;
if (!activeElement.isConnected) return null;
const owner = activeElement.closest<HTMLElement>("[data-terminal-owner]")?.dataset.terminalOwner;
if (owner === "drawer" || owner === "right-panel") return owner;
return null;
}
export function isTerminalFocused(): boolean {
return getTerminalFocusOwner() !== null;
}
+86
View File
@@ -0,0 +1,86 @@
import type {
DiscoveredLocalServer,
EnvironmentApi,
EnvironmentId,
ThreadId,
} from "@t3tools/contracts";
import { useMemo } from "react";
import { create } from "zustand";
const EMPTY_PORTS: ReadonlyArray<DiscoveredLocalServer> = Object.freeze([]);
interface PortDiscoveryState {
readonly byEnvironment: Record<string, ReadonlyArray<DiscoveredLocalServer>>;
setPorts: (environmentId: EnvironmentId, ports: ReadonlyArray<DiscoveredLocalServer>) => void;
clearEnvironment: (environmentId: EnvironmentId) => void;
reset: () => void;
}
export const usePortDiscoveryStore = create<PortDiscoveryState>((set) => ({
byEnvironment: {},
setPorts: (environmentId, ports) =>
set((state) => ({
byEnvironment: {
...state.byEnvironment,
[environmentId]: ports,
},
})),
clearEnvironment: (environmentId) =>
set((state) => {
if (!(environmentId in state.byEnvironment)) return state;
const { [environmentId]: _removed, ...byEnvironment } = state.byEnvironment;
return { byEnvironment };
}),
reset: () => set({ byEnvironment: {} }),
}));
export function subscribePortDiscovery(input: {
readonly environmentId: EnvironmentId;
readonly previewApi: Pick<EnvironmentApi["preview"], "subscribePorts">;
}): () => void {
usePortDiscoveryStore.getState().clearEnvironment(input.environmentId);
return input.previewApi.subscribePorts((snapshot) => {
usePortDiscoveryStore.getState().setPorts(input.environmentId, snapshot.servers);
});
}
export function useDiscoveredPorts(
environmentId: EnvironmentId | null,
): ReadonlyArray<DiscoveredLocalServer> {
return usePortDiscoveryStore(
(state) => (environmentId ? state.byEnvironment[environmentId] : undefined) ?? EMPTY_PORTS,
);
}
export function useThreadDiscoveredPorts(input: {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
}): ReadonlyArray<DiscoveredLocalServer> {
const ports = useDiscoveredPorts(input.environmentId);
return useMemo(
() =>
input.threadId
? ports.filter((port) => port.terminal?.threadId === input.threadId)
: EMPTY_PORTS,
[input.threadId, ports],
);
}
export function useTerminalDiscoveredPorts(input: {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
readonly terminalId: string | null;
}): ReadonlyArray<DiscoveredLocalServer> {
const ports = useDiscoveredPorts(input.environmentId);
return useMemo(
() =>
input.threadId && input.terminalId
? ports.filter(
(port) =>
port.terminal?.threadId === input.threadId &&
port.terminal.terminalId === input.terminalId,
)
: EMPTY_PORTS,
[input.terminalId, input.threadId, ports],
);
}
+36
View File
@@ -154,6 +154,42 @@ describe("previewStateStore (single-tab)", () => {
expect(state.recentlySeenUrls).toContain("http://localhost:5173/");
});
it("optimistically removes a session before the server close event arrives", () => {
const first = makeSnapshot({ tabId: "tab_a" });
const second = makeSnapshot({
tabId: "tab_b",
updatedAt: "2026-01-01T00:00:01.000Z",
});
const store = usePreviewStateStore.getState();
store.applyServerSnapshot(ref, first);
store.applyServerSnapshot(ref, second);
store.removeSession(ref, second.tabId);
const state = selectThreadPreviewState(usePreviewStateStore.getState().byThreadKey, ref);
expect(Object.keys(state.sessions)).toEqual([first.tabId]);
expect(state.activeTabId).toBe(first.tabId);
expect(state.snapshot?.tabId).toBe(first.tabId);
});
it("treats a late server close event after optimistic removal as a no-op", () => {
const snapshot = makeSnapshot();
const store = usePreviewStateStore.getState();
store.applyServerSnapshot(ref, snapshot);
store.removeSession(ref, snapshot.tabId);
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.sessions).toEqual({});
expect(state.snapshot).toBeNull();
});
it("closed event for a different tab is a no-op", () => {
const snapshot = makeSnapshot({ tabId: "tab_a" });
const store = usePreviewStateStore.getState();
+32 -22
View File
@@ -58,6 +58,7 @@ export interface PreviewStateStoreState {
tabId: string,
overlay: DesktopPreviewOverlay | null,
) => void;
removeSession: (ref: ScopedThreadRef, tabId: string) => void;
setActiveTab: (ref: ScopedThreadRef, tabId: string) => void;
rememberUrl: (ref: ScopedThreadRef, url: string) => void;
removeThread: (ref: ScopedThreadRef) => void;
@@ -93,6 +94,27 @@ const dedupeRecentUrls = (existing: string[], url: string): string[] => {
return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
};
const removeSession = (current: ThreadPreviewState, tabId: string): ThreadPreviewState => {
if (!current.sessions[tabId]) return current;
const { [tabId]: _closed, ...sessions } = current.sessions;
const { [tabId]: _desktop, ...desktopByTabId } = current.desktopByTabId;
const nextSnapshot =
Object.values(sessions)
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
.at(-1) ?? null;
const activeTabId =
current.activeTabId === tabId ? (nextSnapshot?.tabId ?? null) : current.activeTabId;
const snapshot = activeTabId ? (sessions[activeTabId] ?? nextSnapshot) : nextSnapshot;
return {
...current,
sessions,
desktopByTabId,
activeTabId: snapshot?.tabId ?? null,
snapshot,
desktopOverlay: snapshot ? (desktopByTabId[snapshot.tabId] ?? null) : null,
};
};
export const usePreviewStateStore = create<PreviewStateStoreState>()((set) => ({
byThreadKey: {},
applyServerEvent: (ref, event) =>
@@ -145,28 +167,9 @@ export const usePreviewStateStore = create<PreviewStateStoreState>()((set) => ({
});
break;
case "closed":
nextByThread = updateThread(state, threadKey, (current) => {
if (!current.sessions[event.tabId]) return current;
const { [event.tabId]: _closed, ...sessions } = current.sessions;
const { [event.tabId]: _desktop, ...desktopByTabId } = current.desktopByTabId;
const nextSnapshot =
Object.values(sessions)
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
.at(-1) ?? null;
const activeTabId =
current.activeTabId === event.tabId
? (nextSnapshot?.tabId ?? null)
: current.activeTabId;
const snapshot = activeTabId ? (sessions[activeTabId] ?? nextSnapshot) : nextSnapshot;
return {
...current,
sessions,
desktopByTabId,
activeTabId: snapshot?.tabId ?? null,
snapshot,
desktopOverlay: snapshot ? (desktopByTabId[snapshot.tabId] ?? null) : null,
};
});
nextByThread = updateThread(state, threadKey, (current) =>
removeSession(current, event.tabId),
);
break;
}
return { byThreadKey: nextByThread };
@@ -216,6 +219,13 @@ export const usePreviewStateStore = create<PreviewStateStoreState>()((set) => ({
});
return { byThreadKey: nextByThread };
}),
removeSession: (ref, tabId) =>
set((state) => {
const threadKey = scopedThreadKey(ref);
return {
byThreadKey: updateThread(state, threadKey, (current) => removeSession(current, tabId)),
};
}),
setActiveTab: (ref, tabId) =>
set((state) => {
const threadKey = scopedThreadKey(ref);
+160 -5
View File
@@ -3,6 +3,7 @@ import { type EnvironmentId, ThreadId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it } from "vite-plus/test";
import {
migratePersistedRightPanelState,
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectActiveRightPanelKindWithUrl,
@@ -18,6 +19,60 @@ beforeEach(() => {
});
describe("rightPanelStore", () => {
it("drops the legacy singleton terminal surface during migration", () => {
expect(
migratePersistedRightPanelState({
byThreadKey: {
"env-1:thread-A": {
activeSurfaceId: "terminal",
surfaces: [
{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" },
{ id: "terminal", kind: "terminal" },
],
},
},
}),
).toEqual({
byThreadKey: {
"env-1:thread-A": {
isOpen: false,
activeSurfaceId: null,
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
},
},
});
});
it("upgrades saved single-session terminal surfaces to split-capable surfaces", () => {
expect(
migratePersistedRightPanelState({
byThreadKey: {
"env-1:thread-A": {
isOpen: true,
activeSurfaceId: "terminal:term-1",
surfaces: [{ id: "terminal:term-1", kind: "terminal", resourceId: "term-1" }],
},
},
}),
).toEqual({
byThreadKey: {
"env-1:thread-A": {
isOpen: true,
activeSurfaceId: "terminal:term-1",
surfaces: [
{
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1"],
activeTerminalId: "term-1",
},
],
},
},
});
});
it("open sets the active panel for a thread", () => {
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
@@ -33,10 +88,27 @@ describe("rightPanelStore", () => {
).toHaveLength(2);
});
it("close clears the active panel", () => {
it("close hides the panel without clearing its selected surface", () => {
useRightPanelStore.getState().open(refA, "plan");
useRightPanelStore.getState().close(refA);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: "plan",
surfaces: [{ id: "plan", kind: "plan" }],
});
});
it("toggles empty panel visibility without creating a surface", () => {
useRightPanelStore.getState().toggleVisibility(refA);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
useRightPanelStore.getState().toggleVisibility(refA);
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
});
it("toggle opens then closes the same kind", () => {
@@ -86,18 +158,101 @@ describe("rightPanelStore", () => {
});
});
it("tracks one surface per terminal session", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openTerminal(refA, "term-2");
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces).toEqual([
{
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1"],
activeTerminalId: "term-1",
},
{
id: "terminal:term-2",
kind: "terminal",
resourceId: "term-2",
terminalIds: ["term-2"],
activeTerminalId: "term-2",
},
]);
expect(state.activeSurfaceId).toBe("terminal:term-2");
});
it("tracks split panes and the active pane within a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
});
useRightPanelStore.getState().activateTerminal(refA, "terminal:term-1", "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-2"],
activeTerminalId: "term-2",
});
});
it("tracks vertical layout for a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2", "vertical");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
splitDirection: "vertical",
});
});
it("closing the final terminal pane removes its surface but keeps the panel open", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
});
it("closing the active surface activates a neighboring surface", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().open(refA, "terminal");
useRightPanelStore.getState().closeSurface(refA, "terminal");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id).toBe(
"browser:tab-a",
);
});
it("closing the final surface leaves the panel open and empty", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
});
it("reconciles browser surfaces without deleting other surface kinds", () => {
useRightPanelStore.getState().open(refA, "terminal");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openBrowser(refA, "tab-b");
useRightPanelStore.getState().reconcileBrowserSurfaces(refA, ["tab-b", "tab-c"]);
@@ -106,6 +261,6 @@ describe("rightPanelStore", () => {
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map(
(surface) => surface.id,
),
).toEqual(["terminal", "browser:tab-b", "browser:tab-c"]);
).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]);
});
});
+214 -15
View File
@@ -3,8 +3,9 @@
*
* This is intentionally a shallow workspace model: it owns an ordered set of
* surface descriptors and the active surface, while each feature continues to
* own its durable resource state. Browser surfaces point at preview tab ids;
* singleton surfaces bridge the existing terminal, diff, and plan features.
* own its durable resource state. Browser surfaces point at preview tab ids,
* terminal surfaces point at terminal session ids, and diff/plan remain
* singleton surfaces.
*/
import { scopedThreadKey } from "@t3tools/client-runtime";
import type { ScopedThreadRef } from "@t3tools/contracts";
@@ -19,35 +20,59 @@ export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
export type RightPanelSurface =
| { id: `browser:${string}`; kind: "preview"; resourceId: string }
| { id: "browser:new"; kind: "preview"; resourceId: null }
| { id: "terminal"; kind: "terminal" }
| {
id: `terminal:${string}`;
kind: "terminal";
resourceId: string;
terminalIds: string[];
activeTerminalId: string;
splitDirection?: "horizontal" | "vertical";
}
| { id: "diff"; kind: "diff" }
| { id: "plan"; kind: "plan" };
const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
const RIGHT_PANEL_STORAGE_VERSION = 5;
export interface ThreadRightPanelState {
isOpen: boolean;
activeSurfaceId: string | null;
surfaces: RightPanelSurface[];
}
interface RightPanelStoreState {
byThreadKey: Record<string, ThreadRightPanelState>;
open: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "terminal">) => void;
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
splitTerminal: (
ref: ScopedThreadRef,
surfaceId: string,
terminalId: string,
direction?: "horizontal" | "vertical",
) => void;
activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
show: (ref: ScopedThreadRef) => void;
close: (ref: ScopedThreadRef) => void;
toggle: (ref: ScopedThreadRef, kind: RightPanelKind) => void;
toggleVisibility: (ref: ScopedThreadRef) => void;
toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "terminal">) => void;
removeThread: (ref: ScopedThreadRef) => void;
}
const EMPTY_THREAD_STATE: ThreadRightPanelState = { activeSurfaceId: null, surfaces: [] };
const EMPTY_THREAD_STATE: ThreadRightPanelState = {
isOpen: false,
activeSurfaceId: null,
surfaces: [],
};
const singletonSurface = (kind: Exclude<RightPanelKind, "preview">): RightPanelSurface => {
const singletonSurface = (
kind: Exclude<RightPanelKind, "preview" | "terminal">,
): RightPanelSurface => {
switch (kind) {
case "terminal":
return { id: "terminal", kind };
case "diff":
return { id: "diff", kind };
case "plan":
@@ -60,11 +85,20 @@ const browserSurface = (tabId: string | null): RightPanelSurface =>
? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
: { id: "browser:new", kind: "preview", resourceId: null };
const terminalSurface = (terminalId: string): RightPanelSurface => ({
id: `terminal:${terminalId}`,
kind: "terminal",
resourceId: terminalId,
terminalIds: [terminalId],
activeTerminalId: terminalId,
});
const upsertSurface = (
current: ThreadRightPanelState,
surface: RightPanelSurface,
activate = true,
): ThreadRightPanelState => ({
isOpen: true,
surfaces: current.surfaces.some((entry) => entry.id === surface.id)
? current.surfaces
: [...current.surfaces, surface],
@@ -78,7 +112,7 @@ const updateThread = (
): Record<string, ThreadRightPanelState> => {
const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
const next = updater(current);
if (next.activeSurfaceId === null && next.surfaces.length === 0) {
if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
if (!(threadKey in byThreadKey)) return byThreadKey;
const { [threadKey]: _removed, ...rest } = byThreadKey;
return rest;
@@ -87,6 +121,74 @@ const updateThread = (
return { ...byThreadKey, [threadKey]: next };
};
export function migratePersistedRightPanelState(persistedState: unknown): {
byThreadKey: Record<string, ThreadRightPanelState>;
} {
if (!persistedState || typeof persistedState !== "object") {
return { byThreadKey: {} };
}
const byThreadKey =
"byThreadKey" in persistedState &&
persistedState.byThreadKey &&
typeof persistedState.byThreadKey === "object"
? Object.fromEntries(
Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>).map(
([threadKey, threadState]) => {
const validThreadState =
threadState && typeof threadState === "object" ? threadState : null;
const surfaces = Array.isArray(validThreadState?.surfaces)
? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
if (surface.kind !== "terminal") return [surface];
if (
!("resourceId" in surface) ||
typeof surface.resourceId !== "string" ||
surface.id !== `terminal:${surface.resourceId}`
) {
return [];
}
const terminalIds =
"terminalIds" in surface && Array.isArray(surface.terminalIds)
? [
...new Set(
surface.terminalIds.filter(
(terminalId): terminalId is string =>
typeof terminalId === "string",
),
),
]
: [surface.resourceId];
const activeTerminalId =
"activeTerminalId" in surface &&
typeof surface.activeTerminalId === "string" &&
terminalIds.includes(surface.activeTerminalId)
? surface.activeTerminalId
: (terminalIds[0] ?? surface.resourceId);
return [
{
...surface,
terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
activeTerminalId,
},
];
})
: [];
const activeSurfaceId = surfaces.some(
(surface) => surface.id === validThreadState?.activeSurfaceId,
)
? (validThreadState?.activeSurfaceId ?? null)
: null;
const isOpen =
typeof validThreadState?.isOpen === "boolean"
? validThreadState.isOpen
: activeSurfaceId !== null;
return [threadKey, { isOpen, surfaces, activeSurfaceId }];
},
),
)
: {};
return { byThreadKey };
}
export const useRightPanelStore = create<RightPanelStoreState>()(
persist(
(set) => ({
@@ -111,11 +213,89 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
}),
})),
openTerminal: (ref, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
upsertSurface(current, terminalSurface(terminalId)),
),
})),
splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
...current,
isOpen: true,
activeSurfaceId: surfaceId,
surfaces: current.surfaces.map((surface) => {
if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
const { splitDirection: _splitDirection, ...baseSurface } = surface;
return {
...baseSurface,
terminalIds: surface.terminalIds.includes(terminalId)
? surface.terminalIds
: [...surface.terminalIds, terminalId],
activeTerminalId: terminalId,
...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
};
}),
})),
})),
activateTerminal: (ref, surfaceId, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
...current,
activeSurfaceId: surfaceId,
surfaces: current.surfaces.map((surface) =>
surface.id === surfaceId &&
surface.kind === "terminal" &&
surface.terminalIds.includes(terminalId)
? { ...surface, activeTerminalId: terminalId }
: surface,
),
})),
})),
closeTerminal: (ref, surfaceId, terminalId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
const surface = current.surfaces.find(
(entry) => entry.id === surfaceId && entry.kind === "terminal",
);
if (!surface || surface.kind !== "terminal") return current;
const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
if (terminalIds.length === 0) {
const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
return {
...current,
surfaces,
activeSurfaceId:
current.activeSurfaceId === surfaceId
? (fallback?.id ?? null)
: current.activeSurfaceId,
};
}
return {
...current,
surfaces: current.surfaces.map((entry) =>
entry.id === surfaceId && entry.kind === "terminal"
? {
...entry,
terminalIds,
activeTerminalId:
entry.activeTerminalId === terminalId
? (terminalIds.at(-1) ?? terminalIds[0]!)
: entry.activeTerminalId,
}
: entry,
),
};
}),
})),
activateSurface: (ref, surfaceId) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
current.surfaces.some((surface) => surface.id === surfaceId)
? { ...current, activeSurfaceId: surfaceId }
? { ...current, isOpen: true, activeSurfaceId: surfaceId }
: current,
),
})),
@@ -127,7 +307,7 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
if (current.activeSurfaceId !== surfaceId) return { ...current, surfaces };
const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
return { surfaces, activeSurfaceId: fallback?.id ?? null };
return { ...current, surfaces, activeSurfaceId: fallback?.id ?? null };
}),
})),
reconcileBrowserSurfaces: (ref, tabIds) =>
@@ -151,6 +331,7 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
);
const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
return {
...current,
surfaces,
activeSurfaceId: activeStillExists
? current.activeSurfaceId
@@ -158,11 +339,23 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
};
}),
})),
show: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
current.isOpen ? current : { ...current, isOpen: true },
),
})),
close: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
current.isOpen ? { ...current, isOpen: false } : current,
),
})),
toggleVisibility: (ref) =>
set((state) => ({
byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
...current,
activeSurfaceId: null,
isOpen: !current.isOpen,
})),
})),
toggle: (ref, kind) =>
@@ -171,7 +364,9 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
const active = current.surfaces.find(
(surface) => surface.id === current.activeSurfaceId,
);
if (active?.kind === kind) return { ...current, activeSurfaceId: null };
if (current.isOpen && active?.kind === kind) {
return { ...current, isOpen: false };
}
if (kind === "preview") {
const existing = current.surfaces.find((surface) => surface.kind === "preview");
return upsertSurface(current, existing ?? browserSurface(null));
@@ -189,11 +384,12 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
}),
{
name: RIGHT_PANEL_STORAGE_KEY,
version: 2,
version: RIGHT_PANEL_STORAGE_VERSION,
storage: createJSONStorage(() =>
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
),
partialize: (state) => ({ byThreadKey: state.byThreadKey }),
migrate: migratePersistedRightPanelState,
},
),
);
@@ -211,6 +407,7 @@ export function selectActiveRightPanel(
ref: ScopedThreadRef | null | undefined,
): RightPanelKind | null {
const state = selectThreadRightPanelState(byThreadKey, ref);
if (!state.isOpen) return null;
return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
}
@@ -219,6 +416,7 @@ export function selectActiveRightPanelSurface(
ref: ScopedThreadRef | null | undefined,
): RightPanelSurface | null {
const state = selectThreadRightPanelState(byThreadKey, ref);
if (!state.isOpen) return null;
return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
}
@@ -227,6 +425,7 @@ export function selectActiveRightPanelKindWithUrl(
ref: ScopedThreadRef | null | undefined,
diffSearchActive: boolean,
): RightPanelKind | null {
if (!selectThreadRightPanelState(byThreadKey, ref).isOpen) return null;
if (diffSearchActive) return "diff";
return selectActiveRightPanel(byThreadKey, ref);
}
@@ -1,3 +1,4 @@
import { WS_METHODS } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
@@ -50,6 +51,13 @@ describe("requestLatencyState", () => {
expect(getSlowRpcAckRequests()).toEqual([]);
});
it("ignores the long-lived preview automation connection", () => {
trackRpcRequestSent("1", WS_METHODS.previewAutomationConnect);
vi.advanceTimersByTime(SLOW_RPC_ACK_THRESHOLD_MS * 2);
expect(getSlowRpcAckRequests()).toEqual([]);
});
it("evicts the oldest pending requests once the tracker reaches capacity", () => {
for (let index = 0; index < MAX_TRACKED_RPC_ACK_REQUESTS + 1; index += 1) {
trackRpcRequestSent(String(index), "server.getConfig");
+3 -1
View File
@@ -1,4 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
import { WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "./atomRegistry";
@@ -21,6 +22,7 @@ interface PendingRpcAckRequest {
}
const pendingRpcAckRequests = new Map<string, PendingRpcAckRequest>();
const untrackedRpcAckTags = new Set<string>([WS_METHODS.previewAutomationConnect]);
const slowRpcAckRequestsAtom = Atom.make<ReadonlyArray<SlowRpcAckRequest>>([]).pipe(
Atom.keepAlive,
@@ -36,7 +38,7 @@ function getSlowRpcAckRequestsValue(): ReadonlyArray<SlowRpcAckRequest> {
}
function shouldTrackRpcAck(tag: string): boolean {
return !tag.includes("subscribe");
return !tag.includes("subscribe") && !untrackedRpcAckTags.has(tag);
}
export function getSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
+18
View File
@@ -56,6 +56,24 @@ describe("terminalUiStateStore actions", () => {
]);
});
it("stacks vertically split terminals in the active group", () => {
const store = useTerminalUiStateStore.getState();
store.setTerminalOpen(THREAD_REF, true);
store.splitTerminalVertical(THREAD_REF, "terminal-2");
const terminalUiState = selectThreadTerminalUiState(
useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
THREAD_REF,
);
expect(terminalUiState.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "terminal-2"],
splitDirection: "vertical",
},
]);
});
it("materializes the default terminal when opening an empty drawer", () => {
useTerminalUiStateStore.getState().setTerminalOpen(THREAD_REF, true);
+18 -1
View File
@@ -126,6 +126,7 @@ function normalizeTerminalGroups(
nextGroups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
...(group.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
});
}
@@ -155,6 +156,11 @@ function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalG
const rightGroup = right[index];
if (!leftGroup || !rightGroup) return false;
if (leftGroup.id !== rightGroup.id) return false;
if (
(leftGroup.splitDirection ?? "horizontal") !== (rightGroup.splitDirection ?? "horizontal")
) {
return false;
}
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
}
return true;
@@ -241,6 +247,7 @@ function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[
return groups.map((group) => ({
id: group.id,
terminalIds: [...group.terminalIds],
...(group.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),
}));
}
@@ -248,6 +255,7 @@ function upsertTerminalIntoGroups(
state: ThreadTerminalUiState,
terminalId: string,
mode: "split" | "new",
splitDirection: "horizontal" | "vertical" = "horizontal",
): ThreadTerminalUiState {
const normalized = normalizeThreadTerminalUiState(state);
const effectiveMode: "split" | "new" = normalized.terminalIds.length === 0 ? "new" : mode;
@@ -323,6 +331,11 @@ function upsertTerminalIntoGroups(
destinationGroup.terminalIds.push(terminalId);
}
}
if (splitDirection === "vertical") {
destinationGroup.splitDirection = "vertical";
} else {
delete destinationGroup.splitDirection;
}
return normalizeThreadTerminalUiState({
...normalized,
@@ -357,8 +370,9 @@ function setThreadTerminalHeight(
function splitThreadTerminal(
state: ThreadTerminalUiState,
terminalId: string,
direction: "horizontal" | "vertical" = "horizontal",
): ThreadTerminalUiState {
return upsertTerminalIntoGroups(state, terminalId, "split");
return upsertTerminalIntoGroups(state, terminalId, "split", direction);
}
function newThreadTerminal(
@@ -510,6 +524,7 @@ interface TerminalUiStateStoreState {
setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void;
splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
splitTerminalVertical: (threadRef: ScopedThreadRef, terminalId: string) => void;
newTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
ensureTerminal: (
threadRef: ScopedThreadRef,
@@ -554,6 +569,8 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
updateTerminal(threadRef, (state) => setThreadTerminalHeight(state, height)),
splitTerminal: (threadRef, terminalId) =>
updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId)),
splitTerminalVertical: (threadRef, terminalId) =>
updateTerminal(threadRef, (state) => splitThreadTerminal(state, terminalId, "vertical")),
newTerminal: (threadRef, terminalId) =>
updateTerminal(threadRef, (state) => newThreadTerminal(state, terminalId)),
ensureTerminal: (threadRef, terminalId, options) =>
+1
View File
@@ -30,6 +30,7 @@ export type ProjectScript = ContractProjectScript;
export interface ThreadTerminalGroup {
id: string;
terminalIds: string[];
splitDirection?: "horizontal" | "vertical";
}
export interface ChatImageAttachment {
+33
View File
@@ -455,6 +455,15 @@ export interface DesktopPreviewTabState {
updatedAt: string;
}
export interface DesktopPreviewPointerEvent {
tabId: string;
phase: "move" | "click";
x: number;
y: number;
sequence: number;
createdAt: string;
}
/**
* Static config a renderer needs to mount a preview `<webview>`. Returned
* atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer
@@ -478,6 +487,26 @@ export interface DesktopPreviewWebviewConfig {
preloadUrl: string | null;
}
export interface DesktopPreviewAnnotationTheme {
colorScheme: "light" | "dark";
radius: string;
background: string;
foreground: string;
popover: string;
popoverForeground: string;
primary: string;
primaryForeground: string;
muted: string;
mutedForeground: string;
accent: string;
accentForeground: string;
border: string;
input: string;
ring: string;
fontSans: string;
fontMono: string;
}
export interface DesktopPreviewRecordingFrame {
tabId: string;
data: string;
@@ -700,6 +729,7 @@ export interface DesktopPreviewBridge {
* the contract + main, not the renderer's mount logic.
*/
getPreviewConfig: (environmentId: EnvironmentId) => Promise<DesktopPreviewWebviewConfig>;
setAnnotationTheme: (theme: DesktopPreviewAnnotationTheme) => Promise<void>;
/**
* Activate the in-page element picker for the given tab. Resolves with
* the picked payload, or `null` when the user cancels (Escape / nav). The
@@ -709,6 +739,8 @@ export interface DesktopPreviewBridge {
/** Cancel an in-flight preview annotation session. */
cancelPickElement: (tabId: string) => Promise<void>;
captureScreenshot: (tabId: string) => Promise<DesktopPreviewScreenshotArtifact>;
revealArtifact: (path: string) => Promise<void>;
copyArtifactToClipboard: (path: string) => Promise<void>;
recording: {
startScreencast: (tabId: string) => Promise<void>;
stopScreencast: (tabId: string) => Promise<void>;
@@ -730,6 +762,7 @@ export interface DesktopPreviewBridge {
waitFor: (tabId: string, input: PreviewAutomationWaitForInput) => Promise<void>;
};
onStateChange: (listener: (tabId: string, state: DesktopPreviewTabState) => void) => () => void;
onPointerEvent: (listener: (event: DesktopPreviewPointerEvent) => void) => () => void;
}
/**
+8 -1
View File
@@ -29,6 +29,12 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedRightPanelToggle = yield* decode(KeybindingRule, {
key: "mod+alt+b",
command: "rightPanel.toggle",
});
assert.strictEqual(parsedRightPanelToggle.command, "rightPanel.toggle");
const parsedClose = yield* decode(KeybindingRule, {
key: "mod+w",
command: "terminal.close",
@@ -100,8 +106,9 @@ it.effect("parses keybindings array payload", () =>
const parsed = yield* decode(KeybindingsConfig, [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
]);
assert.lengthOf(parsed, 2);
assert.lengthOf(parsed, 3);
}),
);
+2
View File
@@ -50,8 +50,10 @@ export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMA
const STATIC_KEYBINDING_COMMANDS = [
"terminal.toggle",
"terminal.split",
"terminal.splitVertical",
"terminal.new",
"terminal.close",
"rightPanel.toggle",
"diff.toggle",
"preview.toggle",
"preview.refresh",
+4
View File
@@ -123,6 +123,7 @@ describe("DiscoveredLocalServer", () => {
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: null,
});
expect(server.port).toBe(5173);
expect(server.processName).toBe("node");
@@ -135,6 +136,7 @@ describe("DiscoveredLocalServer", () => {
url: "http://localhost:3000",
processName: null,
pid: null,
terminal: null,
});
expect(server.processName).toBeNull();
});
@@ -147,6 +149,7 @@ describe("DiscoveredLocalServer", () => {
url: "http://localhost:0",
processName: null,
pid: null,
terminal: null,
}),
).toThrow();
expect(() =>
@@ -156,6 +159,7 @@ describe("DiscoveredLocalServer", () => {
url: "http://localhost:70000",
processName: null,
pid: null,
terminal: null,
}),
).toThrow();
});
+6
View File
@@ -142,6 +142,12 @@ export const DiscoveredLocalServer = Schema.Struct({
url: Url,
processName: Schema.NullOr(TrimmedNonEmptyString),
pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
terminal: Schema.NullOr(
Schema.Struct({
threadId: ThreadId,
terminalId: TrimmedNonEmptyString,
}),
),
});
export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
+2
View File
@@ -20,7 +20,9 @@ type WhenToken =
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+alt+b", command: "rightPanel.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+shift+d", command: "terminal.splitVertical", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
+3
View File
@@ -147,6 +147,9 @@ importers:
electron-builder:
specifier: 26.8.1
version: 26.8.1([email protected])
tailwindcss:
specifier: ^4.0.0
version: 4.3.0
vite-plus:
specifier: 'catalog:'
version: 0.1.24(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])