Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 092b804ef8 Make shell command resolution use Effect file metadata
Co-authored-by: Julius Marminge <[email protected]>
2026-06-25 16:06:49 +00:00
100 changed files with 2054 additions and 10298 deletions

No files matched your search

+14 -36
View File
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
const envEntries = [
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync(
targetBinaryPath,
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
@@ -302,12 +286,6 @@ function buildMacLauncher(electronBinaryPath) {
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
@@ -1,28 +0,0 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
});
@@ -43,16 +43,7 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -79,11 +70,6 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -113,34 +99,6 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+2 -45
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -115,60 +114,18 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
+10 -387
View File
@@ -1,5 +1,4 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -19,25 +18,16 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const {
createFromPath,
fromId,
getFocusedWebContents,
mkdir,
showItemInFolder,
webviewSend,
writeFile,
writeImage,
} = vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
@@ -54,7 +44,6 @@ vi.mock("electron", () => ({
},
webContents: {
fromId,
getFocusedWebContents,
},
}));
@@ -92,7 +81,6 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
@@ -109,8 +97,6 @@ const withManager = <A>(
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
@@ -264,197 +250,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -716,178 +511,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
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);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
+74 -236
View File
@@ -25,7 +25,6 @@ import type {
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import {
type BrowserWindow,
@@ -63,7 +62,6 @@ import {
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -380,7 +378,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
artifactDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
@@ -857,24 +854,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
commandParams?: Record<string, unknown>,
) => Effect.Effect<unknown, PreviewManagerError>;
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
send: SendCommand,
enableRuntime: boolean,
) {
yield* Effect.all(
[
...(enableRuntime ? [send("Runtime.enable")] : []),
send("Input.setIgnoreInputEvents", { ignore: false }),
],
{ concurrency: 2, discard: true },
);
});
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
tabId: string,
wc: Electron.WebContents,
action: string,
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
) {
const sequence = yield* nextCounter(actionSequenceRef);
const startedAt = yield* currentIso;
@@ -915,22 +899,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return result;
},
);
// Cleanup commands must still run after human input invalidates the action's
// control epoch. Otherwise a partially dispatched input can leave Chromium
// with a held key or focus emulation enabled for subsequent actions.
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
function* (method, commandParams) {
return yield* attemptPromise(
{
operation: `${action}.cleanup.${method}`,
tabId,
webContentsId: wc.id,
},
() => wc.debugger.sendCommand(method, commandParams),
);
},
);
return yield* use(send, sendCleanup);
return yield* use(send);
});
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
exit: Exit.Exit<A, PreviewManagerError>,
@@ -1122,62 +1091,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
) {
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
if (wc.isDestroyed()) return;
const zoomFactor = yield* attempt(
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
() => wc.getZoomFactor(),
).pipe(Effect.option);
const computedNavStatus = computeNavStatus(wc);
const canGoBack = wc.navigationHistory.canGoBack();
const canGoForward = wc.navigationHistory.canGoForward();
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
const navStatus =
preserveLoadFailure &&
current.navStatus.kind === "LoadFailed" &&
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const state: PreviewTabState = {
...current,
navStatus,
canGoBack,
canGoForward,
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
yield* update(tabId, {
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
});
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const failed = (
_event: Event,
code: number,
description: string,
validatedUrl: string,
isMainFrame: boolean,
): void => {
if (code === -3 || !isMainFrame) return;
const sync = () => runFork(syncState());
const failed = (_event: Event, code: number, description: string): void => {
if (code === -3) return;
runFork(
update(tabId, {
navStatus: {
kind: "LoadFailed",
url: validatedUrl || wc.getURL(),
url: wc.getURL(),
title: wc.getTitle(),
code,
description,
@@ -1232,8 +1161,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("did-navigate", sync);
wc.off("did-navigate-in-page", sync);
wc.off("page-title-updated", sync);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
@@ -1244,8 +1173,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("did-navigate", sync);
wc.on("did-navigate-in-page", sync);
wc.on("page-title-updated", sync);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
@@ -1351,40 +1280,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
return;
}
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
if (replacedWebContentsId !== null) {
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
yield* Effect.all(
[
detachControlSession(replacedWebContentsId),
detachListeners(replacedWebContentsId),
detachControlSession(tab.webContentsId),
detachListeners(tab.webContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
}
const zoomFactor =
replacedWebContentsId !== null
? yield* attempt(
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
() => {
wc.setZoomFactor(tab.zoomFactor);
return tab.zoomFactor;
},
)
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
wc.getZoomFactor(),
);
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
@@ -1403,7 +1313,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor,
updatedAt: registeredAt,
};
return [
@@ -1421,6 +1330,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
@@ -2032,7 +1946,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationClickInput,
send: SendCommand,
) {
yield* prepareAutomationInput(send, true);
yield* Effect.all(
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
{ concurrency: 2, discard: true },
);
const point = yield* resolveClickPoint(tabId, send, input);
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
tabId,
@@ -2094,7 +2011,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
tabId: string,
send: SendCommand,
input: PreviewAutomationTypeInput,
@@ -2104,15 +2021,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const locatorJson = locator
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
: null;
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
const result = yield* evaluateWithDebugger<
| { ok: true }
| { invalidSelector: true; message: string }
| { notEditable: true }
| { notFound: true }
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
>(
tabId,
send,
@@ -2120,54 +2030,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try {
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
if (!element) return { notFound: true };
const textControl =
element instanceof HTMLTextAreaElement ||
(element instanceof HTMLInputElement &&
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
const editable = textControl || element.isContentEditable;
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
element.focus();
if (document.activeElement !== element) return { notEditable: true };
const clear = ${input.clear ?? false};
if (clear) {
if (textControl) {
element.select();
} else {
const range = document.createRange();
range.selectNodeContents(element);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
if (${input.clear ?? false}) {
if ("value" in element) element.value = "";
else if (element.isContentEditable) element.textContent = "";
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
}
const text = ${textJson};
let inserted = true;
if (text.length > 0) {
inserted = document.execCommand("insertText", false, text);
} else if (clear) {
document.execCommand("delete", false);
const cleared = textControl
? element.value.length === 0
: (element.textContent ?? "").length === 0;
if (!cleared) {
if (textControl) {
const prototype = element instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
if (valueSetter) valueSetter.call(element, "");
else element.value = "";
} else {
element.replaceChildren();
}
element.dispatchEvent(new InputEvent("input", {
bubbles: true,
inputType: "deleteContentBackward",
}));
}
}
if (!inserted) return { notEditable: true };
element.dispatchEvent(new Event("change", { bubbles: true }));
return { ok: true };
} catch (error) {
return { invalidSelector: true, message: String(error) };
@@ -2191,12 +2059,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
...automationSelectorDiagnostics(input),
});
}
if ("notEditable" in result) {
return yield* new PreviewAutomationTargetNotEditableError({
tabId,
...automationSelectorDiagnostics(input),
});
}
});
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
@@ -2204,10 +2066,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationTypeInput,
send: SendCommand,
) {
// CDP Input.insertText silently drops text until Electron has activated a hidden
// guest WebContents with a pointer event. Editing in the page runtime keeps
// background automation deterministic without stealing foreground app focus.
yield* typeIntoAutomationTarget(tabId, send, input);
yield* send("Runtime.enable");
yield* focusAutomationTarget(tabId, send, input);
yield* send("Input.insertText", { text: input.text });
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
yield* evaluateWithDebugger(
tabId,
send,
`(() => {
const element = document.activeElement;
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
element?.dispatchEvent(new Event("change", { bubbles: true }));
})()`,
false,
);
});
const automationType = Effect.fn("PreviewManager.automationType")(function* (
@@ -2222,54 +2097,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
tabId: string,
wc: Electron.WebContents,
input: PreviewAutomationPressInput,
send: SendCommand,
sendCleanup: SendCommand,
) {
yield* prepareAutomationInput(send, false);
const keySequence = makePreviewAutomationKeySequence(input, {
isMac: hostPlatform === "darwin",
});
const previouslyFocused = yield* attempt(
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
() => webContents.getFocusedWebContents(),
);
let keyDownAttempted = false;
const releaseInput = Effect.gen(function* () {
if (keyDownAttempted) {
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
Effect.ignore,
);
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
yield* attempt(
{
operation: "automationPress.restoreFocusedWebContents",
tabId,
webContentsId: previouslyFocused.id,
},
() => previouslyFocused.focus(),
).pipe(Effect.ignore);
}
});
// Focus the guest WebContents itself, not its containing BrowserWindow. This
// activates native keyboard behavior for hidden/background previews without
// changing which thread is mounted in the UI. Restore the previous renderer
// after dispatch so automation never leaves the app's input focus behind.
yield* Effect.gen(function* () {
yield* attempt(
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
() => wc.focus(),
);
yield* send("Page.bringToFront");
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
yield* expectAgentInput(tabId, keySequence.signal);
keyDownAttempted = true;
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
}).pipe(Effect.ensuring(releaseInput));
}, 0);
const key = input.key;
const text = key.length === 1 ? key : undefined;
const params = {
key,
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
};
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
});
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
@@ -2277,8 +2130,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationPressInput,
) {
const wc = yield* requireWebContents(tabId);
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
performAutomationPress(tabId, wc, input, send, sendCleanup),
yield* withControlSession(tabId, wc, "press", (send) =>
performAutomationPress(tabId, input, send),
);
});
@@ -2676,20 +2529,6 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
}
}
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
"PreviewAutomationTargetNotEditableError",
{
tabId: Schema.String,
selectorKind: PreviewAutomationSelectorKind,
selectorLength: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
}
}
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
"PreviewAutomationCoordinatesOutsideViewportError",
{
@@ -2792,7 +2631,6 @@ export const PreviewManagerError = Schema.Union([
PreviewAutomationDebuggerAttachedError,
PreviewAutomationEvaluationError,
PreviewAutomationTargetNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationCoordinatesOutsideViewportError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationResultTooLargeError,
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
-203
View File
@@ -1,203 +0,0 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -48,14 +47,12 @@ function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
setWindowOpenHandler: vi.fn(),
@@ -82,7 +79,6 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -241,73 +237,6 @@ describe("DesktopWindow", () => {
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
if (!didFailLoad || !didFinishLoad) {
return yield* Effect.die("renderer load listeners were not registered");
}
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
yield* TestClock.adjust(100);
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
["t3code-dev://app/"],
["t3code-dev://app/"],
]);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
didFinishLoad();
yield* TestClock.adjust(250);
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it("retries only transient failures for the development renderer", () => {
assert.isTrue(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -3,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "https://example.com/",
}),
);
});
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+3 -95
View File
@@ -1,6 +1,5 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -23,16 +22,6 @@ const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
-102, // ERR_CONNECTION_REFUSED
-105, // ERR_NAME_NOT_RESOLVED
-106, // ERR_INTERNET_DISCONNECTED
-118, // ERR_CONNECTION_TIMED_OUT
]);
type WindowTitleBarOptions = Pick<
Electron.BrowserWindowConstructorOptions,
@@ -97,22 +86,6 @@ export function isSameOriginRendererNavigation(input: {
}
}
export function isRetryableDevelopmentRendererLoadFailure(input: {
readonly applicationUrl: string;
readonly errorCode: number;
readonly isMainFrame: boolean;
readonly validatedUrl: string;
}): boolean {
return (
input.isMainFrame &&
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
isSameOriginRendererNavigation({
applicationUrl: input.applicationUrl,
navigationUrl: input.validatedUrl,
})
);
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -179,7 +152,6 @@ export const make = Effect.gen(function* () {
const previewManager = yield* PreviewManager.PreviewManager;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
@@ -305,61 +277,7 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
}
const retryFiber = developmentLoadRetryFiber;
developmentLoadRetryFiber = undefined;
runFork(Fiber.interrupt(retryFiber));
};
const loadApplication = () => {
if (window.isDestroyed()) {
return;
}
void window.loadURL(applicationUrl).catch(() => undefined);
};
const scheduleDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
return undefined;
}
const retryIndex = Math.min(
developmentLoadRetryIndex,
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
);
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
developmentLoadRetryIndex += 1;
developmentLoadRetryFiber = runFork(
Effect.sleep(retryInMs).pipe(
Effect.andThen(
Effect.sync(() => {
developmentLoadRetryFiber = undefined;
if (!window.isDestroyed()) {
loadApplication();
}
}),
),
),
);
return retryInMs;
};
window.webContents.on("did-finish-load", () => {
if (
environment.isDevelopment &&
!isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: window.webContents.getURL(),
})
) {
return;
}
clearDevelopmentLoadRetry();
developmentLoadRetryIndex = 0;
window.setTitle(environment.displayName);
});
window.webContents.on(
@@ -368,22 +286,11 @@ export const make = Effect.gen(function* () {
if (!isMainFrame) {
return;
}
const retryInMs =
environment.isDevelopment &&
isRetryableDevelopmentRendererLoadFailure({
applicationUrl,
errorCode,
isMainFrame,
validatedUrl: validatedURL,
})
? scheduleDevelopmentLoadRetry()
: undefined;
void runPromise(
logWindowWarning("main window failed to load", {
errorCode,
errorDescription,
url: validatedURL,
...(retryInMs === undefined ? {} : { retryInMs }),
}),
);
},
@@ -405,13 +312,14 @@ export const make = Effect.gen(function* () {
void runPromise(electronWindow.reveal(window));
});
loadApplication();
if (environment.isDevelopment) {
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
clearDevelopmentLoadRetry();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^7.0.3"
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
+13 -260
View File
@@ -19,23 +19,6 @@ const emitInterleavedAssistantToolCalls =
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
const emitStaleXAiPromptCompleteBeforeSecondHang =
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
const emitOverlappingXAiPromptCompleteOutOfOrder =
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
@@ -53,21 +36,8 @@ let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
function promptIdFromRequestMeta(
request: Pick<AcpSchema.PromptRequest, "_meta">,
): string | undefined {
const meta = request._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
function logExit(reason: string): void {
if (!exitLogPath) {
return;
@@ -75,10 +45,6 @@ function logExit(reason: string): void {
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
@@ -318,66 +284,22 @@ const program = Effect.gen(function* () {
}),
);
const emitLoadReplayNotifications = (requestedSessionId: string) => {
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "replay-tool-1",
title: "Replay tool",
kind: "search",
status: "completed",
},
});
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed assistant text" },
},
});
};
yield* agent.handleLoadSession((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (failLoadSession) {
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
}
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
emitLoadReplayNotifications(requestedSessionId);
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay-tail" },
},
});
yield* Effect.sleep(loadSessionDelayMs);
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}
if (emitLoadReplay) {
emitLoadReplayNotifications(requestedSessionId);
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
agent.client
.sessionUpdate({
sessionId: String(request.sessionId ?? sessionId),
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay" },
},
});
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
})
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionModel((request) =>
@@ -434,152 +356,19 @@ const program = Effect.gen(function* () {
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "late after cancel" },
},
});
});
}
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
promptCount += 1;
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (failPrompt) {
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
return {
stopReason: "end_turn",
_meta: {
promptId: "mock-stale-xai-prompt-1",
requestId: "mock-stale-xai-prompt-1",
},
};
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: "mock-stale-xai-prompt-1",
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: currentPromptId,
stopReason: "end_turn",
agentResult: null,
});
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
overlappingFirstPromptId = promptIdFromRequestMeta(request);
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
const secondPromptId = promptIdFromRequestMeta(request);
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: secondPromptId,
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: overlappingFirstPromptId,
stopReason: "end_turn",
agentResult: null,
});
}
return yield* Effect.never;
}
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
return yield* Effect.never;
}
if (emitXAiPromptCompleteThenHang) {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from " },
},
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child before completion" },
},
});
}
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
agentResult: null,
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child after completion" },
},
});
}
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "mock" },
},
});
return yield* Effect.never;
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
@@ -810,42 +599,6 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitForeignSessionUpdates) {
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "root before child" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child content" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: " root after child" },
},
});
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
+1 -6
View File
@@ -44,18 +44,13 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
return HttpRouter.cors({
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
: {}),
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
maxAge: 600,
+75 -56
View File
@@ -1,6 +1,5 @@
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -35,7 +34,7 @@ const client = McpSchema.McpServerClient.of({
});
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
Layer.provideMerge(PreviewAutomationBroker.layer),
);
it("normalizes empty successful notification responses to accepted", () => {
@@ -55,26 +54,36 @@ it.effect("returns bounded structural preview snapshot failures", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const events = yield* broker.connect({
const requests = yield* broker.connect({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(events, (event) =>
event.type === "connected"
? Effect.void
: broker.respond({
clientId: "mcp-failure-client",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: false,
error: {
_tag: "PreviewAutomationExecutionError",
message: "sensitive renderer failure",
detail: { consoleOutput: "sensitive browser output" },
},
}),
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: false,
error: {
_tag: "PreviewAutomationExecutionError",
message: "sensitive renderer failure",
detail: { consoleOutput: "sensitive browser output" },
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: {} })
@@ -154,50 +163,60 @@ it.effect("registers annotated tools and preserves authenticated request context
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const events = yield* broker.connect({
const requests = yield* broker.connect({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(events, (event) =>
event.type === "connected"
? Effect.void
: broker.respond({
clientId: "mcp-test-client",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: true,
result:
event.request.operation === "snapshot"
? {
url: "http://example.test/",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
accessibilityTree: {},
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
screenshot: {
mimeType: "image/png",
data: Buffer.from("png").toString("base64"),
width: 10,
height: 5,
},
}
: event.request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: true,
result:
request.operation === "snapshot"
? {
url: "http://example.test/",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
accessibilityTree: {},
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
screenshot: {
mimeType: "image/png",
data: Buffer.from("png").toString("base64"),
width: 10,
height: 5,
},
}
: request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
+4 -1
View File
@@ -214,4 +214,7 @@ const McpTransportLive = McpServer.layerHttp({
path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpTransportLive),
Layer.provide(PreviewAutomationBroker.layer),
);
@@ -1,28 +1,20 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationClientDisconnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoAvailableHostError,
PreviewAutomationTargetNotEditableError,
PreviewTabId,
PreviewAutomationNoFocusedOwnerError,
ProviderInstanceId,
ThreadId,
type PreviewAutomationHost,
type PreviewAutomationRequest,
type PreviewAutomationStreamEvent,
type PreviewAutomationOwner,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
const scope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
@@ -30,42 +22,27 @@ const scope = {
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
expiresAt: 2,
};
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: null,
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
...overrides,
});
type RoutedRequest = PreviewAutomationRequest & {
readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
};
const requestsFrom = (
events: Stream.Stream<PreviewAutomationStreamEvent>,
onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
): Stream.Stream<RoutedRequest> =>
events.pipe(
Stream.filterMap((event) => {
if (event.type === "connected") {
onConnected(event.connectionId);
return Result.failVoid;
}
return Result.succeed({ ...event.request, connectionId: event.connectionId });
}),
);
it.effect("atomically registers a connected host and correlates its response", () =>
it.effect("atomically registers a connected owner and correlates its response", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: { available: true },
@@ -84,39 +61,6 @@ it.effect("atomically registers a connected host and correlates its response", (
),
);
it.effect("announces a live replacement stream before delivering requests", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const events = yield* broker.connect(makeHost());
const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
const consumer = yield* events.pipe(
Stream.take(2),
Stream.runForEach((event) => {
receivedTypes.push(event.type);
return event.type === "connected"
? Effect.void
: broker.respond({
clientId: "client-1",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: true,
result: "ready",
});
}),
Effect.forkScoped,
);
yield* Effect.yieldNow;
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
yield* Fiber.join(consumer);
expect(receivedTypes).toEqual(["connected", "request"]);
expect(result).toBe("ready");
}),
),
);
it.effect("preserves bounded request and remote selector diagnostics", () => {
const locator = "role=button[name='request-secret']";
const remoteMessage = "Unexpected token near remote-secret.";
@@ -128,12 +72,10 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
return Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
error: remoteError,
@@ -146,7 +88,6 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
scope,
operation: "click",
input: { locator },
tabId: PreviewTabId.make("tab-1"),
timeoutMs: 1_234,
})
.pipe(Effect.flip);
@@ -180,61 +121,13 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
);
});
it.effect("classifies a remote non-editable target without collapsing it to execution", () => {
const remoteError = {
_tag: "PreviewAutomationTargetNotEditableError",
message: "remote target details",
detail: { selectorKind: "focused-element" },
} as const;
return Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
error: remoteError,
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({
scope,
operation: "type",
input: { text: "hello" },
tabId: PreviewTabId.make("tab-1"),
})
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError);
expect(error).toMatchObject({
operation: "type",
tabId: "tab-1",
selectorKind: "focused-element",
remoteTag: "PreviewAutomationTargetNotEditableError",
});
expect(error.message).toBe("Preview automation type requires an editable focused element.");
}),
);
});
it.effect("distinguishes malformed remote failures", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
}),
broker.respond({ requestId: request.requestId, ok: false }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
@@ -257,14 +150,13 @@ it.effect("distinguishes malformed remote failures", () =>
),
);
it.effect("rejects calls when no connected host exists", () =>
it.effect("rejects calls when no focused owner exists", () =>
Effect.gen(function* () {
const broker = yield* makeBroker;
const broker = yield* PreviewAutomationBroker.make;
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
expect(error).toMatchObject({
operation: "status",
environmentId: scope.environmentId,
@@ -275,425 +167,32 @@ it.effect("rejects calls when no connected host exists", () =>
}),
);
it.effect("does not create host state from focus updates without a live stream", () =>
Effect.gen(function* () {
const broker = yield* makeBroker;
yield* broker.focusHost({
clientId: "client-1",
environmentId: scope.environmentId,
connectionId: "connection-missing",
focused: true,
});
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
}),
);
it.effect("removes host availability when the authoritative request stream disconnects", () =>
it.effect("routes interactive commands to a hidden durable browser host", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const beforeAcquisition = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
);
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Fiber.interrupt(consumer);
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
}),
),
);
it.effect("routes requests for background threads through an environment-level host", () =>
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const backgroundThreadId = ThreadId.make("thread-background");
const requests = requestsFrom(yield* broker.connect(makeHost()));
let routedThreadId: string | undefined;
yield* Stream.runForEach(requests, (request) => {
routedThreadId = request.threadId;
return broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "background",
});
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const result = yield* broker.invoke<string>({
scope: {
...scope,
threadId: backgroundThreadId,
providerSessionId: "provider-session-background",
},
operation: "status",
input: {},
});
expect(result).toBe("background");
expect(routedThreadId).toBe(backgroundThreadId);
}),
),
);
it.effect("never routes a provider session to a host from another environment", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const matchingRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-matching" })),
);
const foreignRequests = requestsFrom(
yield* broker.connect(
makeHost({
clientId: "client-foreign",
environmentId: EnvironmentId.make("environment-foreign"),
}),
),
);
yield* Stream.runForEach(matchingRequests, (request) =>
broker.respond({
clientId: "client-matching",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "matching",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(foreignRequests, (request) =>
broker.respond({
clientId: "client-foreign",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "foreign",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"matching",
);
}),
),
);
it.effect("pins a provider session to its initial host despite later focus changes", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
let secondConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
(connectionId) => {
secondConnectionId = connectionId;
},
);
yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: "connection-stale",
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: firstConnectionId,
focused: true,
});
const firstPinnedScope = {
...scope,
providerSessionId: "provider-session-first-pinned",
};
expect(
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
).toBe("first");
yield* broker.focusHost({
clientId: "client-second",
environmentId: scope.environmentId,
connectionId: secondConnectionId,
focused: true,
});
expect(
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
).toBe("first");
expect(
yield* broker.invoke<string>({
scope: { ...scope, providerSessionId: "provider-session-second-pinned" },
operation: "status",
input: {},
}),
).toBe("second");
}),
),
);
it.effect("does not route new operations to legacy hosts that did not advertise support", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const legacyEvents = yield* broker.connect(makeHost());
yield* Stream.runDrain(legacyEvents).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId });
}),
),
);
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const capableRequests = requestsFrom(
yield* broker.connect(
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
),
);
const legacyRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
);
yield* Stream.runForEach(capableRequests, (request) =>
broker.respond({
clientId: "client-capable",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "capable",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(legacyRequests, (request) =>
broker.respond({
clientId: "client-legacy",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "legacy",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(
yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
).toBe("capable");
}),
),
);
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const legacyRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
);
yield* Stream.runForEach(legacyRequests, (request) =>
broker.respond({
clientId: "client-legacy",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "legacy",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"legacy",
);
const capableRequests = requestsFrom(
yield* broker.connect(
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
),
);
yield* Stream.runForEach(capableRequests, (request) =>
broker.respond({
clientId: "client-capable",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "capable",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"legacy",
);
}),
),
);
it.effect("ignores stale focus updates for a different environment", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
);
yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: EnvironmentId.make("environment-stale"),
connectionId: firstConnectionId,
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
}),
),
);
it.effect("fails over a pinned provider session only after its host disconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
);
const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: firstConnectionId,
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
yield* Fiber.interrupt(firstConsumer);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
}),
),
);
it.effect("lets the browser host resolve an active tab locally", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ tabId: null }));
let routedTabId: string | undefined;
yield* Stream.runForEach(requests, (request) => {
routedTabId = request.tabId;
return broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
});
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
@@ -704,55 +203,61 @@ it.effect("lets the browser host resolve an active tab locally", () =>
),
);
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
it.effect("preserves current owner metadata when its request stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
let replacementConnectionId = "";
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
firstConnectionId = connectionId;
});
const broker = yield* PreviewAutomationBroker.make;
const firstRequests = yield* broker.connect(makeOwner());
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
const reconnectedRequests = yield* broker.connect(makeOwner());
let routedTabId: string | undefined;
yield* Stream.runForEach(reconnectedRequests, (request) => {
routedTabId = request.tabId;
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const replacementRequests = requestsFrom(
yield* broker.connect(makeHost()),
(connectionId) => {
replacementConnectionId = connectionId;
},
);
yield* Stream.runForEach(replacementRequests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "replacement",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
expect(replacementConnectionId).not.toBe(firstConnectionId);
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
expect(result).toBe("replacement");
expect(routedTabId).toBe("tab-current");
}),
),
);
it.effect("fails requests assigned to the stream that is replaced", () =>
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.clearOwner({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: ThreadId.make("thread-stale"),
});
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
}),
),
);
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.make;
const _requests = yield* broker.connect(makeOwner());
const pending = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
const _replacementRequests = yield* broker.connect(makeOwner());
const error = yield* Fiber.join(pending);
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
@@ -770,40 +275,25 @@ it.effect("fails requests assigned to the stream that is replaced", () =>
),
);
it.effect("accepts responses only from the host that received the request", () =>
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
yield* Stream.runForEach(requests, (request) =>
Effect.gen(function* () {
yield* broker.respond({
clientId: "client-foreign",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "foreign",
});
yield* broker.respond({
clientId: "client-1",
connectionId: "connection-stale",
requestId: request.requestId,
ok: true,
result: "stale",
});
yield* broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "owner",
});
}),
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner(
makeOwner({
clientId: "client-report-only",
focusedAt: "2026-06-11T00:00:01.000Z",
}),
);
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
expect(result).toBe("owner");
expect(result).toBe("connected");
}),
),
);
+142 -267
View File
@@ -1,29 +1,26 @@
import {
PREVIEW_AUTOMATION_V1_OPERATIONS,
PreviewAutomationClientDisconnectedError,
PreviewAutomationControlInterruptedError,
PreviewAutomationExecutionError,
PreviewAutomationHostNotConnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoAvailableHostError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationRemoteUnavailableError,
PreviewAutomationRequestQueueClosedError,
PreviewAutomationResultTooLargeError,
PreviewAutomationTabNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationTimeoutError,
PreviewAutomationUnsupportedClientError,
type PreviewAutomationError,
type PreviewAutomationOperation,
type PreviewAutomationHost,
type PreviewAutomationHostFocus,
type PreviewAutomationOwner,
type PreviewAutomationOwnerIdentity,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
type PreviewAutomationStreamEvent,
type PreviewTabId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -46,9 +43,12 @@ export class PreviewAutomationBroker extends Context.Service<
PreviewAutomationBroker,
{
readonly connect: (
host: PreviewAutomationHost,
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
owner: PreviewAutomationOwner,
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
readonly reportOwner: (
owner: PreviewAutomationOwner,
) => Effect.Effect<void, PreviewAutomationError>;
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
readonly respond: (
response: PreviewAutomationResponse,
) => Effect.Effect<void, PreviewAutomationError>;
@@ -60,12 +60,7 @@ export class PreviewAutomationBroker extends Context.Service<
interface ClientConnection {
readonly clientId: string;
readonly connectionId: string;
readonly environmentId: PreviewAutomationHost["environmentId"];
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
readonly focused: boolean;
readonly focusOrder: number;
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
readonly queue: Queue.Queue<PreviewAutomationRequest>;
}
interface PendingRequest {
@@ -74,13 +69,6 @@ interface PendingRequest {
readonly context: PreviewAutomationRequestErrorContext;
}
interface HostAssignment {
readonly clientId: ClientConnection["clientId"];
readonly connectionId: ClientConnection["connectionId"];
readonly queue: ClientConnection["queue"];
readonly expiresAt: number;
}
interface PreviewAutomationRequestErrorContext {
readonly operation: PreviewAutomationOperation;
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
@@ -88,7 +76,6 @@ interface PreviewAutomationRequestErrorContext {
readonly providerSessionId: string;
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
readonly clientId: string;
readonly connectionId: ClientConnection["connectionId"];
readonly requestId: string;
readonly tabId?: PreviewTabId;
readonly timeoutMs: number;
@@ -98,36 +85,11 @@ interface PreviewAutomationRequestErrorContext {
interface BrokerState {
readonly clients: ReadonlyMap<string, ClientConnection>;
readonly assignments: ReadonlyMap<string, HostAssignment>;
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
readonly pending: ReadonlyMap<string, PendingRequest>;
readonly requestSequence: number;
readonly focusSequence: number;
}
const removeConnectionFromState = (
current: BrokerState,
clientId: string,
queue: ClientConnection["queue"],
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
const clients = new Map(current.clients);
const assignments = new Map(current.assignments);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
for (const [assignmentKey, assignment] of assignments) {
if (assignment.queue === queue) assignments.delete(assignmentKey);
}
for (const [requestId, entry] of pending) {
if (entry.queue !== queue) continue;
pending.delete(requestId);
disconnected.push(entry);
}
return {
state: { ...current, clients, assignments, pending },
disconnected,
};
};
const selectorDiagnosticsFromInput = (
input: unknown,
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
@@ -141,14 +103,6 @@ const selectorDiagnosticsFromInput = (
return {};
};
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
`${scope.environmentId}\u0000${scope.providerSessionId}`;
const supportsOperation = (
connection: ClientConnection,
operation: PreviewAutomationOperation,
): boolean => connection.supportedOperations.has(operation);
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
function remoteDetailKind(detail: unknown): RemoteDetailKind {
@@ -177,8 +131,8 @@ const classifyResponseError = (
cause: error,
};
switch (error._tag) {
case "PreviewAutomationNoAvailableHostError":
return new PreviewAutomationNoAvailableHostError({
case "PreviewAutomationNoFocusedOwnerError":
return new PreviewAutomationNoFocusedOwnerError({
...context,
...remoteDiagnostics,
});
@@ -208,36 +162,6 @@ const classifyResponseError = (
...remoteDiagnostics,
});
}
case "PreviewAutomationTargetNotEditableError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
const remoteSelectorKind =
detail &&
"selectorKind" in detail &&
(detail.selectorKind === "focused-element" ||
detail.selectorKind === "locator" ||
detail.selectorKind === "selector")
? detail.selectorKind
: undefined;
const remoteSelectorLength =
detail &&
"selectorLength" in detail &&
typeof detail.selectorLength === "number" &&
Number.isInteger(detail.selectorLength) &&
detail.selectorLength >= 0
? detail.selectorLength
: undefined;
return new PreviewAutomationTargetNotEditableError({
...context,
...remoteDiagnostics,
...(remoteSelectorKind === undefined && context.selectorKind === undefined
? {}
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
...(remoteSelectorLength === undefined && context.selectorLength === undefined
? {}
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
});
}
case "PreviewAutomationResultTooLargeError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
@@ -269,21 +193,36 @@ const classifyResponseError = (
};
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const crypto = yield* Crypto.Crypto;
const state = yield* SynchronizedRef.make<BrokerState>({
clients: new Map(),
assignments: new Map(),
owners: new Map(),
pending: new Map(),
requestSequence: 0,
focusSequence: 0,
});
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
clientId: string,
queue: ClientConnection["queue"],
disconnected: ReadonlyArray<PendingRequest>,
) {
const toFail = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
if (current.clients.get(clientId)?.queue === queue) {
clients.delete(clientId);
owners.delete(clientId);
}
for (const [requestId, entry] of pending) {
if (entry.queue === queue) {
pending.delete(requestId);
disconnected.push(entry);
}
}
return [disconnected, { ...current, clients, owners, pending }] as const;
});
yield* Effect.forEach(
disconnected,
toFail,
({ deferred, context }) =>
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
{ discard: true },
@@ -291,89 +230,54 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
yield* Queue.shutdown(queue);
});
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
clientId: string,
queue: ClientConnection["queue"],
) {
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
const removed = removeConnectionFromState(current, clientId, queue);
return [removed.disconnected, removed.state] as const;
});
yield* closeConnection(queue, disconnected);
});
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
host: PreviewAutomationHost,
) {
const clientId = host.clientId;
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
yield* Queue.offer(queue, { type: "connected", connectionId });
const connection: ClientConnection = {
clientId,
connectionId,
environmentId: host.environmentId,
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
focused: false,
focusOrder: 0,
queue,
};
const registration = yield* SynchronizedRef.modify(state, (current) => {
const previousConnection = current.clients.get(clientId);
const removed = previousConnection
? removeConnectionFromState(current, clientId, previousConnection.queue)
: { state: current, disconnected: [] };
const clients = new Map(removed.state.clients);
const focusSequence = removed.state.focusSequence + 1;
const registeredConnection = { ...connection, focusOrder: focusSequence };
clients.set(clientId, registeredConnection);
return [
{
previousConnection,
disconnected: removed.disconnected,
registeredConnection,
},
{ ...removed.state, clients, focusSequence },
] as const;
});
if (registration.previousConnection) {
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
}
return registration.registeredConnection;
});
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
"PreviewAutomationBroker.connect",
)((host) =>
Effect.succeed(
Stream.unwrap(
Effect.acquireRelease(acquireConnection(host), (connection) =>
disconnect(connection.clientId, connection.queue),
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
),
),
);
)(function* (owner) {
const clientId = owner.clientId;
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
const previous = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const existingOwner = current.owners.get(clientId);
clients.set(clientId, { clientId, queue });
owners.set(
clientId,
existingOwner?.environmentId === owner.environmentId &&
existingOwner.threadId === owner.threadId
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
: owner,
);
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
});
if (previous) yield* disconnect(clientId, previous.queue);
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
});
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
"PreviewAutomationBroker.focusHost",
)(function* (host) {
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
"PreviewAutomationBroker.reportOwner",
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const currentHost = current.clients.get(host.clientId);
const owners = new Map(current.owners);
owners.set(owner.clientId, owner);
return { ...current, owners };
});
});
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
"PreviewAutomationBroker.clearOwner",
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const currentOwner = current.owners.get(owner.clientId);
if (
!currentHost ||
currentHost.environmentId !== host.environmentId ||
currentHost.connectionId !== host.connectionId
!currentOwner ||
currentOwner.environmentId !== owner.environmentId ||
currentOwner.threadId !== owner.threadId
) {
return current;
}
const clients = new Map(current.clients);
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
clients.set(host.clientId, {
...currentHost,
focused: host.focused,
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
});
return { ...current, clients, focusSequence };
const owners = new Map(current.owners);
owners.delete(owner.clientId);
return { ...current, owners };
});
});
@@ -382,13 +286,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
)(function* (response) {
const pending = yield* SynchronizedRef.modify(state, (current) => {
const entry = current.pending.get(response.requestId);
if (
!entry ||
entry.context.clientId !== response.clientId ||
entry.context.connectionId !== response.connectionId
) {
return [undefined, current] as const;
}
if (!entry) return [undefined, current] as const;
const next = new Map(current.pending);
next.delete(response.requestId);
return [entry, { ...current, pending: next }] as const;
@@ -409,83 +307,29 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
): Effect.fn.Return<A, PreviewAutomationError> {
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const now = yield* Clock.currentTimeMillis;
const route = yield* SynchronizedRef.modify(state, (current) => {
const assignments = new Map(
Array.from(current.assignments).filter(([, assignment]) => {
const connection = current.clients.get(assignment.clientId);
return (
assignment.expiresAt > now &&
connection?.connectionId === assignment.connectionId &&
connection.queue === assignment.queue
);
}),
);
const assignmentKey = hostAssignmentKey(input.scope);
const assigned = assignments.get(assignmentKey);
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
// Keep one provider session on one physical desktop runtime so a
// multi-step browser interaction cannot jump between independent
// Electron cookie/DOM state. A live assignment that predates an
// operation is not silently moved to a newer client: the caller gets a
// capability failure and can deliberately start a fresh provider
// session. A dead lease is pruned above and may fail over.
const connection =
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
? assignedConnection
: hasLiveAssignment
? undefined
: Array.from(current.clients.values())
.filter(
(host) =>
host.environmentId === input.scope.environmentId &&
supportsOperation(host, input.operation),
)
.sort(
(left, right) =>
right.supportedOperations.size - left.supportedOperations.size ||
Number(right.focused) - Number(left.focused) ||
right.focusOrder - left.focusOrder,
)[0];
if (!connection) {
if (!hasLiveAssignment) assignments.delete(assignmentKey);
return [undefined, { ...current, assignments }] as const;
const current = yield* SynchronizedRef.get(state);
const candidates = Array.from(current.owners.values())
.filter(
(owner) =>
owner.environmentId === input.scope.environmentId &&
owner.threadId === input.scope.threadId &&
owner.supportsAutomation,
)
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
if (!owner) {
const disconnectedOwner = candidates[0];
if (disconnectedOwner) {
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: disconnectedOwner.clientId,
});
}
assignments.set(assignmentKey, {
clientId: connection.clientId,
connectionId: connection.connectionId,
queue: connection.queue,
expiresAt: input.scope.expiresAt,
});
const requestId = `preview-${current.requestSequence}`;
const tabId = input.tabId;
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
const context: PreviewAutomationRequestErrorContext = {
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: connection.clientId,
connectionId: connection.connectionId,
requestId,
...(tabId === undefined ? {} : { tabId }),
timeoutMs,
...selectorDiagnostics,
};
const pending = new Map(current.pending);
pending.set(requestId, { queue: connection.queue, deferred, context });
return [
{ connection, requestId, requestContext: context },
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
] as const;
});
if (!route) {
return yield* new PreviewAutomationNoAvailableHostError({
return yield* new PreviewAutomationNoFocusedOwnerError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
@@ -493,7 +337,42 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
providerInstanceId: input.scope.providerInstanceId,
});
}
const { connection, requestId, requestContext } = route;
const connection = current.clients.get(owner.clientId);
if (!connection) {
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
});
}
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
const requestId = `preview-${next.requestSequence}`;
const tabId = input.tabId ?? owner.tabId ?? undefined;
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
const context: PreviewAutomationRequestErrorContext = {
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
requestId,
...(tabId === undefined ? {} : { tabId }),
timeoutMs,
...selectorDiagnostics,
};
const pending = new Map(next.pending);
pending.set(requestId, { queue: connection.queue, deferred, context });
return [
[requestId, context] as const,
{ ...next, pending, requestSequence: next.requestSequence + 1 },
] as const;
});
const removePending = SynchronizedRef.update(state, (next) => {
if (!next.pending.has(requestId)) return next;
const pending = new Map(next.pending);
@@ -502,16 +381,12 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
});
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
const offered = yield* Queue.offer(connection.queue, {
type: "request",
connectionId: connection.connectionId,
request: {
requestId,
threadId: input.scope.threadId,
tabId: requestContext.tabId,
operation: input.operation,
input: input.input,
timeoutMs,
},
requestId,
threadId: input.scope.threadId,
tabId: requestContext.tabId,
operation: input.operation,
input: input.input,
timeoutMs,
});
if (!offered) {
const completion = yield* Deferred.poll(deferred);
@@ -529,7 +404,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
});
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
export const layer = Layer.effect(PreviewAutomationBroker, make);
@@ -3,7 +3,6 @@ import type {
PreviewAutomationOperation,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationResizeResult,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -40,8 +39,6 @@ const handlers = {
reuseExistingTab: input.reuseExistingTab ?? true,
}),
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
preview_resize: (input) =>
invoke<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
+1 -18
View File
@@ -7,8 +7,6 @@ import {
PreviewAutomationPressInput,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationResizeInput,
PreviewAutomationResizeResult,
PreviewAutomationScrollInput,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
@@ -37,7 +35,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
export const PreviewStatusTool = Tool.make("preview_status", {
description:
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size.",
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
success: PreviewAutomationStatus,
failure: PreviewAutomationError,
dependencies,
@@ -71,19 +69,6 @@ export const PreviewNavigateTool = safeBrowserTool(
}).annotate(Tool.Title, "Navigate browser preview"),
);
export const PreviewResizeTool = safeBrowserTool(
Tool.make("preview_resize", {
description:
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
parameters: PreviewAutomationResizeInput,
success: PreviewAutomationResizeResult,
failure: PreviewAutomationError,
dependencies,
})
.annotate(Tool.Title, "Resize browser viewport")
.annotate(Tool.Idempotent, true),
);
export const PreviewSnapshotTool = readonlyBrowserTool(
Tool.make("preview_snapshot", {
description:
@@ -183,7 +168,6 @@ export const PreviewToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewSnapshotTool,
PreviewClickTool,
PreviewTypeTool,
@@ -199,7 +183,6 @@ export const PreviewStandardToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewClickTool,
PreviewTypeTool,
PreviewPressTool,
-55
View File
@@ -151,61 +151,6 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
}),
);
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
const resized = yield* manager.resize({
threadId,
tabId: opened.tabId,
viewport: { _tag: "freeform", width: 1024, height: 768 },
});
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
const navigated = yield* manager.navigate({
threadId,
tabId: opened.tabId,
url: "http://localhost:5173/resized",
});
expect(navigated.viewport).toEqual(resized.viewport);
yield* manager.reportStatus({
threadId,
tabId: opened.tabId,
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
canGoBack: true,
canGoForward: false,
});
const listed = yield* manager.list({ threadId });
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
const events = yield* collector.drain;
expect(events.map((event) => event.type)).toEqual([
"opened",
"resized",
"navigated",
"navigated",
]);
}),
);
it.effect("rejects resize for an unknown tab", () =>
Effect.gen(function* () {
const manager = yield* PreviewManager.PreviewManager;
const error = yield* Effect.flip(
manager.resize({
threadId: freshThreadId(),
tabId: "tab_missing",
viewport: { _tag: "fill" },
}),
);
expect(error._tag).toBe("PreviewSessionLookupError");
}),
);
it.effect("reportStatus emits failed for LoadFailed nav", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
-38
View File
@@ -20,8 +20,6 @@ import {
type PreviewOpenInput,
type PreviewRefreshInput,
type PreviewReportStatusInput,
type PreviewResizeInput,
FILL_PREVIEW_VIEWPORT,
PreviewSessionLookupError,
type PreviewSessionSnapshot,
} from "@t3tools/contracts";
@@ -47,9 +45,6 @@ export class PreviewManager extends Context.Service<
input: PreviewNavigateInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
readonly resize: (
input: PreviewResizeInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
@@ -119,7 +114,6 @@ const buildLoadingSnapshot = (input: {
navStatus: { _tag: "Loading", url: input.url, title: input.title },
canGoBack: false,
canGoForward: false,
viewport: FILL_PREVIEW_VIEWPORT,
updatedAt: input.updatedAt,
});
@@ -133,7 +127,6 @@ const buildIdleSnapshot = (input: {
navStatus: { _tag: "Idle" },
canGoBack: false,
canGoForward: false,
viewport: FILL_PREVIEW_VIEWPORT,
updatedAt: input.updatedAt,
});
@@ -244,7 +237,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
navStatus: { _tag: "Success", url, title: resolvedTitle },
canGoBack: session.snapshot.canGoBack,
canGoForward: session.snapshot.canGoForward,
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
updatedAt,
};
return {
@@ -277,7 +269,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
navStatus: input.navStatus,
canGoBack: input.canGoBack,
canGoForward: input.canGoForward,
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
updatedAt,
};
const emit: PreviewEvent =
@@ -308,34 +299,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
);
});
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
function* (input) {
return yield* mutateExistingSession(
input.threadId,
input.tabId,
Effect.fn("PreviewManager.resizeSession")(function* (session) {
const updatedAt = yield* currentIsoTimestamp;
const snapshot: PreviewSessionSnapshot = {
...session.snapshot,
viewport: input.viewport,
updatedAt,
};
return {
next: { ...session, snapshot },
emit: {
type: "resized",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
snapshot,
},
result: snapshot,
};
}),
);
},
);
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
function* (input) {
// Verify the session exists; the desktop bridge handles the actual reload
@@ -397,7 +360,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
open,
navigate,
reportStatus,
resize,
refresh,
close,
list,
@@ -113,23 +113,6 @@ async function waitForFileContent(filePath: string, attempts = 40) {
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
function waitForJsonLogMatch(
filePath: string,
predicate: (entry: Record<string, unknown>) => boolean,
attempts = 40,
) {
return Effect.gen(function* () {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const requests = yield* Effect.promise(() => readJsonLines(filePath));
if (requests.some(predicate)) {
return requests;
}
yield* Effect.yieldNow;
}
return yield* Effect.promise(() => readJsonLines(filePath));
});
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
@@ -1021,10 +1004,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
assert.equal(turnCompleted.payload.stopReason, "cancelled");
}
const requests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(
requests.some(
@@ -785,9 +785,6 @@ export function makeCursorAdapter(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "EventStreamBarrier":
yield* Deferred.succeed(event.acknowledge, undefined);
return;
case "ModeChanged":
return;
case "AssistantItemStarted":
@@ -10,23 +10,20 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import {
ApprovalRequestId,
GrokSettings,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TurnId,
ProviderInstanceId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
import { makeGrokAdapter } from "./GrokAdapter.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -48,11 +45,7 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
return wrapperPath;
}
function waitForFileContent(
filePath: string,
attempts = 40,
expectedContent?: string,
): Effect.Effect<string> {
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
Effect.gen(function* () {
if (remainingAttempts <= 0) {
@@ -61,10 +54,7 @@ function waitForFileContent(
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
Effect.orElseSucceed(() => ""),
);
if (
raw.trim().length > 0 &&
(expectedContent === undefined || raw.includes(expectedContent))
) {
if (raw.trim().length > 0) {
return raw;
}
yield* Effect.sleep("25 millis");
@@ -89,39 +79,6 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
it("requires a settlement to match the live Grok turn", () => {
const staleTurnId = TurnId.make("stale-turn");
const replacementTurnId = TurnId.make("replacement-turn");
assert.isFalse(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "session-1",
expectedAcpSessionId: "session-1",
liveActiveTurnId: replacementTurnId,
liveSessionActiveTurnId: replacementTurnId,
turnId: staleTurnId,
}),
);
assert.isFalse(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "replacement-session",
expectedAcpSessionId: "stale-session",
liveActiveTurnId: staleTurnId,
liveSessionActiveTurnId: staleTurnId,
turnId: staleTurnId,
}),
);
assert.isTrue(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "session-1",
expectedAcpSessionId: "session-1",
liveActiveTurnId: staleTurnId,
liveSessionActiveTurnId: staleTurnId,
turnId: staleTurnId,
}),
);
});
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
Effect.gen(function* () {
@@ -218,783 +175,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
}),
);
it.effect("reports a Grok session running only while the prompt is in flight", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-session-ready-after-prompt");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_TOOL_CALLS: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const requestOpened =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "request.opened" }>>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "request.opened"
? Deferred.succeed(requestOpened, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "check lifecycle", attachments: [] })
.pipe(Effect.forkChild);
const requestOpenedEvent = yield* Deferred.await(requestOpened);
const runningSessions = yield* adapter.listSessions();
const runningSession = runningSessions.find((session) => session.threadId === threadId);
assert.equal(runningSession?.status, "running");
assert.isDefined(runningSession?.activeTurnId);
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(requestOpenedEvent.requestId)),
"accept",
);
yield* Fiber.join(sendTurnFiber);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("restores ready without completing an unstarted turn when preparation fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-preparation-failure-while-connecting");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: "prepare invalid attachment",
attachments: [
{
type: "image",
id: "missing-image",
name: "missing.png",
mimeType: "image/png",
sizeBytes: 1,
},
],
}),
);
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(error._tag, "ProviderAdapterRequestError");
assert.isUndefined(turnCompletedEvent);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-prompt-complete-fallback");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnResult = yield* adapter.sendTurn({
threadId,
input: "exercise fallback",
attachments: [],
});
yield* Deferred.await(turnCompleted);
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
const eventTypes = runtimeEvents.map((event) => event.type);
const content = runtimeEvents
.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "content.delta" }> =>
event.type === "content.delta" && String(event.threadId) === String(threadId),
)
.map((event) => event.payload.delta)
.join("");
const terminalIndex = runtimeEvents.findIndex(
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const turnOutputTypes = new Set([
"content.delta",
"item.started",
"item.updated",
"item.completed",
"turn.plan.updated",
]);
const outputAfterTerminal = runtimeEvents
.slice(terminalIndex + 1)
.filter(
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
);
const toolTitles = runtimeEvents.flatMap((event) =>
event.type === "item.updated" && event.payload.title ? [event.payload.title] : [],
);
assert.equal(sendTurnResult.threadId, threadId);
assert.include(eventTypes, "turn.completed");
assert.equal(content, "hello from mock");
assert.isAtLeast(terminalIndex, 0);
assert.deepEqual(outputAfterTerminal, []);
assert.notInclude(toolTitles, "Child-only tool");
assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const contentDelta = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "interrupt after prompt",
attachments: [],
})
.pipe(Effect.forkChild);
yield* Deferred.await(contentDelta);
for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
yield* Fiber.interrupt(sendTurnFiber);
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const snapshot = yield* adapter.readThread(threadId);
assert.equal(snapshot.turns.length, 1);
assert.equal(snapshot.turns[0]?.items.length, 1);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("does not report a synthetic stop reason when xAI omits one", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({
threadId,
input: "exercise missing stop reason",
attachments: [],
});
yield* Deferred.await(turnCompleted);
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
assert.equal(turnCompletedEvent?.payload.state, "completed");
assert.isNull(turnCompletedEvent?.payload.stopReason);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-after-full-silence");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* Effect.gen(function* () {
yield* Effect.sleep("500 millis");
yield* adapter.interruptTurn(threadId);
}).pipe(Effect.forkChild({ startImmediately: true }));
yield* adapter.sendTurn({
threadId,
input: "hang forever",
attachments: [],
});
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const cancelledEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.lengthOf(cancelledEvents, 1);
assert.equal(cancelledEvents[0]?.payload.state, "cancelled");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
const followUpEventsBefore = runtimeEvents.length;
yield* adapter.sendTurn({
threadId,
input: "continue after stop",
attachments: [],
});
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const followUpCompletedEvents = runtimeEvents
.slice(followUpEventsBefore)
.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
assert.lengthOf(followUpCompletedEvents, 1);
assert.equal(followUpCompletedEvents[0]?.payload.state, "completed");
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")),
);
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const firstTurnStarted = yield* Deferred.make<TurnId>();
const twoTurnsCompleted = yield* Deferred.make<void>();
const completedCountRef = yield* Ref.make(0);
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "turn.started" && event.turnId !== undefined) {
yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
return;
}
if (event.type !== "turn.completed") {
return;
}
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
if (completedCount === 2) {
yield* Deferred.succeed(twoTurnsCompleted, undefined);
}
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const firstSendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "cancel this prompt", attachments: [] })
.pipe(Effect.forkChild);
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
const followUp = yield* adapter
.sendTurn({ threadId, input: "complete the follow-up", attachments: [] })
.pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds"));
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
const turnCompletedEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.notEqual(String(followUp.turnId), String(firstTurnId));
assert.deepEqual(
turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]),
[
[String(firstTurnId), "cancelled"],
[String(followUp.turnId), "completed"],
],
);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("drops late ACP notifications after a turn is cancelled", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_PROMPT_FOREVER: "1",
T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1",
}),
);
const lateNativeUpdate = yield* Deferred.make<void>();
const adapter = yield* makeTestAdapter(wrapperPath, {
nativeEventLogger: {
filePath: "memory://grok-cancelled-native-events",
write: (record: unknown) =>
JSON.stringify(record).includes("late after cancel")
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
: Effect.void,
close: () => Effect.void,
},
});
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnStarted = yield* Deferred.make<TurnId>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.started" &&
event.turnId !== undefined &&
String(event.threadId) === String(threadId)
? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "cancel before the late update", attachments: [] })
.pipe(Effect.forkChild);
const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds"));
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds"));
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const cancelledIndex = runtimeEvents.findIndex(
(event) =>
event.type === "turn.completed" &&
String(event.threadId) === String(threadId) &&
String(event.turnId) === String(turnId) &&
event.payload.state === "cancelled",
);
const turnOutputTypes = new Set([
"content.delta",
"item.started",
"item.updated",
"item.completed",
"turn.plan.updated",
]);
const outputAfterCancellation = runtimeEvents
.slice(cancelledIndex + 1)
.filter(
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
);
assert.isAtLeast(cancelledIndex, 0);
assert.deepEqual(outputAfterCancellation, []);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("lets Stop cancel during the xAI completion drain window", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-during-completion-drain");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const activeTurnIdRef = yield* Ref.make<TurnId | undefined>(undefined);
const trailingChunkTurnId = yield* Deferred.make<TurnId>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "turn.started") {
yield* Ref.set(activeTurnIdRef, event.turnId);
}
if (event.type !== "content.delta" || event.payload.delta !== "mock") {
return;
}
const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef));
if (turnId === undefined) {
return;
}
yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "cancel during completion drain",
attachments: [],
})
.pipe(Effect.forkChild);
const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds"));
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
const turnCompletedEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.lengthOf(turnCompletedEvents, 1);
assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("settles the in-flight prompt before emitting completion", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-completion-before-next-turn");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const completedCountRef = yield* Ref.make(0);
const secondTurnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) {
return Effect.void;
}
return Ref.modify(completedCountRef, (count) => {
const nextCount = count + 1;
return [nextCount, nextCount] as const;
}).pipe(
Effect.flatMap((count) => {
if (count === 1) {
return adapter
.sendTurn({
threadId,
input: "second turn after completion",
attachments: [],
})
.pipe(Effect.forkChild, Effect.asVoid);
}
if (count === 2) {
return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid);
}
return Effect.void;
}),
);
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({
threadId,
input: "first turn",
attachments: [],
});
yield* Deferred.await(secondTurnCompleted);
const completedCount = yield* Ref.get(completedCountRef);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(completedCount, 2);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("restores a Grok session to ready when the prompt RPC fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-prompt-failure-ready");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_FAIL_PROMPT: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: "fail prompt",
attachments: [],
}),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
const failedTurnCompleted = runtimeEvents.find(
(event) => event.type === "turn.completed" && event.threadId === threadId,
);
assert.equal(error._tag, "ProviderAdapterRequestError");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
assert.equal(failedTurnCompleted?.type, "turn.completed");
if (failedTurnCompleted?.type === "turn.completed") {
assert.equal(failedTurnCompleted.payload.state, "failed");
assert.isString(failedTurnCompleted.payload.errorMessage);
}
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-load-replay-filter");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_LOAD_REPLAY: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
const session = yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" },
});
yield* adapter.sendTurn({
threadId,
input: "after resume",
attachments: [],
});
assert.deepStrictEqual(session.resumeCursor, {
schemaVersion: 1,
sessionId: "mock-session-1",
});
assert.isFalse(
runtimeEvents.some(
(event) => event.type === "item.completed" && event.payload.title === "Replay tool",
),
);
assert.isFalse(
runtimeEvents.some(
(event) =>
event.type === "content.delta" && event.payload.delta === "replayed assistant text",
),
);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
@@ -1151,7 +331,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
assert.deepEqual(resolvedEvent.payload.answers, {
"Which scope should Grok use?": "Workspace",
});
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
yield* Fiber.join(sendTurnFiber);
yield* Fiber.interrupt(eventsFiber);
+56 -512
View File
@@ -22,7 +22,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
@@ -63,7 +62,6 @@ import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
promptResponseHasMissingXAiStopReason,
XAiAskUserQuestionRequest,
} from "../acp/XAiAcpExtension.ts";
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
@@ -110,8 +108,6 @@ interface GrokSessionContext {
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
interruptedTurnIds: Set<TurnId>;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
@@ -140,38 +136,10 @@ function settlePendingUserInputsAsCancelled(
);
}
function appendPromptResultToTurn(
ctx: GrokSessionContext,
turnId: TurnId,
promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,
result: EffectAcpSchema.PromptResponse,
): void {
const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === turnId
? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }
: turn,
)
: [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
const resolveSessionCallbackTurnId = (
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
threadId: ThreadId,
): TurnId | undefined => {
const ctx = sessions.get(threadId);
return ctx ? resolveCallbackTurnId(ctx) : undefined;
};
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
if (!isRecord(raw)) return undefined;
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
@@ -202,28 +170,6 @@ function selectAutoApprovedPermissionOption(
);
}
function completedStopReasonFromPromptResponse(
response: EffectAcpSchema.PromptResponse | undefined,
): EffectAcpSchema.StopReason | null {
if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {
return null;
}
return response.stopReason;
}
export function grokPromptSettlementBelongsToContext(input: {
readonly liveAcpSessionId: string;
readonly expectedAcpSessionId: string;
readonly liveActiveTurnId: TurnId | undefined;
readonly liveSessionActiveTurnId: TurnId | undefined;
readonly turnId: TurnId;
}): boolean {
return (
input.liveAcpSessionId === input.expectedAcpSessionId &&
(input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)
);
}
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
@@ -294,144 +240,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
const settlePromptInFlight = (
threadId: ThreadId,
turnId: TurnId,
expectedAcpSessionId: string,
options?: {
readonly errorMessage?: string;
readonly completedStopReason?: EffectAcpSchema.StopReason | null;
readonly emitTurnCompletion?: boolean;
/** Interrupt/cancel: drop every outstanding prompt slot and settle once. */
readonly settleAllPrompts?: boolean;
},
) =>
Effect.gen(function* () {
const liveCtx = sessions.get(threadId);
if (!liveCtx) {
return;
}
const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({
liveAcpSessionId: liveCtx.acpSessionId,
expectedAcpSessionId,
liveActiveTurnId: liveCtx.activeTurnId,
liveSessionActiveTurnId: liveCtx.session.activeTurnId,
turnId,
});
if (!settlementBelongsToLiveContext) {
// interruptTurn already consumed every prompt slot for this turn. A
// late prompt result must neither emit a second terminal event nor
// consume a slot belonging to a newer turn on the same ACP session.
if (
liveCtx.acpSessionId !== expectedAcpSessionId ||
liveCtx.interruptedTurnIds.has(turnId)
) {
return;
}
if (options?.emitTurnCompletion !== false) {
if (options?.errorMessage !== undefined) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId,
payload: {
state: "failed",
errorMessage: options.errorMessage,
},
});
} else if (options?.completedStopReason !== undefined) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId,
payload: {
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
stopReason: options.completedStopReason ?? null,
},
});
}
}
return;
}
let settleTurnId = turnId;
if (options?.settleAllPrompts) {
liveCtx.promptsInFlight = 0;
if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {
const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;
if (!fallbackTurnId) {
if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") {
const updatedAt = yield* nowIso;
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
liveCtx.activeTurnId = undefined;
liveCtx.session = {
...readySession,
status: "ready",
updatedAt,
};
}
return;
}
settleTurnId = fallbackTurnId;
}
} else {
const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);
if (
remainingPrompts > 0 ||
liveCtx.activeTurnId !== settleTurnId ||
liveCtx.session.activeTurnId !== settleTurnId
) {
liveCtx.promptsInFlight = remainingPrompts;
return;
}
liveCtx.promptsInFlight = remainingPrompts;
}
const updatedAt = yield* nowIso;
const canEmitTurnCompletion =
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;
const shouldEmitCompletedTurn =
options?.completedStopReason !== undefined && canEmitTurnCompletion;
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
liveCtx.activeTurnId = undefined;
liveCtx.session = {
...readySession,
status: "ready",
updatedAt,
};
if (options?.emitTurnCompletion === false) {
return;
}
if (shouldEmitFailedTurn) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId: settleTurnId,
payload: {
state: "failed",
errorMessage: options.errorMessage,
},
});
} else if (shouldEmitCompletedTurn) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId: settleTurnId,
payload: {
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
stopReason: options.completedStopReason ?? null,
},
});
}
});
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
Effect.gen(function* () {
if (!nativeEventLogger) return;
@@ -463,8 +271,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const emitPlanUpdate = (
ctx: GrokSessionContext,
turnId: TurnId | undefined,
stamp: { readonly eventId: EventId; readonly createdAt: string },
payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
@@ -476,17 +282,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
method: string,
) =>
Effect.gen(function* () {
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
ctx.lastPlanFingerprint = fingerprint;
yield* offerRuntimeEvent(
makeAcpPlanUpdatedEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId,
turnId: ctx.activeTurnId,
payload,
source: "acp.jsonrpc",
method,
@@ -618,14 +424,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const resolution = yield* Deferred.make<PendingUserInputResolution>();
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
pendingUserInputs.set(requestId, { resolution });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractXAiAskUserQuestions(params) },
raw: {
@@ -642,7 +447,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolvedAnswers },
raw: {
@@ -681,14 +486,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
pendingApprovals.set(requestId, { decision });
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
@@ -708,7 +512,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
@@ -774,7 +578,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
interruptedTurnIds: new Set(),
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
@@ -783,39 +586,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
if (event._tag === "EventStreamBarrier") {
yield* Deferred.succeed(event.acknowledge, undefined);
return;
}
if (
event._tag === "PlanUpdated" ||
event._tag === "ToolCallUpdated" ||
event._tag === "ContentDelta"
) {
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
}
if (event._tag === "ModeChanged") {
return;
}
const notificationTurnId = resolveNotificationTurnId(ctx);
if (
notificationTurnId === undefined ||
ctx.interruptedTurnIds.has(notificationTurnId)
) {
return;
}
const stamp = yield* makeEventStamp();
switch (event._tag) {
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
@@ -824,44 +602,40 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* emitPlanUpdate(
ctx,
notificationTurnId,
stamp,
event.payload,
event.rawPayload,
"session/update",
);
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
@@ -923,15 +697,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
// Bind the turn id before cooperative yields so interruptTurn can
// settle this prompt even if stop arrives during preparation.
ctx.activeTurnId = turnId;
ctx.session = {
...ctx.session,
status: steeringTurnId === undefined ? "connecting" : "running",
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
return yield* Effect.gen(function* () {
const turnModelSelection =
@@ -1000,27 +765,12 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
if (ctx.interruptedTurnIds.has(turnId)) {
yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {
completedStopReason: "cancelled",
emitTurnCompletion: false,
settleAllPrompts: true,
});
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok prompt was interrupted during preparation.",
});
}
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
status: "running",
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
@@ -1046,27 +796,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
};
}).pipe(
Effect.tapCause(() =>
Effect.gen(function* () {
const liveCtx = sessions.get(input.threadId);
if (!liveCtx) {
return;
}
yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {
errorMessage: "Grok prompt preparation failed.",
emitTurnCompletion: false,
});
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
}),
);
const promptSettled = yield* Ref.make(false);
const promptRpcSucceeded = yield* Ref.make(false);
const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(
undefined,
);
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
return yield* Effect.gen(function* () {
const result = yield* prepared.acp
@@ -1074,18 +810,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
prompt: prepared.promptParts,
})
.pipe(
Effect.tap((promptResult) =>
Effect.all([
Ref.set(promptRpcSucceeded, true),
Ref.set(promptResultRef, promptResult),
]),
),
Effect.tapError((error) =>
Ref.set(
promptFailureMessageRef,
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
).pipe(Effect.andThen(prepared.acp.drainEvents)),
),
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
@@ -1096,88 +820,38 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
errorMessage: "Grok session changed before the turn completed.",
settleAllPrompts: true,
},
);
yield* Ref.set(promptSettled, true);
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
// Keep prompt settlement atomic with respect to Stop and steering.
// interruptTurn marks its target before waiting for this lock, so
// cancellation can still win while queued ACP events are drained.
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
yield* prepared.acp.drainEvents;
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
if (
ctx.promptsInFlight <= 0 ||
ctx.activeTurnId !== prepared.turnId ||
ctx.session.activeTurnId !== prepared.turnId
) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === prepared.turnId
? {
...turn,
items: [...turn.items, { prompt: prepared.promptParts, result }],
}
: turn,
)
: [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
status: "running",
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);
ctx.promptsInFlight = remainingPrompts;
// Only the last remaining prompt settles the turn. A steer-
// superseded prompt resolving while another is in flight or
// pending must leave the merged turn running.
if (
remainingPrompts === 0 &&
ctx.activeTurnId === prepared.turnId &&
ctx.session.activeTurnId === prepared.turnId
) {
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
const completedAt = yield* nowIso;
const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;
ctx.activeTurnId = undefined;
ctx.session = {
...readySession,
status: "ready",
updatedAt: completedAt,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
const completedStopReason = completedStopReasonFromPromptResponse(result);
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another
// is in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
@@ -1186,13 +860,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: completedStopReason,
stopReason: result.stopReason ?? null,
},
});
ctx.interruptedTurnIds.delete(prepared.turnId);
yield* Ref.set(promptSettled, true);
} else if (remainingPrompts > 0) {
yield* Ref.set(promptSettled, true);
}
return {
@@ -1204,153 +874,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
);
}).pipe(
Effect.ensuring(
Effect.gen(function* () {
if (yield* Ref.get(promptSettled)) {
return;
Effect.sync(() => {
const liveCtx = sessions.get(input.threadId);
if (liveCtx) {
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
}
if (yield* Ref.get(promptRpcSucceeded)) {
const promptResult = yield* Ref.get(promptResultRef);
if (promptResult === undefined) {
return;
}
yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
errorMessage: "Grok session changed before the turn completed.",
settleAllPrompts: true,
},
);
return;
}
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
return;
}
if (
ctx.promptsInFlight <= 0 ||
ctx.activeTurnId !== prepared.turnId ||
ctx.session.activeTurnId !== prepared.turnId
) {
return;
}
appendPromptResultToTurn(
ctx,
prepared.turnId,
prepared.promptParts,
promptResult,
);
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
completedStopReason: completedStopReasonFromPromptResponse(promptResult),
},
);
}),
);
return;
}
const errorMessage = yield* Ref.get(promptFailureMessageRef);
yield* withThreadLock(
input.threadId,
settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {
errorMessage: errorMessage ?? "Grok prompt request failed.",
}),
);
}).pipe(Effect.catch(() => Effect.void)),
}),
),
);
});
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const observed = yield* Effect.sync(() => {
const ctx = sessions.get(threadId);
if (!ctx || ctx.stopped) {
return {
_tag: "Proceed" as const,
acpSessionId: undefined,
interruptedTurnId: turnId,
};
}
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
return { _tag: "Ignore" as const };
}
const interruptedTurnId = turnId ?? activeTurnId;
if (interruptedTurnId !== undefined) {
ctx.interruptedTurnIds.add(interruptedTurnId);
}
return {
_tag: "Proceed" as const,
acpSessionId: ctx.acpSessionId,
interruptedTurnId,
};
});
if (observed._tag === "Ignore") {
return;
}
yield* withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {
return;
}
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
return;
}
if (
observed.interruptedTurnId !== undefined &&
activeTurnId !== undefined &&
activeTurnId !== observed.interruptedTurnId
) {
return;
}
const interruptedTurnId =
observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
if (interruptedTurnId) {
ctx.interruptedTurnIds.add(interruptedTurnId);
yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {
completedStopReason: "cancelled",
settleAllPrompts: true,
});
} else if (
ctx.promptsInFlight > 0 ||
ctx.session.status === "running" ||
ctx.session.status === "connecting"
) {
const updatedAt = yield* nowIso;
ctx.promptsInFlight = 0;
ctx.activeTurnId = undefined;
const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;
ctx.session = {
...readySession,
status: "ready",
updatedAt,
};
}
}),
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
});
@@ -7,9 +7,6 @@ import * as NodeFS from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as TestClock from "effect/testing/TestClock";
import * as Stream from "effect/Stream";
import { describe, expect } from "vite-plus/test";
@@ -116,122 +113,6 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("drops session updates emitted for a child ACP session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(
notes
.filter((note) => note._tag === "ContentDelta")
.map((note) => note.text)
.join(""),
).toBe("root before child root after child");
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("supports successive standard ACP prompts", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptFiber = yield* runtime
.prompt({
prompt: [{ type: "text", text: "hang forever" }],
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust("500 millis");
yield* runtime.cancel;
const firstPromptResult = yield* Fiber.join(promptFiber);
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("segments assistant text around ACP tool calls", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
@@ -465,109 +346,6 @@ describe("AcpSessionRuntime", () => {
);
});
it.effect("fails session startup when session/load returns an error", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const error = yield* runtime.start().pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_FAIL_LOAD_SESSION: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "stale-session-id",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("ignores session/update replay notifications during session/load", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
"AssistantItemStarted",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_LOAD_REPLAY: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
expect(started.sessionId).toBe("mock-session-1");
expect(started.sessionSetupResult._meta).toMatchObject({
t3SessionLoadReady: "replay_idle",
});
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
Effect.timeoutOption("100 millis"),
);
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
sessionLoadReplayIdleGap: "50 millis",
sessionLoadTimeout: "1 second",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
TestClock.withLive,
),
);
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
@@ -8,8 +8,6 @@ import {
parsePermissionRequest,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
syntheticLoadSessionResponseFromInitialize,
} from "./AcpRuntimeModel.ts";
describe("AcpRuntimeModel", () => {
@@ -61,95 +59,6 @@ describe("AcpRuntimeModel", () => {
expect(modelConfigId).toBe("model");
});
it("detects Grok session replay updates from _meta.isReplay", () => {
expect(
sessionUpdateIsReplay({
_meta: { isReplay: true },
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateIsReplay({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "live" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(false);
});
it("builds a synthetic load response from initialize model state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.currentModelId).toBe("grok-build");
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("accepts initialize model descriptions with null", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.availableModels[0]?.description).toBeNull();
});
it("ignores malformed initialize model state in synthetic load responses", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [null],
},
modeState: {
currentModeId: "code",
availableModes: [{ id: "code", name: 12 }],
},
},
} as EffectAcpSchema.InitializeResponse);
expect(response.models).toBeUndefined();
expect(response.modes).toBeUndefined();
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("builds a synthetic load response with initialize mode state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modeState: {
currentModeId: "code",
availableModes: [
{ id: "ask", name: "Ask" },
{ id: "code", name: "Code" },
],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.modes?.currentModeId).toBe("code");
expect(response.modes?.availableModes).toHaveLength(2);
});
it("projects typed ACP tool call updates into runtime events", () => {
const created = parseSessionUpdateEvent({
sessionId: "session-1",
@@ -1,8 +1,3 @@
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import type * as EffectAcpSchema from "effect-acp/schema";
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
import type { ToolLifecycleItemType } from "@t3tools/contracts";
@@ -11,40 +6,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
if (!isRecord(value) || typeof value.currentModelId !== "string") {
return false;
}
if (!Array.isArray(value.availableModels)) {
return false;
}
return value.availableModels.every(
(model) =>
isRecord(model) &&
typeof model.modelId === "string" &&
typeof model.name === "string" &&
(model.description === undefined ||
model.description === null ||
typeof model.description === "string"),
);
}
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
if (!isRecord(value) || typeof value.currentModeId !== "string") {
return false;
}
if (!Array.isArray(value.availableModes)) {
return false;
}
return value.availableModes.every(
(mode) =>
isRecord(mode) &&
typeof mode.id === "string" &&
typeof mode.name === "string" &&
(mode.description === undefined || typeof mode.description === "string"),
);
}
export interface AcpSessionMode {
readonly id: string;
readonly name: string;
@@ -453,58 +414,6 @@ export function parsePermissionRequest(
};
}
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
const meta = params._meta;
return isRecord(meta) && meta.isReplay === true;
}
export interface SessionLoadGate {
readonly active: boolean;
readonly lastActivityAtMillis: number | undefined;
readonly idleGap: Duration.Duration;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
}
export const waitForSessionLoadReplayIdle = (input: {
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
Effect.gen(function* () {
const pollInterval = Duration.millis(25);
while (true) {
const gate = yield* Ref.get(input.gateRef);
if (
Option.isSome(gate) &&
gate.value.active &&
gate.value.lastActivityAtMillis !== undefined
) {
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
const nowMillis = yield* Clock.currentTimeMillis;
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
}
}
yield* Effect.sleep(pollInterval);
}
});
export function syntheticLoadSessionResponseFromInitialize(
initializeResult: EffectAcpSchema.InitializeResponse,
): EffectAcpSchema.LoadSessionResponse {
const meta = initializeResult._meta;
const modelState = isRecord(meta) ? meta.modelState : undefined;
const modeState = isRecord(meta) ? meta.modeState : undefined;
const models = isSessionModelState(modelState) ? modelState : undefined;
const modes = isSessionModeState(modeState) ? modeState : undefined;
return {
...(models ? { models } : {}),
...(modes ? { modes } : {}),
_meta: {
t3SessionLoadReady: "replay_idle",
},
};
}
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
readonly modeId?: string;
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
+46 -177
View File
@@ -1,16 +1,12 @@
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -27,9 +23,6 @@ import {
mergeToolCallState,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
waitForSessionLoadReplayIdle,
type SessionLoadGate,
type AcpParsedSessionEvent,
type AcpSessionModeState,
type AcpToolCallState,
@@ -39,16 +32,6 @@ function formatConfigOptionValue(value: string | boolean): string {
return JSON.stringify(value);
}
export interface AcpSessionEventStreamBarrier {
readonly _tag: "EventStreamBarrier";
readonly acknowledge: Deferred.Deferred<void>;
}
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
const defaultSessionLoadTimeout = Duration.seconds(90);
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
export interface AcpSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -60,8 +43,6 @@ export interface AcpSessionRuntimeOptions {
readonly spawn: AcpSpawnInput;
readonly cwd: string;
readonly resumeSessionId?: string;
readonly sessionLoadTimeout?: Duration.Input;
readonly sessionLoadReplayIdleGap?: Duration.Input;
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: {
readonly name: string;
@@ -179,9 +160,7 @@ export class AcpSessionRuntime extends Context.Service<
*/
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
/** Stream of parsed ACP session events emitted after startup. */
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
/** Waits until the current event consumer has processed every queued event. */
readonly drainEvents: Effect.Effect<void>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
/** Latest mode state observed from session setup and `session/update` notifications. */
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
/** Latest configuration options observed from session setup and configuration writes. */
@@ -275,17 +254,12 @@ export const make = (
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const promptSerializationSemaphore = yield* Semaphore.make(1);
const activePromptFiberRef = yield* Ref.make<
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
>(Option.none());
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
@@ -357,40 +331,15 @@ export const make = (
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
yield* acp.handleSessionUpdate((notification) =>
Effect.gen(function* () {
const gate = yield* Ref.get(sessionLoadGateRef);
if (Option.isSome(gate) && gate.value.active) {
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
yield* Ref.set(
sessionLoadGateRef,
Option.some({
...gate.value,
lastActivityAtMillis,
}),
);
return;
}
if (sessionUpdateIsReplay(notification)) {
return;
}
const startState = yield* Ref.get(startStateRef);
// One runtime projects one root ACP session. Child-session updates need
// explicit lineage routing and must never be flattened into this stream.
if (
startState._tag !== "Started" ||
notification.sessionId !== startState.result.sessionId
) {
return;
}
yield* handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
});
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
}),
);
const initializeClientCapabilities = {
fs: {
readTextFile: false,
@@ -550,74 +499,27 @@ export const make = (
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const sessionLoadTimeout = Duration.fromInputUnsafe(
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
);
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
);
yield* Ref.set(
sessionLoadGateRef,
Option.some({
active: true,
lastActivityAtMillis: undefined,
idleGap: sessionLoadReplayIdleGap,
initializeResult,
}),
);
sessionId = options.resumeSessionId;
sessionSetupResult = yield* Effect.gen(function* () {
yield* logRequest({
method: "session/load",
payload: loadPayload,
status: "started",
});
const idleFiber = yield* waitForSessionLoadReplayIdle({
gateRef: sessionLoadGateRef,
}).pipe(Effect.forkIn(runtimeScope));
const loaded = yield* Effect.raceFirst(
acp.agent.loadSession(loadPayload),
Fiber.join(idleFiber),
).pipe(
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
Effect.timeoutOption(sessionLoadTimeout),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new EffectAcpErrors.AcpTransportError({
operation: "call-rpc",
method: "session/load",
detail: "session/load timed out waiting for RPC response or replay idle gap",
cause: undefined,
}),
),
onSome: Effect.succeed,
}),
),
Effect.tap((result) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "succeeded",
result,
}),
),
Effect.onError((cause) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "failed",
cause,
}),
),
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
acp.agent.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.agent.createSession(createPayload),
);
return loaded;
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
const createPayload = {
cwd: options.cwd,
@@ -694,48 +596,25 @@ export const make = (
handleExtNotification: acp.handleExtNotification,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
drainEvents: Effect.gen(function* () {
const acknowledge = yield* Deferred.make<void>();
yield* Queue.offer(eventQueue, {
_tag: "EventStreamBarrier",
acknowledge,
});
yield* Deferred.await(acknowledge);
}),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
prompt: (payload) =>
promptSerializationSemaphore.withPermit(
Effect.gen(function* () {
const started = yield* getStartedState;
yield* closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
});
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
const cancelledResponse = {
stopReason: "cancelled",
} satisfies EffectAcpSchema.PromptResponse;
const promptRpcFiber = yield* runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
).pipe(Effect.forkIn(runtimeScope));
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
return yield* Fiber.join(promptRpcFiber).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.succeed(cancelledResponse)
: Effect.failCause(cause),
),
Effect.ensuring(
Effect.gen(function* () {
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
yield* Ref.set(activePromptFiberRef, Option.none());
}),
return closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
}).pipe(
Effect.andThen(
runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
),
),
Effect.tap(() =>
closeActiveAssistantSegment({
@@ -747,17 +626,7 @@ export const make = (
}),
),
cancel: getStartedState.pipe(
Effect.flatMap((started) =>
Effect.gen(function* () {
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
if (Option.isSome(activePromptFiber)) {
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
}
yield* acp.agent
.cancel({ sessionId: started.sessionId })
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
}),
),
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
),
setMode: (modeId) =>
Ref.get(modeStateRef).pipe(
@@ -836,7 +705,7 @@ const handleSessionUpdate = ({
assistantSegmentRef,
params,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
@@ -932,7 +801,7 @@ const ensureActiveAssistantSegment = ({
assistantSegmentRef,
sessionId,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
}) =>
@@ -969,7 +838,7 @@ const closeActiveAssistantSegment = ({
queue,
assistantSegmentRef,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
}) =>
Ref.modify(assistantSegmentRef, (current) => {
@@ -8,7 +8,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { normalizeModelSlug } from "@t3tools/shared/model";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
@@ -69,10 +68,9 @@ export const makeGrokAcpRuntime = (
),
),
);
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(acpContext),
);
return yield* makeXAiPromptCompletionRuntime(runtime);
});
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
@@ -1,39 +1,12 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { describe, expect } from "vite-plus/test";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
makeXAiPromptCompletionRuntime,
XAiAskUserQuestionRequest,
} from "./XAiAcpExtension.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.make({
spawn: {
command: process.execPath,
args: [mockAgentPath],
env,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
});
return yield* makeXAiPromptCompletionRuntime(runtime);
});
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
@@ -274,59 +247,4 @@ describe("XAiAcpExtension", () => {
},
});
});
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
});
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const promptId = promptResult._meta?.promptId;
expect(typeof promptId).toBe("string");
expect(promptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
sessionId: "mock-session-1",
promptId,
requestId: promptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("ignores stale xAI completion from an already settled prompt", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
});
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
expect(firstPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: { promptId: "mock-stale-xai-prompt-1" },
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
const secondPromptId = secondPromptResult._meta?.promptId;
expect(typeof secondPromptId).toBe("string");
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
expect(secondPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
promptId: secondPromptId,
requestId: secondPromptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -1,29 +1,5 @@
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import type * as EffectAcpSchema from "effect-acp/schema";
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const XAiPromptCompleteNotification = Schema.Struct({
sessionId: Schema.String,
promptId: Schema.optional(Schema.String),
stopReason: Schema.optional(Schema.String),
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
});
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
interface PendingXAiPromptCompletion {
readonly sessionId: string;
readonly promptId: string;
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
}
const completedXAiPromptIdLimit = 128;
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
const XAiAskUserQuestionOption = Schema.Struct({
label: Schema.String,
@@ -195,238 +171,3 @@ export function makeXAiAskUserQuestionResponse(
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
return { outcome: "cancelled" };
}
/**
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
* The underlying runtime remains unaware of xAI methods and metadata.
*/
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
let nextPromptFallbackId = 0;
const allocatePromptFallbackId = Effect.sync(() => {
nextPromptFallbackId += 1;
return `t3-xai-prompt-${nextPromptFallbackId}`;
});
yield* runtime.handleExtNotification(
"_x.ai/session/prompt_complete",
XAiPromptCompleteNotification,
(notification) =>
resolveXAiPromptCompletionFallback({
pendingRef,
completedPromptIdsRef,
notification,
}),
);
return {
...runtime,
start: () =>
runtime
.start()
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
prompt: (payload) =>
Effect.gen(function* () {
const sessionId = yield* Ref.get(activeSessionIdRef);
if (sessionId === undefined) {
return yield* runtime.prompt(payload);
}
const promptId = yield* allocatePromptFallbackId;
const fallback = yield* registerXAiPromptCompletionFallback(
pendingRef,
sessionId,
promptId,
);
const requestPayload = {
...payload,
_meta: {
...payload._meta,
promptId: fallback.promptId,
requestId: fallback.promptId,
},
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
return yield* Effect.raceFirst(
runtime.prompt(requestPayload),
Deferred.await(fallback.deferred),
).pipe(
Effect.tap((response) =>
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
),
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
);
}),
cancel: Ref.get(activeSessionIdRef).pipe(
Effect.flatMap((sessionId) =>
sessionId === undefined
? runtime.cancel
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
Effect.andThen(runtime.cancel),
),
),
),
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
},
);
const registerXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
promptId: string,
) =>
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
Effect.tap((deferred) =>
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
),
Effect.map((deferred) => ({ deferred, promptId })),
);
const unregisterXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
const abortPendingPromptCompletions = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
) =>
Ref.modify(pendingRef, (pending) => {
const [toAbort, remaining] = pending.reduce<
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
>(
([aborting, kept], entry) =>
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
[[], []],
);
if (toAbort.length === 0) {
return [Effect.void, pending] as const;
}
return [
Effect.forEach(
toAbort,
(entry) =>
Deferred.succeed(
entry.deferred,
promptResponseFromXAi({
sessionId: entry.sessionId,
promptId: entry.promptId,
stopReason: "cancelled",
agentResult: null,
}),
),
{ concurrency: "unbounded" },
).pipe(Effect.asVoid),
remaining,
] as const;
}).pipe(Effect.flatten);
const resolveXAiPromptCompletionFallback = ({
pendingRef,
completedPromptIdsRef,
notification,
}: {
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
readonly notification: XAiPromptCompleteNotification;
}) =>
Ref.get(completedPromptIdsRef).pipe(
Effect.flatMap((completedPromptIds) => {
if (
notification.promptId !== undefined &&
completedPromptIds.includes(notification.promptId)
) {
return Effect.void;
}
return Ref.modify(pendingRef, (pending) => {
const index =
notification.promptId !== undefined
? pending.findIndex(
(entry) =>
entry.sessionId === notification.sessionId &&
entry.promptId === notification.promptId,
)
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
if (index < 0) {
return [Effect.void, pending] as const;
}
const entry = pending[index];
if (!entry) {
return [Effect.void, pending] as const;
}
return [
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
[...pending.slice(0, index), ...pending.slice(index + 1)],
] as const;
}).pipe(Effect.flatten);
}),
);
const rememberCompletedXAiPromptId = (
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
response: EffectAcpSchema.PromptResponse,
fallbackPromptId: string,
) => {
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
if (completedPromptIds.includes(promptId)) {
return completedPromptIds;
}
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
});
};
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
const meta = response._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
export function promptResponseHasMissingXAiStopReason(
response: EffectAcpSchema.PromptResponse,
): boolean {
const meta = response._meta;
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
}
function promptResponseFromXAi(
notification: XAiPromptCompleteNotification,
): EffectAcpSchema.PromptResponse {
const stopReason = normalizeXAiStopReason(notification.stopReason);
const meta: Record<string, unknown> = {
sessionId: notification.sessionId,
};
if (notification.stopReason === undefined) {
meta[xAiStopReasonMissingMetaKey] = true;
}
if (notification.promptId !== undefined) {
meta.promptId = notification.promptId;
meta.requestId = notification.promptId;
}
if (notification.agentResult !== undefined) {
meta.agentResult = notification.agentResult;
}
return {
stopReason,
_meta: meta,
};
}
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
switch (value) {
case "cancelled":
case "end_turn":
case "max_tokens":
case "max_turn_requests":
case "refusal":
return value;
default:
return "end_turn";
}
}
-67
View File
@@ -653,7 +653,6 @@ const buildAppUnderTest = (options?: {
Layer.mock(PreviewManager.PreviewManager)({
open: () => Effect.die("PreviewManager not stubbed in this test"),
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
resize: () => Effect.die("PreviewManager not stubbed in this test"),
reportStatus: () => Effect.void,
refresh: () => Effect.void,
close: () => Effect.void,
@@ -3234,32 +3233,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: { devUrl: new URL(crossOriginClientOrigin) },
});
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
method: "OPTIONS",
headers: {
origin: desktopOrigin,
"access-control-request-method": "GET",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assertBrowserApiCorsPreflightHeaders(response.headers, {
origin: desktopOrigin,
credentials: true,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
}
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -4126,46 +4099,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("shares one preview automation broker across websocket sessions", () =>
Effect.scoped(
Effect.gen(function* () {
yield* buildAppUnderTest();
const wsUrl = yield* getWsServerUrl("/ws");
const firstConnected = yield* Deferred.make<string>();
const firstClosed = yield* Deferred.make<void>();
const host = {
clientId: "shared-preview-host",
environmentId: testEnvironmentDescriptor.environmentId,
} as const;
yield* withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.previewAutomationConnect](host).pipe(
Stream.tap((event) =>
event.type === "connected"
? Deferred.succeed(firstConnected, event.connectionId)
: Effect.void,
),
Stream.runDrain,
Effect.ensuring(Deferred.succeed(firstClosed, undefined)),
),
).pipe(Effect.forkScoped);
const firstConnectionId = yield* Deferred.await(firstConnected);
const replacementEvent = yield* withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead),
).pipe(Effect.map(Option.getOrThrow));
const firstStreamClosed = yield* Deferred.await(firstClosed).pipe(
Effect.timeoutOption("2 seconds"),
);
assert.equal(replacementEvent.type, "connected");
assert.notEqual(replacementEvent.connectionId, firstConnectionId);
assert.isTrue(Option.isSome(firstStreamClosed));
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+1 -2
View File
@@ -36,7 +36,6 @@ import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/Provide
import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as ProcessRunner from "./processRunner.ts";
@@ -358,7 +357,7 @@ export const makeRoutesLayer = Layer.mergeAll(
websocketRpcRouteLayer,
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
).pipe(Layer.provide(browserApiCorsLayer));
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
+19 -19
View File
@@ -330,14 +330,14 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope],
[WS_METHODS.previewOpen, AuthOrchestrationOperateScope],
[WS_METHODS.previewNavigate, AuthOrchestrationOperateScope],
[WS_METHODS.previewResize, AuthOrchestrationOperateScope],
[WS_METHODS.previewRefresh, AuthOrchestrationOperateScope],
[WS_METHODS.previewClose, AuthOrchestrationOperateScope],
[WS_METHODS.previewList, AuthOrchestrationReadScope],
[WS_METHODS.previewReportStatus, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationConnect, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationRespond, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationFocusHost, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationReportOwner, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationClearOwner, AuthOrchestrationOperateScope],
[WS_METHODS.subscribePreviewEvents, AuthOrchestrationReadScope],
[WS_METHODS.subscribeDiscoveredLocalServers, AuthOrchestrationReadScope],
[WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],
@@ -385,10 +385,7 @@ function toAuthAccessStreamEvent(
}
}
const makeWsRpcLayer = (
currentSession: EnvironmentAuth.AuthenticatedSession,
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
) =>
const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
WsRpcGroup.toLayer(
Effect.gen(function* () {
const currentSessionId = currentSession.sessionId;
@@ -403,6 +400,7 @@ const makeWsRpcLayer = (
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const terminalManager = yield* TerminalManager.TerminalManager;
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const previewManager = yield* PreviewManager.PreviewManager;
const portDiscovery = yield* PortScanner.PortDiscovery;
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
@@ -1624,10 +1622,6 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.previewNavigate, previewManager.navigate(input), {
"rpc.aggregate": "preview",
}),
[WS_METHODS.previewResize]: (input) =>
observeRpcEffect(WS_METHODS.previewResize, previewManager.resize(input), {
"rpc.aggregate": "preview",
}),
[WS_METHODS.previewRefresh]: (input) =>
observeRpcEffect(WS_METHODS.previewRefresh, previewManager.refresh(input), {
"rpc.aggregate": "preview",
@@ -1656,10 +1650,16 @@ const makeWsRpcLayer = (
previewAutomationBroker.respond(input),
{ "rpc.aggregate": "preview-automation" },
),
[WS_METHODS.previewAutomationFocusHost]: (input) =>
[WS_METHODS.previewAutomationReportOwner]: (input) =>
observeRpcEffect(
WS_METHODS.previewAutomationFocusHost,
previewAutomationBroker.focusHost(input),
WS_METHODS.previewAutomationReportOwner,
previewAutomationBroker.reportOwner(input),
{ "rpc.aggregate": "preview-automation" },
),
[WS_METHODS.previewAutomationClearOwner]: (input) =>
observeRpcEffect(
WS_METHODS.previewAutomationClearOwner,
previewAutomationBroker.clearOwner(input),
{ "rpc.aggregate": "preview-automation" },
),
[WS_METHODS.subscribePreviewEvents]: (_input) =>
@@ -1791,9 +1791,8 @@ const makeWsRpcLayer = (
);
export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
return HttpRouter.add(
Effect.succeed(
HttpRouter.add(
"GET",
"/ws",
Effect.gen(function* () {
@@ -1812,8 +1811,9 @@ export const websocketRpcRouteLayer = Layer.unwrap(
disableTracing: true,
}).pipe(
Effect.provide(
makeWsRpcLayer(session, previewAutomationBroker).pipe(
makeWsRpcLayer(session).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(
SourceControlDiscovery.layer.pipe(
@@ -1850,6 +1850,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
EnvironmentInternalError: HttpServerRespondable.toResponse,
}),
),
);
}),
),
),
);
+3 -5
View File
@@ -3,22 +3,20 @@ import { RouterProvider } from "@tanstack/react-router";
import { describe, expect, it } from "vite-plus/test";
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
import { AppRoot } from "./AppRoot";
describe("AppRoot", () => {
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
it("shares the application atom registry with routed UI and the Electron browser host", () => {
const root = AppRoot({ router: {} as AppRouter });
expect(root.type).toBe(AppAtomRegistryProvider);
const children = Children.toArray(
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
);
expect(children).toHaveLength(3);
expect(children).toHaveLength(2);
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
expect(isValidElement(children[1]) && children[1].type).toBe(ElectronBrowserHost);
});
});
-2
View File
@@ -1,7 +1,6 @@
import { RouterProvider } from "@tanstack/react-router";
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
import type { AppRouter } from "./router";
@@ -14,7 +13,6 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
return (
<AppAtomRegistryProvider>
<RouterProvider router={router} />
<PreviewAutomationHosts />
<ElectronBrowserHost />
</AppAtomRegistryProvider>
);
@@ -1,49 +0,0 @@
import type { PreviewViewportSetting } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import {
commitViewportAndAspectRatio,
reconcileLockedAspectRatio,
} from "./browserDeviceToolbarState";
describe("commitViewportAndAspectRatio", () => {
it("commits the aspect ratio only after the viewport succeeds", async () => {
let resolveChange: (() => void) | undefined;
const onChange = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveChange = resolve;
}),
);
const onAspectRatioChange = vi.fn();
const setting: PreviewViewportSetting = { _tag: "freeform", width: 900, height: 600 };
const commit = commitViewportAndAspectRatio(setting, 1.5, onChange, onAspectRatioChange);
expect(onAspectRatioChange).not.toHaveBeenCalled();
resolveChange?.();
await commit;
expect(onAspectRatioChange).toHaveBeenCalledWith(1.5);
});
it("keeps the previous aspect ratio when the viewport commit fails", async () => {
const onAspectRatioChange = vi.fn();
await expect(
commitViewportAndAspectRatio(
{ _tag: "fill" },
null,
async () => Promise.reject(new Error("resize failed")),
onAspectRatioChange,
),
).rejects.toThrow("resize failed");
expect(onAspectRatioChange).not.toHaveBeenCalled();
});
});
describe("reconcileLockedAspectRatio", () => {
it("tracks external viewport ratios only while the lock remains active", () => {
expect(reconcileLockedAspectRatio(1.5, 16 / 9)).toBe(16 / 9);
expect(reconcileLockedAspectRatio(null, 16 / 9)).toBeNull();
expect(reconcileLockedAspectRatio(1.5, null)).toBeNull();
});
});
@@ -1,340 +0,0 @@
"use client";
import {
PREVIEW_VIEWPORT_MAX_AREA,
PREVIEW_VIEWPORT_MAX_DIMENSION,
PREVIEW_VIEWPORT_MIN_DIMENSION,
type PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESETS, resolvePreviewViewport } from "@t3tools/shared/previewViewport";
import { Link2, X } from "lucide-react";
import { useState } from "react";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import {
Select,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import { cn } from "~/lib/utils";
import { BROWSER_DEVICE_TOOLBAR_HEIGHT, resizeFreeformViewport } from "./browserViewportLayout";
import { commitViewportAndAspectRatio } from "./browserDeviceToolbarState";
const RESPONSIVE_VALUE = "responsive";
const SELECT_ITEMS = [
{ value: RESPONSIVE_VALUE, label: "Responsive" },
...PREVIEW_VIEWPORT_PRESETS.map((preset) => ({ value: preset.id, label: preset.label })),
];
function ScreenRotationIcon() {
return (
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<rect x="7.25" y="7.25" width="9.5" height="9.5" rx="1.4" transform="rotate(-45 12 12)" />
<path d="M12.5 2a10 10 0 0 1 8.4 5.4" />
<path d="M20.8 3.5v4h-4" />
<path d="M11.5 22a10 10 0 0 1-8.4-5.4" />
<path d="M3.2 20.5v-4h4" />
</svg>
);
}
interface Props {
readonly setting: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>;
readonly width: number;
readonly aspectRatio: number | null;
readonly onAspectRatioChange: (aspectRatio: number | null) => void;
readonly onChange: (setting: PreviewViewportSetting) => Promise<void>;
}
export function BrowserDeviceToolbar({
setting,
width,
aspectRatio,
onAspectRatioChange,
onChange,
}: Props) {
const [pending, setPending] = useState(false);
const [customSize, setCustomSize] = useState<{
readonly width: string;
readonly height: string;
} | null>(null);
const presentedSize = customSize ?? {
width: String(setting.width),
height: String(setting.height),
};
const selectedValue =
setting._tag === "preset" &&
PREVIEW_VIEWPORT_PRESETS.some((preset) => preset.id === setting.presetId)
? setting.presetId
: RESPONSIVE_VALUE;
const customWidth = Number(presentedSize.width);
const customHeight = Number(presentedSize.height);
const customValid =
Number.isInteger(customWidth) &&
Number.isInteger(customHeight) &&
customWidth >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
customWidth <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
customHeight >= PREVIEW_VIEWPORT_MIN_DIMENSION &&
customHeight <= PREVIEW_VIEWPORT_MAX_DIMENSION &&
customWidth * customHeight <= PREVIEW_VIEWPORT_MAX_AREA;
const apply = (next: PreviewViewportSetting, nextAspectRatio = aspectRatio) => {
setPending(true);
void commitViewportAndAspectRatio(next, nextAspectRatio, onChange, onAspectRatioChange).then(
() => {
setPending(false);
setCustomSize(null);
},
() => setPending(false),
);
};
const applyCustomSize = () => {
if (!customValid || (customWidth === setting.width && customHeight === setting.height)) {
setCustomSize(null);
return;
}
apply({ _tag: "freeform", width: customWidth, height: customHeight });
};
const updateCustomDimension = (axis: "width" | "height", value: string) => {
setCustomSize((current) => {
const next = {
width: axis === "width" ? value : (current?.width ?? String(setting.width)),
height: axis === "height" ? value : (current?.height ?? String(setting.height)),
};
const numeric = Number(value);
if (
aspectRatio === null ||
!Number.isInteger(numeric) ||
numeric < PREVIEW_VIEWPORT_MIN_DIMENSION ||
numeric > PREVIEW_VIEWPORT_MAX_DIMENSION
) {
return next;
}
const resized = resizeFreeformViewport(
setting,
axis === "width"
? { x: numeric - setting.width, y: 0 }
: { x: 0, y: numeric - setting.height },
1,
axis === "width" ? "east" : "south",
aspectRatio,
);
return { width: String(resized.width), height: String(resized.height) };
});
};
const selectViewport = (value: string | null) => {
if (!value) return;
if (value === RESPONSIVE_VALUE) {
if (setting._tag === "freeform") return;
apply({ _tag: "freeform", width: setting.width, height: setting.height });
return;
}
const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === value);
if (!preset) return;
apply(
resolvePreviewViewport({ mode: "preset", preset: preset.id }),
aspectRatio === null ? null : preset.width / preset.height,
);
};
const rotate = () => {
const hasCustomSize =
customValid && (customWidth !== setting.width || customHeight !== setting.height);
const source = hasCustomSize
? ({ _tag: "freeform", width: customWidth, height: customHeight } as const)
: setting;
apply(
{ ...source, width: source.height, height: source.width },
aspectRatio === null ? null : 1 / aspectRatio,
);
};
const toggleAspectRatio = () => {
onAspectRatioChange(aspectRatio === null ? customWidth / customHeight : null);
};
return (
<div
className="sticky left-0 top-0 z-50 flex items-center gap-0.5 overflow-x-auto border-b border-border/70 bg-background/95 px-1.5 shadow-xs backdrop-blur-md [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
style={{ width, height: BROWSER_DEVICE_TOOLBAR_HEIGHT }}
role="toolbar"
aria-label="Browser device toolbar"
data-browser-device-toolbar
onBlur={(event) => {
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
const eventTarget = event.target;
if (
(nextTarget instanceof HTMLElement &&
nextTarget.closest('[data-slot="select-positioner"]')) ||
(eventTarget instanceof HTMLElement &&
eventTarget.closest('[data-slot="select-positioner"]'))
) {
return;
}
applyCustomSize();
}}
>
{width >= 560 ? (
<span className="mr-0.5 shrink-0 text-[11px] font-medium text-muted-foreground">
Dimensions
</span>
) : null}
<Select
modal={false}
value={selectedValue}
onValueChange={selectViewport}
items={SELECT_ITEMS}
disabled={pending}
>
<SelectTrigger
variant="ghost"
size="xs"
className={cn(
"shrink-0 justify-between px-1.5 font-medium",
width >= 440 ? "w-36" : "w-24",
)}
aria-label="Browser device preset"
>
<SelectValue />
</SelectTrigger>
<SelectPopup align="start" alignItemWithTrigger={false} className="min-w-64">
<SelectItem value={RESPONSIVE_VALUE}>Responsive</SelectItem>
<SelectGroup>
<SelectGroupLabel>Standard</SelectGroupLabel>
{PREVIEW_VIEWPORT_PRESETS.map((preset) => (
<SelectItem key={preset.id} value={preset.id}>
<span className="flex w-full items-center justify-between gap-5">
<span>{preset.label}</span>
<span className="text-xs tabular-nums text-muted-foreground">
{preset.detail}
</span>
</span>
</SelectItem>
))}
</SelectGroup>
</SelectPopup>
</Select>
<form
className="m-0 flex min-w-0 shrink-0 items-center gap-0.5 border-0 p-0"
aria-label="Viewport dimensions"
onSubmit={(event) => {
event.preventDefault();
applyCustomSize();
}}
>
<Input
nativeInput
type="number"
inputMode="numeric"
size="sm"
min={PREVIEW_VIEWPORT_MIN_DIMENSION}
max={PREVIEW_VIEWPORT_MAX_DIMENSION}
value={presentedSize.width}
disabled={pending}
onFocus={() =>
setCustomSize(
(current) =>
current ?? {
width: String(setting.width),
height: String(setting.height),
},
)
}
onChange={(event) => updateCustomDimension("width", event.target.value)}
aria-label="Viewport width"
aria-invalid={!customValid}
className={cn(
"h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
width >= 360 ? "w-14" : "w-11",
)}
/>
<span className="text-xs text-muted-foreground">×</span>
<Input
nativeInput
type="number"
inputMode="numeric"
size="sm"
min={PREVIEW_VIEWPORT_MIN_DIMENSION}
max={PREVIEW_VIEWPORT_MAX_DIMENSION}
value={presentedSize.height}
disabled={pending}
onFocus={() =>
setCustomSize(
(current) =>
current ?? {
width: String(setting.width),
height: String(setting.height),
},
)
}
onChange={(event) => updateCustomDimension("height", event.target.value)}
aria-label="Viewport height"
aria-invalid={!customValid}
className={cn(
"h-6 rounded-md text-center tabular-nums [&_[data-slot=input]]:h-full [&_[data-slot=input]]:px-1 [&_[data-slot=input]]:text-xs [&_[data-slot=input]]:leading-none [&_[data-slot=input]::-webkit-inner-spin-button]:appearance-none [&_[data-slot=input]]:[appearance:textfield]",
width >= 360 ? "w-14" : "w-11",
)}
/>
</form>
<Button
variant="ghost"
size="icon-xs"
type="button"
aria-label={
aspectRatio === null ? "Lock viewport aspect ratio" : "Unlock viewport aspect ratio"
}
aria-pressed={aspectRatio !== null}
title={aspectRatio === null ? "Lock aspect ratio" : "Unlock aspect ratio"}
className={cn(aspectRatio !== null && "bg-accent text-foreground")}
disabled={pending || !customValid}
onPointerDown={(event) => event.preventDefault()}
onClick={toggleAspectRatio}
>
<Link2 className={cn(aspectRatio !== null && "text-foreground")} />
</Button>
<Button
variant="ghost"
size="icon-xs"
type="button"
aria-label="Rotate viewport"
disabled={pending}
onClick={rotate}
>
<ScreenRotationIcon />
</Button>
<Button
variant="ghost"
size="icon-xs"
type="button"
aria-label="Close device toolbar"
className="sticky right-0 ml-auto bg-background/95"
disabled={pending}
onClick={() => {
apply({ _tag: "fill" }, null);
}}
>
<X />
</Button>
</div>
);
}
@@ -1,169 +0,0 @@
"use client";
import type {
CSSProperties,
KeyboardEvent as ReactKeyboardEvent,
PointerEvent as ReactPointerEvent,
} from "react";
import { cn } from "~/lib/utils";
import {
BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
type BrowserViewportLayout,
type BrowserViewportResizeDirection,
} from "./browserViewportLayout";
interface Props {
readonly layout: BrowserViewportLayout;
readonly activeDirection: BrowserViewportResizeDirection | null;
readonly onPointerDown: (
direction: BrowserViewportResizeDirection,
event: ReactPointerEvent<HTMLButtonElement>,
) => void;
readonly onKeyDown: (
direction: BrowserViewportResizeDirection,
event: ReactKeyboardEvent<HTMLButtonElement>,
) => void;
}
type HandleKind = "horizontal" | "vertical" | "corner";
const EDGE_BUTTON_CLASS =
"group absolute z-20 touch-none border-0 bg-transparent p-0 outline-none before:absolute before:-inset-1 before:content-[''] focus-visible:bg-foreground/[0.04]";
const EDGE_GRIP_CLASS =
"pointer-events-none absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center text-muted-foreground/55 transition-colors duration-150 group-hover:text-foreground/85 group-focus-visible:text-foreground group-active:text-foreground";
function ResizeHandle(props: {
readonly direction: BrowserViewportResizeDirection;
readonly label: string;
readonly kind: HandleKind;
readonly cursorClassName: string;
readonly style: CSSProperties;
readonly active: boolean;
readonly mirrorCorner?: boolean;
readonly onPointerDown: Props["onPointerDown"];
readonly onKeyDown: Props["onKeyDown"];
}) {
const {
direction,
label,
kind,
cursorClassName,
style,
active,
mirrorCorner = false,
onPointerDown,
onKeyDown,
} = props;
return (
<button
type="button"
aria-label={`${label}. Use arrow keys to resize.`}
className={cn(EDGE_BUTTON_CLASS, kind === "corner" && "z-30", cursorClassName)}
style={style}
onPointerDown={(event) => onPointerDown(direction, event)}
onKeyDown={(event) => onKeyDown(direction, event)}
>
<span
className={cn(
EDGE_GRIP_CLASS,
kind === "vertical" && "h-8 w-1.5",
kind === "horizontal" && "h-1.5 w-8",
kind === "corner" && "size-3",
active && "text-foreground",
)}
>
{kind === "vertical" ? (
<span className="flex gap-px" aria-hidden="true">
<span className="h-6 w-px rounded-full bg-current" />
<span className="h-6 w-px rounded-full bg-current" />
</span>
) : kind === "horizontal" ? (
<span className="flex flex-col gap-px" aria-hidden="true">
<span className="h-px w-6 rounded-full bg-current" />
<span className="h-px w-6 rounded-full bg-current" />
</span>
) : (
<span
className={cn("relative block size-3", mirrorCorner && "-scale-x-100")}
aria-hidden="true"
>
<span className="absolute bottom-[3px] left-0 h-px w-3 -rotate-45 rounded-full bg-current" />
<span className="absolute bottom-0 left-[5px] h-px w-2 -rotate-45 rounded-full bg-current" />
</span>
)}
</span>
</button>
);
}
export function BrowserViewportResizeHandles({
layout,
activeDirection,
onPointerDown,
onKeyDown,
}: Props) {
const left = layout.viewportX;
const top = layout.viewportY;
const right = left + layout.viewportWidth;
const bottom = top + layout.viewportHeight;
const railSize = BROWSER_VIEWPORT_RESIZE_RAIL_SIZE;
const shared = { activeDirection, onPointerDown, onKeyDown };
return (
<>
<ResizeHandle
direction="west"
label="Resize browser viewport from left edge"
kind="vertical"
cursorClassName="cursor-ew-resize"
style={{ left: left - railSize, top, width: railSize, height: layout.viewportHeight }}
active={shared.activeDirection === "west"}
onPointerDown={shared.onPointerDown}
onKeyDown={shared.onKeyDown}
/>
<ResizeHandle
direction="east"
label="Resize browser viewport from right edge"
kind="vertical"
cursorClassName="cursor-ew-resize"
style={{ left: right, top, width: railSize, height: layout.viewportHeight }}
active={shared.activeDirection === "east"}
onPointerDown={shared.onPointerDown}
onKeyDown={shared.onKeyDown}
/>
<ResizeHandle
direction="south"
label="Resize browser viewport from bottom edge"
kind="horizontal"
cursorClassName="cursor-ns-resize"
style={{ left, top: bottom, width: layout.viewportWidth, height: railSize }}
active={shared.activeDirection === "south"}
onPointerDown={shared.onPointerDown}
onKeyDown={shared.onKeyDown}
/>
<ResizeHandle
direction="southwest"
label="Resize browser viewport from bottom-left corner"
kind="corner"
cursorClassName="cursor-nesw-resize"
style={{ left: left - railSize, top: bottom, width: railSize, height: railSize }}
active={shared.activeDirection === "southwest"}
mirrorCorner
onPointerDown={shared.onPointerDown}
onKeyDown={shared.onKeyDown}
/>
<ResizeHandle
direction="southeast"
label="Resize browser viewport from bottom-right corner"
kind="corner"
cursorClassName="cursor-nwse-resize"
style={{ left: right, top: bottom, width: railSize, height: railSize }}
active={shared.activeDirection === "southeast"}
onPointerDown={shared.onPointerDown}
onKeyDown={shared.onKeyDown}
/>
</>
);
}
+2 -5
View File
@@ -1,7 +1,6 @@
"use client";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { FILL_PREVIEW_VIEWPORT } from "@t3tools/contracts";
import { useEffect, useMemo } from "react";
import { isElectron } from "~/env";
@@ -23,7 +22,7 @@ export function ElectronBrowserHost() {
? Object.values(previewState.sessions).map((snapshot) => ({
threadRef,
snapshot,
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
active: previewState.activeTabId === snapshot.tabId,
}))
: [];
}),
@@ -74,7 +73,7 @@ export function ElectronBrowserHost() {
if (!isElectron) return null;
return (
<div className="contents" data-electron-browser-host>
{sessions.map(({ threadRef, snapshot, zoomFactor }) => {
{sessions.map(({ threadRef, snapshot }) => {
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
return (
<HostedBrowserWebview
@@ -82,8 +81,6 @@ export function ElectronBrowserHost() {
threadRef={threadRef}
tabId={snapshot.tabId}
initialUrl={url}
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
zoomFactor={zoomFactor}
/>
);
})}
+22 -163
View File
@@ -1,22 +1,16 @@
"use client";
import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useShallow } from "zustand/react/shallow";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useRef } from "react";
import { previewBridge } from "~/components/preview/previewBridge";
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
import { cn } from "~/lib/utils";
import { useActiveBrowserRecordingTabId } from "./browserRecording";
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
import { browserViewportSettingKey } from "./browserViewportLayout";
import { reconcileLockedAspectRatio } from "./browserDeviceToolbarState";
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
import { useBrowserViewportResize } from "./useBrowserViewportResize";
interface ElectronWebview extends HTMLElement {
src: string;
@@ -24,7 +18,6 @@ interface ElectronWebview extends HTMLElement {
preload?: string;
webpreferences?: string;
getWebContentsId: () => number;
executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
}
declare global {
@@ -37,25 +30,13 @@ export function HostedBrowserWebview(props: {
readonly threadRef: ScopedThreadRef;
readonly tabId: string;
readonly initialUrl: string | null;
readonly viewport: PreviewViewportSetting;
readonly zoomFactor: number;
}) {
const { threadRef, tabId, initialUrl, viewport, zoomFactor } = props;
const { threadRef, tabId, initialUrl } = props;
const config = usePreviewWebviewConfig(threadRef.environmentId);
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
const initialSrcRef = useRef(initialUrl ?? "about:blank");
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
const wrapperRef = useRef<HTMLDivElement | null>(null);
const webviewRef = useRef<ElectronWebview | null>(null);
const [lockedAspectRatio, setLockedAspectRatio] = useState<number | null>(null);
const presentation = useBrowserSurfaceStore(
useShallow((state) => {
const current = state.byTabId[tabId];
return {
rect: resolveBrowserSurfacePanelRect(state.byTabId, tabId),
visible: current?.visible ?? false,
};
}),
);
const presentation = useBrowserSurfaceStore(useShallow((state) => state.byTabId[tabId] ?? null));
const recording = useActiveBrowserRecordingTabId() === tabId;
usePreviewBridge({ threadRef, tabId });
@@ -108,69 +89,10 @@ export function HostedBrowserWebview(props: {
};
}, [config, tabId]);
const active = presentation.visible && presentation.rect !== null;
const lastRect = presentation.rect;
const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
const viewportAspectRatio =
viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
useEffect(() => {
setLockedAspectRatio((current) => reconcileLockedAspectRatio(current, viewportAspectRatio));
}, [viewportAspectRatio]);
const hiddenSize =
viewport._tag !== "fill"
? {
width: viewport.width * normalizedZoomFactor,
height: viewport.height * normalizedZoomFactor,
}
: { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };
const containerSize = active && lastRect ? lastRect : hiddenSize;
const deviceToolbarVisible = active && viewport._tag !== "fill";
const {
activeDrag,
commitViewportChange,
effectiveViewport,
handleResizeKeyDown,
handleResizePointerDown,
layout,
} = useBrowserViewportResize({
tabId,
viewport,
zoomFactor,
containerSize,
deviceToolbarVisible,
aspectRatio: lockedAspectRatio,
});
const syncContentPresentation = useCallback(() => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
useBrowserSurfaceStore.getState().presentContent(tabId, {
x: layout.viewportX,
y: layout.viewportY,
width: layout.viewportWidth,
height: layout.viewportHeight,
scale: layout.viewportScale,
scrollLeft: wrapper.scrollLeft,
scrollTop: wrapper.scrollTop,
});
}, [layout, tabId]);
useEffect(() => {
const frameId = window.requestAnimationFrame(syncContentPresentation);
return () => window.cancelAnimationFrame(frameId);
}, [syncContentPresentation]);
useEffect(() => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
wrapper.scrollTo({ left: 0, top: 0 });
}, [tabId, viewport._tag, viewportHeight, viewportWidth]);
if (!config) return null;
const wrapperStyle =
const active = presentation?.visible === true && presentation.rect !== null;
const lastRect = presentation?.rect;
const style =
active && lastRect
? {
left: lastRect.x,
@@ -183,86 +105,23 @@ export function HostedBrowserWebview(props: {
: {
left: 0,
top: 0,
width: hiddenSize.width,
height: hiddenSize.height,
width: lastRect?.width ?? 1280,
height: lastRect?.height ?? 800,
zIndex: recording ? 0 : -1,
pointerEvents: "none" as const,
};
return (
<div
ref={wrapperRef}
className="fixed overflow-hidden bg-muted/35"
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
onScroll={syncContentPresentation}
data-preview-viewport={tabId}
>
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
{deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
<BrowserDeviceToolbar
setting={effectiveViewport}
width={Math.max(1, Math.round(containerSize.width))}
aspectRatio={lockedAspectRatio}
onAspectRatioChange={setLockedAspectRatio}
onChange={commitViewportChange}
/>
) : null}
<webview
ref={setWebviewRef}
src={initialSrc}
partition={config.partition}
webpreferences={config.webPreferences}
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
data-preview-tab={tabId}
data-preview-viewport-mode={effectiveViewport._tag}
data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
data-preview-css-width={
effectiveViewport._tag === "fill"
? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))
: effectiveViewport.width
}
data-preview-css-height={
effectiveViewport._tag === "fill"
? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))
: effectiveViewport.height
}
aria-hidden={active ? undefined : true}
className={cn(
"absolute flex overflow-hidden bg-background",
active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
)}
style={{
left: layout.viewportX,
top: layout.viewportY,
width: layout.viewportWidth / layout.viewportScale,
height: layout.viewportHeight / layout.viewportScale,
transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
transformOrigin: "top left",
}}
/>
{active && effectiveViewport._tag !== "fill" ? (
<>
<BrowserViewportResizeHandles
layout={layout}
activeDirection={activeDrag?.direction ?? null}
onPointerDown={handleResizePointerDown}
onKeyDown={handleResizeKeyDown}
/>
{activeDrag ? (
<div
className="pointer-events-none absolute z-40 -translate-x-1/2 rounded-md border border-border/80 bg-background/95 px-2 py-1 text-[11px] font-medium tabular-nums text-foreground shadow-md backdrop-blur-sm"
style={{
left: layout.viewportX + layout.viewportWidth / 2,
top: layout.viewportY + 10,
}}
aria-hidden="true"
>
{activeDrag.width} × {activeDrag.height}
</div>
) : null}
</>
) : null}
</div>
</div>
<webview
ref={setWebviewRef}
src={initialSrcRef.current}
partition={config.partition}
webpreferences={config.webPreferences}
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
data-preview-tab={tabId}
aria-hidden={active ? undefined : true}
className="fixed flex overflow-hidden bg-background"
style={style}
/>
);
}
@@ -1,18 +0,0 @@
import type { PreviewViewportSetting } from "@t3tools/contracts";
export function reconcileLockedAspectRatio(
current: number | null,
viewportAspectRatio: number | null,
): number | null {
return current === null || viewportAspectRatio === null ? null : viewportAspectRatio;
}
export async function commitViewportAndAspectRatio(
setting: PreviewViewportSetting,
aspectRatio: number | null,
onChange: (setting: PreviewViewportSetting) => Promise<void>,
onAspectRatioChange: (aspectRatio: number | null) => void,
): Promise<void> {
await onChange(setting);
onAspectRatioChange(aspectRatio);
}
+3 -8
View File
@@ -90,10 +90,6 @@ export function useActiveBrowserRecordingTabId(): string | null {
let active: ActiveRecording | null = null;
let unsubscribeFrames: (() => void) | null = null;
export function readActiveBrowserRecordingTabId(): string | null {
return active?.tabId ?? null;
}
const preferredMimeType = (): string => {
const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];
return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";
@@ -141,11 +137,10 @@ export async function startBrowserRecording(tabId: string): Promise<string> {
activeTabId: active.tabId,
});
}
const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
const recordingSize = surface?.content ?? surface?.rect;
const rect = useBrowserSurfaceStore.getState().byTabId[tabId]?.rect;
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, recordingSize?.width ?? 1280);
canvas.height = Math.max(1, recordingSize?.height ?? 800);
canvas.width = Math.max(1, rect?.width ?? 1280);
canvas.height = Math.max(1, rect?.height ?? 800);
const context = canvas.getContext("2d", { alpha: false });
if (!context) {
throw new BrowserRecordingCanvasUnavailableError({
@@ -1,11 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveBrowserRecordingStopTarget } from "./browserRecordingScope";
describe("resolveBrowserRecordingStopTarget", () => {
it("stops the active recording even after the requested tab changes", () => {
expect(resolveBrowserRecordingStopTarget("tab-a")).toBe("tab-a");
expect(resolveBrowserRecordingStopTarget("tab-b")).toBe("tab-b");
expect(resolveBrowserRecordingStopTarget(null)).toBeNull();
});
});
@@ -1,3 +0,0 @@
export function resolveBrowserRecordingStopTarget(activeTabId: string | null): string | null {
return activeTabId;
}
@@ -1,38 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
describe("browserSurfaceStore", () => {
it("tracks content dimensions for a browser that has never been visible", () => {
const tabId = "hidden-browser-surface-content-test";
useBrowserSurfaceStore.getState().presentContent(tabId, {
x: 0,
y: 0,
width: 393,
height: 852,
scale: 1,
scrollLeft: 0,
scrollTop: 0,
});
expect(useBrowserSurfaceStore.getState().byTabId[tabId]).toMatchObject({
rect: null,
visible: false,
content: { width: 393, height: 852 },
});
});
it("uses the live panel rect for a hidden background tab", () => {
const staleRect = { x: 0, y: 0, width: 500, height: 700 };
const liveRect = { x: 10, y: 20, width: 900, height: 640 };
expect(
resolveBrowserSurfacePanelRect(
{
hidden: { rect: staleRect, visible: false, content: null, updatedAt: 1 },
active: { rect: liveRect, visible: true, content: null, updatedAt: 2 },
},
"hidden",
),
).toEqual(liveRect);
});
});
+1 -69
View File
@@ -10,47 +10,15 @@ export interface BrowserSurfaceRect {
export interface BrowserSurfacePresentation {
readonly rect: BrowserSurfaceRect | null;
readonly visible: boolean;
readonly content: BrowserSurfaceContentPresentation | null;
readonly updatedAt: number;
}
export interface BrowserSurfaceContentPresentation {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly scale: number;
readonly scrollLeft: number;
readonly scrollTop: number;
}
interface BrowserSurfaceStoreState {
readonly byTabId: Record<string, BrowserSurfacePresentation>;
readonly present: (tabId: string, rect: BrowserSurfaceRect, visible: boolean) => void;
readonly presentContent: (tabId: string, content: BrowserSurfaceContentPresentation) => void;
readonly hide: (tabId: string) => void;
}
export function resolveBrowserSurfacePanelRect(
byTabId: Readonly<Record<string, BrowserSurfacePresentation>>,
tabId: string,
): BrowserSurfaceRect | null {
const current = byTabId[tabId];
if (current?.visible && current.rect) return current.rect;
let latestVisible: BrowserSurfacePresentation | undefined;
for (const presentation of Object.values(byTabId)) {
if (
presentation.visible &&
presentation.rect &&
(!latestVisible || presentation.updatedAt > latestVisible.updatedAt)
) {
latestVisible = presentation;
}
}
return latestVisible?.rect ?? current?.rect ?? null;
}
const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect): boolean =>
left !== null &&
left.x === right.x &&
@@ -67,43 +35,7 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
return {
byTabId: {
...state.byTabId,
[tabId]: { rect, visible, content: current?.content ?? null, updatedAt: Date.now() },
},
};
}),
presentContent: (tabId, content) =>
set((state) => {
const current = state.byTabId[tabId];
if (!current) {
return {
byTabId: {
...state.byTabId,
[tabId]: {
rect: null,
visible: false,
content,
updatedAt: Date.now(),
},
},
};
}
const previous = current.content;
if (
previous &&
previous.x === content.x &&
previous.y === content.y &&
previous.width === content.width &&
previous.height === content.height &&
previous.scale === content.scale &&
previous.scrollLeft === content.scrollLeft &&
previous.scrollTop === content.scrollTop
) {
return state;
}
return {
byTabId: {
...state.byTabId,
[tabId]: { ...current, content, updatedAt: Date.now() },
[tabId]: { rect, visible, updatedAt: Date.now() },
},
};
}),
@@ -1,112 +0,0 @@
import type { PreviewViewportSetting } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import {
BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
commitBrowserViewportChange,
subscribeBrowserViewportChange,
} from "./browserViewportActions";
describe("browserViewportActions", () => {
it("routes drag commits to the visible tab handler and cleans up exactly that handler", async () => {
const first = vi.fn(async () => undefined);
const second = vi.fn(async () => undefined);
const unsubscribeFirst = subscribeBrowserViewportChange("tab-1", first);
const unsubscribeSecond = subscribeBrowserViewportChange("tab-1", second);
unsubscribeFirst();
await commitBrowserViewportChange("tab-1", {
_tag: "freeform",
width: 900,
height: 700,
});
expect(first).not.toHaveBeenCalled();
expect(second).toHaveBeenCalledWith({ _tag: "freeform", width: 900, height: 700 });
unsubscribeSecond();
await expect(
commitBrowserViewportChange("tab-1", {
_tag: "freeform",
width: 800,
height: 600,
}),
).rejects.toThrow("No visible browser viewport handler");
});
it("commits viewport changes in order for each tab", async () => {
let releaseFirst: (() => void) | undefined;
let markFirstStarted: (() => void) | undefined;
const firstPending = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
markFirstStarted = resolve;
});
const calls: Array<number> = [];
const unsubscribe = subscribeBrowserViewportChange("tab-serial", async (setting) => {
if (setting._tag === "fill") return;
calls.push(setting.width);
if (setting.width === 800) {
markFirstStarted?.();
await firstPending;
}
});
const first = commitBrowserViewportChange("tab-serial", {
_tag: "freeform",
width: 800,
height: 600,
});
const second = commitBrowserViewportChange("tab-serial", {
_tag: "freeform",
width: 900,
height: 700,
});
await firstStarted;
expect(calls).toEqual([800]);
releaseFirst?.();
await Promise.all([first, second]);
expect(calls).toEqual([800, 900]);
unsubscribe();
});
it("does not let a timed-out handler overtake a newer viewport commit", async () => {
vi.useFakeTimers();
try {
let releaseFirst: (() => void) | undefined;
const delayed = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
const handler = vi.fn(async (_setting: PreviewViewportSetting): Promise<void> => undefined);
handler.mockImplementationOnce(() => delayed).mockResolvedValueOnce(undefined);
const unsubscribe = subscribeBrowserViewportChange("tab-timeout", handler);
const first = commitBrowserViewportChange("tab-timeout", {
_tag: "freeform",
width: 800,
height: 600,
});
const firstResult = expect(first).rejects.toThrow(
"Timed out committing the browser viewport for tab tab-timeout",
);
const second = commitBrowserViewportChange("tab-timeout", {
_tag: "freeform",
width: 900,
height: 700,
});
await vi.advanceTimersByTimeAsync(BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS);
await firstResult;
expect(handler).toHaveBeenCalledTimes(1);
releaseFirst?.();
await second;
expect(handler).toHaveBeenCalledTimes(2);
expect(handler.mock.calls[1]?.[0]).toMatchObject({ width: 900, height: 700 });
unsubscribe();
} finally {
vi.useRealTimers();
}
});
});
@@ -1,66 +0,0 @@
import type { PreviewViewportSetting } from "@t3tools/contracts";
type BrowserViewportHandler = (setting: PreviewViewportSetting) => Promise<void>;
export const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
export class BrowserViewportCommitTimeoutError extends Error {
override readonly name = "BrowserViewportCommitTimeoutError";
constructor(readonly tabId: string) {
super(`Timed out committing the browser viewport for tab ${tabId}`);
}
}
const handlers = new Map<string, BrowserViewportHandler>();
const commitTails = new Map<string, Promise<void>>();
const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_resolve, reject) => {
timeoutId = setTimeout(
() => reject(new BrowserViewportCommitTimeoutError(tabId)),
BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
);
});
return Promise.race([operation, timeout]).finally(() => {
if (timeoutId !== undefined) clearTimeout(timeoutId);
});
};
export function subscribeBrowserViewportChange(
tabId: string,
handler: BrowserViewportHandler,
): () => void {
handlers.set(tabId, handler);
return () => {
if (handlers.get(tabId) === handler) handlers.delete(tabId);
};
}
export function commitBrowserViewportChange(
tabId: string,
setting: PreviewViewportSetting,
): Promise<void> {
const previous = commitTails.get(tabId) ?? Promise.resolve();
const started = previous
.catch(() => undefined)
.then(() => {
const handler = handlers.get(tabId);
const operation = handler
? Promise.resolve().then(() => handler(setting))
: Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
return { operation };
});
// The queue follows the real handler lifetime, not the caller-facing timeout.
// A slow commit therefore cannot time out, release the queue, and overwrite a
// newer viewport after that newer request has already completed.
const execution = started.then(({ operation }) => operation);
const result = started.then(({ operation }) => runHandlerWithTimeout(tabId, operation));
commitTails.set(tabId, execution);
const clear = () => {
if (commitTails.get(tabId) === execution) commitTails.delete(tabId);
};
void execution.then(clear, clear);
return result;
}
@@ -1,165 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
resizeBrowserViewportFromRail,
resizeFreeformViewport,
resolveBrowserDeviceViewportLayout,
resolveBrowserViewportLayout,
resolveResponsiveBrowserViewportSize,
} from "./browserViewportLayout";
describe("resolveBrowserViewportLayout", () => {
it("fills the available surface in fill mode", () => {
expect(resolveBrowserViewportLayout({ width: 700, height: 500 }, { _tag: "fill" })).toEqual({
canvasWidth: 700,
canvasHeight: 500,
viewportX: 0,
viewportY: 0,
viewportWidth: 700,
viewportHeight: 500,
viewportScale: 1,
fillsPanel: true,
});
});
it("centers a smaller fixed viewport", () => {
expect(
resolveBrowserViewportLayout(
{ width: 700, height: 1000 },
{ _tag: "freeform", width: 393, height: 852 },
),
).toMatchObject({
canvasWidth: 700,
canvasHeight: 1000,
viewportX: 154,
viewportY: 74,
viewportWidth: 393,
viewportHeight: 852,
});
});
it("scales a larger fixed viewport down to fit without creating overflow", () => {
const layout = resolveBrowserViewportLayout(
{ width: 600, height: 700 },
{ _tag: "freeform", width: 1440, height: 900 },
);
expect(layout).toMatchObject({
canvasWidth: 600,
canvasHeight: 700,
viewportX: 0,
viewportY: 163,
viewportWidth: 600,
viewportHeight: 375,
});
expect(layout.viewportScale).toBeCloseTo(5 / 12);
});
it("keeps fixed dimensions in page CSS pixels when browser zoom changes", () => {
expect(
resolveBrowserViewportLayout(
{ width: 800, height: 700 },
{ _tag: "freeform", width: 400, height: 300 },
1.5,
),
).toMatchObject({
viewportX: 100,
viewportY: 125,
viewportWidth: 600,
viewportHeight: 450,
});
expect(resizeFreeformViewport({ width: 400, height: 300 }, { x: 150, y: 75 }, 1.5)).toEqual({
width: 500,
height: 350,
});
});
it("bounds freeform drag sizes and total render area", () => {
expect(resizeFreeformViewport({ width: 1024, height: 768 }, { x: -2000, y: -2000 })).toEqual({
width: 240,
height: 240,
});
const large = resizeFreeformViewport({ width: 1920, height: 1080 }, { x: 2000, y: 2000 });
expect(large.width * large.height).toBeLessThanOrEqual(3840 * 2160);
});
it("resizes only the axes controlled by each edge", () => {
expect(
resizeFreeformViewport({ width: 800, height: 600 }, { x: -100, y: 500 }, 1, "west"),
).toEqual({ width: 900, height: 600 });
expect(
resizeFreeformViewport({ width: 800, height: 600 }, { x: 500, y: 100 }, 1, "north"),
).toEqual({ width: 800, height: 500 });
expect(
resizeFreeformViewport({ width: 800, height: 600 }, { x: -100, y: -50 }, 1, "northwest"),
).toEqual({ width: 900, height: 650 });
});
it("preserves a locked aspect ratio from either axis", () => {
expect(
resizeFreeformViewport({ width: 800, height: 600 }, { x: 200, y: 0 }, 1, "east", 4 / 3),
).toEqual({ width: 1000, height: 750 });
expect(
resizeFreeformViewport({ width: 800, height: 600 }, { x: 0, y: 150 }, 1, "south", 4 / 3),
).toEqual({ width: 1000, height: 750 });
});
it("reserves persistent device-toolbar rails around the guest viewport", () => {
expect(
resolveBrowserDeviceViewportLayout(
{ width: 1200, height: 900 },
{ _tag: "freeform", width: 1180, height: 858 },
),
).toEqual({
canvasWidth: 1200,
canvasHeight: 900,
viewportX: 10,
viewportY: 32,
viewportWidth: 1180,
viewportHeight: 858,
viewportScale: 1,
fillsPanel: false,
});
});
it("captures the available framed area when responsive mode is enabled", () => {
expect(resolveResponsiveBrowserViewportSize({ width: 1200, height: 900 })).toEqual({
width: 1180,
height: 858,
});
expect(resolveResponsiveBrowserViewportSize({ width: 1200, height: 900 }, 2)).toEqual({
width: 590,
height: 429,
});
});
it("keeps the grabbed rail under the pointer across centered layout boundaries", () => {
const available = { width: 1120, height: 818 };
expect(
resizeBrowserViewportFromRail(
{ width: 1120, height: 818 },
{ x: -100, y: -50 },
available,
1,
"southeast",
),
).toEqual({ width: 920, height: 718 });
expect(
resizeBrowserViewportFromRail(
{ width: 800, height: 600 },
{ x: 300, y: 0 },
{ width: 1200, height: 800 },
1,
"east",
),
).toEqual({ width: 1300, height: 600 });
expect(
resizeBrowserViewportFromRail(
{ width: 560, height: 409 },
{ x: -100, y: 0 },
available,
2,
"east",
),
).toEqual({ width: 460, height: 409 });
});
});
@@ -1,286 +0,0 @@
import {
PREVIEW_VIEWPORT_MAX_AREA,
PREVIEW_VIEWPORT_MAX_DIMENSION,
PREVIEW_VIEWPORT_MIN_DIMENSION,
type PreviewViewportSetting,
type PreviewViewportSize,
} from "@t3tools/contracts";
export interface BrowserViewportLayout {
readonly canvasWidth: number;
readonly canvasHeight: number;
readonly viewportX: number;
readonly viewportY: number;
/** Visible footprint inside the preview panel after fit-to-panel scaling. */
readonly viewportWidth: number;
readonly viewportHeight: number;
/** Presentation-only scale; the guest keeps its requested CSS viewport. */
readonly viewportScale: number;
readonly fillsPanel: boolean;
}
export const BROWSER_DEVICE_TOOLBAR_HEIGHT = 32;
export const BROWSER_VIEWPORT_RESIZE_RAIL_SIZE = 10;
export type BrowserViewportResizeDirection =
| "north"
| "northeast"
| "east"
| "southeast"
| "south"
| "southwest"
| "west"
| "northwest";
export const browserViewportSettingKey = (setting: PreviewViewportSetting): string =>
setting._tag === "fill"
? "fill"
: `${setting._tag}:${setting.width}:${setting.height}:${setting._tag === "preset" ? setting.presetId : ""}`;
const normalizeZoomFactor = (zoomFactor: number): number =>
Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
export function resolveBrowserDeviceViewportArea(container: {
readonly width: number;
readonly height: number;
}): PreviewViewportSize {
return {
width: Math.max(1, container.width - BROWSER_VIEWPORT_RESIZE_RAIL_SIZE * 2),
height: Math.max(
1,
container.height - BROWSER_DEVICE_TOOLBAR_HEIGHT - BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
),
};
}
export function resolveBrowserViewportLayout(
container: { readonly width: number; readonly height: number },
setting: PreviewViewportSetting,
zoomFactor = 1,
): BrowserViewportLayout {
const containerWidth = Math.max(1, Math.round(container.width));
const containerHeight = Math.max(1, Math.round(container.height));
if (setting._tag === "fill") {
return {
canvasWidth: containerWidth,
canvasHeight: containerHeight,
viewportX: 0,
viewportY: 0,
viewportWidth: containerWidth,
viewportHeight: containerHeight,
viewportScale: 1,
fillsPanel: true,
};
}
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
const renderedWidth = setting.width * normalizedZoomFactor;
const renderedHeight = setting.height * normalizedZoomFactor;
const viewportScale = Math.min(
1,
containerWidth / renderedWidth,
containerHeight / renderedHeight,
);
const viewportWidth = renderedWidth * viewportScale;
const viewportHeight = renderedHeight * viewportScale;
return {
canvasWidth: containerWidth,
canvasHeight: containerHeight,
viewportX: Math.max(0, Math.round((containerWidth - viewportWidth) / 2)),
viewportY: Math.max(0, Math.round((containerHeight - viewportHeight) / 2)),
viewportWidth,
viewportHeight,
viewportScale,
fillsPanel: false,
};
}
export function resolveBrowserDeviceViewportLayout(
container: { readonly width: number; readonly height: number },
setting: Exclude<PreviewViewportSetting, { readonly _tag: "fill" }>,
zoomFactor = 1,
): BrowserViewportLayout {
const layout = resolveBrowserViewportLayout(
resolveBrowserDeviceViewportArea(container),
setting,
zoomFactor,
);
return {
...layout,
canvasWidth: Math.max(1, Math.round(container.width)),
canvasHeight: Math.max(1, Math.round(container.height)),
viewportX: layout.viewportX + BROWSER_VIEWPORT_RESIZE_RAIL_SIZE,
viewportY: layout.viewportY + BROWSER_DEVICE_TOOLBAR_HEIGHT,
};
}
const clampViewportDimension = (value: number): number =>
Math.min(PREVIEW_VIEWPORT_MAX_DIMENSION, Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, value));
const validAspectRatio = (aspectRatio: number | undefined): aspectRatio is number =>
aspectRatio !== undefined && Number.isFinite(aspectRatio) && aspectRatio > 0;
function resizeAtAspectRatio(
desired: number,
aspectRatio: number,
primaryAxis: "width" | "height",
): PreviewViewportSize {
if (primaryAxis === "width") {
const minimum = Math.ceil(
Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, PREVIEW_VIEWPORT_MIN_DIMENSION * aspectRatio),
);
const maximum = Math.floor(
Math.min(
PREVIEW_VIEWPORT_MAX_DIMENSION,
PREVIEW_VIEWPORT_MAX_DIMENSION * aspectRatio,
Math.sqrt(PREVIEW_VIEWPORT_MAX_AREA * aspectRatio),
),
);
let width = Math.min(maximum, Math.max(minimum, Math.round(desired)));
let height = Math.round(width / aspectRatio);
while (width * height > PREVIEW_VIEWPORT_MAX_AREA && width > minimum) {
width -= 1;
height = Math.round(width / aspectRatio);
}
return { width, height };
}
const minimum = Math.ceil(
Math.max(PREVIEW_VIEWPORT_MIN_DIMENSION, PREVIEW_VIEWPORT_MIN_DIMENSION / aspectRatio),
);
const maximum = Math.floor(
Math.min(
PREVIEW_VIEWPORT_MAX_DIMENSION,
PREVIEW_VIEWPORT_MAX_DIMENSION / aspectRatio,
Math.sqrt(PREVIEW_VIEWPORT_MAX_AREA / aspectRatio),
),
);
let height = Math.min(maximum, Math.max(minimum, Math.round(desired)));
let width = Math.round(height * aspectRatio);
while (width * height > PREVIEW_VIEWPORT_MAX_AREA && height > minimum) {
height -= 1;
width = Math.round(height * aspectRatio);
}
return { width, height };
}
export function resizeFreeformViewport(
start: PreviewViewportSize,
delta: { readonly x: number; readonly y: number },
zoomFactor = 1,
direction: BrowserViewportResizeDirection = "southeast",
aspectRatio?: number,
): PreviewViewportSize {
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
const horizontalDelta = direction.includes("east")
? delta.x
: direction.includes("west")
? -delta.x
: 0;
const verticalDelta = direction.includes("south")
? delta.y
: direction.includes("north")
? -delta.y
: 0;
const desiredWidth = start.width + horizontalDelta / normalizedZoomFactor;
const desiredHeight = start.height + verticalDelta / normalizedZoomFactor;
if (validAspectRatio(aspectRatio)) {
const controlsWidth = horizontalDelta !== 0 || direction === "east" || direction === "west";
const controlsHeight = verticalDelta !== 0 || direction === "north" || direction === "south";
const primaryAxis =
controlsWidth && !controlsHeight
? "width"
: controlsHeight && !controlsWidth
? "height"
: Math.abs(desiredWidth - start.width) / start.width >=
Math.abs(desiredHeight - start.height) / start.height
? "width"
: "height";
return resizeAtAspectRatio(
primaryAxis === "width" ? desiredWidth : desiredHeight,
aspectRatio,
primaryAxis,
);
}
let width = clampViewportDimension(Math.round(desiredWidth));
let height = clampViewportDimension(Math.round(desiredHeight));
if (width * height <= PREVIEW_VIEWPORT_MAX_AREA) return { width, height };
if (Math.abs(horizontalDelta) >= Math.abs(verticalDelta)) {
width = Math.max(
PREVIEW_VIEWPORT_MIN_DIMENSION,
Math.floor(PREVIEW_VIEWPORT_MAX_AREA / height),
);
} else {
height = Math.max(
PREVIEW_VIEWPORT_MIN_DIMENSION,
Math.floor(PREVIEW_VIEWPORT_MAX_AREA / width),
);
}
return { width, height };
}
const resizeFromEndRail = (start: number, pointerDelta: number, available: number): number => {
const startEdge = start < available ? (available + start) / 2 : start;
const targetEdge = startEdge + pointerDelta;
return targetEdge <= available ? targetEdge * 2 - available : targetEdge;
};
const resizeFromStartRail = (start: number, pointerDelta: number, available: number): number => {
if (start > available) {
const distanceToFit = start - available;
return pointerDelta <= distanceToFit
? start - pointerDelta
: available - (pointerDelta - distanceToFit) * 2;
}
const targetEdge = (available - start) / 2 + pointerDelta;
return targetEdge >= 0 ? available - targetEdge * 2 : available - targetEdge;
};
export function resizeBrowserViewportFromRail(
start: PreviewViewportSize,
pointerDelta: { readonly x: number; readonly y: number },
available: PreviewViewportSize,
zoomFactor = 1,
direction: BrowserViewportResizeDirection = "southeast",
aspectRatio?: number,
): PreviewViewportSize {
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
const startWidth = start.width * normalizedZoomFactor;
const startHeight = start.height * normalizedZoomFactor;
const desiredWidth = direction.includes("east")
? resizeFromEndRail(startWidth, pointerDelta.x, available.width)
: direction.includes("west")
? resizeFromStartRail(startWidth, pointerDelta.x, available.width)
: startWidth;
const desiredHeight = direction.includes("south")
? resizeFromEndRail(startHeight, pointerDelta.y, available.height)
: direction.includes("north")
? resizeFromStartRail(startHeight, pointerDelta.y, available.height)
: startHeight;
const widthDelta = desiredWidth - startWidth;
const heightDelta = desiredHeight - startHeight;
return resizeFreeformViewport(
start,
{
x: direction.includes("west") ? -widthDelta : widthDelta,
y: direction.includes("north") ? -heightDelta : heightDelta,
},
normalizedZoomFactor,
direction,
aspectRatio,
);
}
export function resolveResponsiveBrowserViewportSize(
container: { readonly width: number; readonly height: number },
zoomFactor = 1,
): PreviewViewportSize {
const area = resolveBrowserDeviceViewportArea(container);
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
return resizeFreeformViewport(
{
width: area.width / normalizedZoomFactor,
height: area.height / normalizedZoomFactor,
},
{ x: 0, y: 0 },
);
}
@@ -1,260 +0,0 @@
"use client";
import type { PreviewViewportSetting, PreviewViewportSize } from "@t3tools/contracts";
import {
useCallback,
useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
import { commitBrowserViewportChange } from "./browserViewportActions";
import {
browserViewportSettingKey,
resizeBrowserViewportFromRail,
resizeFreeformViewport,
resolveBrowserDeviceViewportArea,
resolveBrowserDeviceViewportLayout,
resolveBrowserViewportLayout,
type BrowserViewportResizeDirection,
} from "./browserViewportLayout";
interface ViewportDrag extends PreviewViewportSize {
readonly sourceKey: string;
readonly direction: BrowserViewportResizeDirection;
}
const KEYBOARD_RESIZE_COMMIT_DELAY_MS = 150;
export function useBrowserViewportResize(options: {
readonly tabId: string;
readonly viewport: PreviewViewportSetting;
readonly zoomFactor: number;
readonly containerSize: PreviewViewportSize;
readonly deviceToolbarVisible: boolean;
readonly aspectRatio: number | null;
}) {
const { tabId, viewport, zoomFactor, containerSize, deviceToolbarVisible, aspectRatio } = options;
const dragCleanupRef = useRef<(() => void) | null>(null);
const dragVersionRef = useRef(0);
const keyboardCommitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const keyboardViewportRef = useRef<ViewportDrag | null>(null);
const [dragViewport, setDragViewport] = useState<ViewportDrag | null>(null);
const sourceViewportKey = browserViewportSettingKey(viewport);
const sourceViewportKeyRef = useRef(sourceViewportKey);
sourceViewportKeyRef.current = sourceViewportKey;
const activeDrag = dragViewport?.sourceKey === sourceViewportKey ? dragViewport : null;
const effectiveViewport = activeDrag
? ({
_tag: "freeform",
width: activeDrag.width,
height: activeDrag.height,
} as const satisfies PreviewViewportSetting)
: viewport;
const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
const viewportContainerSize = deviceToolbarVisible
? resolveBrowserDeviceViewportArea(containerSize)
: containerSize;
const layout =
deviceToolbarVisible && effectiveViewport._tag !== "fill"
? resolveBrowserDeviceViewportLayout(containerSize, effectiveViewport, zoomFactor)
: resolveBrowserViewportLayout(containerSize, effectiveViewport, zoomFactor);
useEffect(
() => () => {
dragVersionRef.current += 1;
dragCleanupRef.current?.();
if (keyboardCommitTimerRef.current !== null) {
clearTimeout(keyboardCommitTimerRef.current);
}
keyboardCommitTimerRef.current = null;
keyboardViewportRef.current = null;
},
[],
);
useEffect(() => {
const pending = keyboardViewportRef.current;
if (!pending || pending.sourceKey === sourceViewportKey) return;
if (keyboardCommitTimerRef.current !== null) {
clearTimeout(keyboardCommitTimerRef.current);
keyboardCommitTimerRef.current = null;
}
keyboardViewportRef.current = null;
}, [sourceViewportKey]);
const commitViewportChange = useCallback(
(next: PreviewViewportSetting) => {
dragVersionRef.current += 1;
dragCleanupRef.current?.();
if (keyboardCommitTimerRef.current !== null) {
clearTimeout(keyboardCommitTimerRef.current);
keyboardCommitTimerRef.current = null;
}
keyboardViewportRef.current = null;
setDragViewport(null);
return commitBrowserViewportChange(tabId, next);
},
[tabId],
);
const clearDrag = () => setDragViewport(null);
const commitDrag = (next: PreviewViewportSetting) => {
const version = ++dragVersionRef.current;
const clearIfCurrent = () => {
if (dragVersionRef.current === version) clearDrag();
};
void commitBrowserViewportChange(tabId, next).then(clearIfCurrent, clearIfCurrent);
};
const handleResizeKeyDown = (
direction: BrowserViewportResizeDirection,
event: ReactKeyboardEvent<HTMLButtonElement>,
) => {
if (effectiveViewport._tag === "fill") return;
const controlsWidth = direction.includes("east") || direction.includes("west");
const controlsHeight = direction.includes("north") || direction.includes("south");
const step = (event.shiftKey ? 50 : 10) * normalizedZoomFactor;
const delta =
event.key === "ArrowLeft" && controlsWidth
? { x: -step, y: 0 }
: event.key === "ArrowRight" && controlsWidth
? { x: step, y: 0 }
: event.key === "ArrowUp" && controlsHeight
? { x: 0, y: -step }
: event.key === "ArrowDown" && controlsHeight
? { x: 0, y: step }
: null;
if (!delta) return;
event.preventDefault();
event.stopPropagation();
const pending = keyboardViewportRef.current;
const base = pending?.sourceKey === sourceViewportKey ? pending : effectiveViewport;
const next = resizeFreeformViewport(
base,
delta,
zoomFactor,
direction,
aspectRatio ?? undefined,
);
if (next.width === base.width && next.height === base.height) return;
const keyboardViewport = { sourceKey: sourceViewportKey, ...next, direction };
keyboardViewportRef.current = keyboardViewport;
setDragViewport(keyboardViewport);
if (keyboardCommitTimerRef.current !== null) {
clearTimeout(keyboardCommitTimerRef.current);
}
keyboardCommitTimerRef.current = setTimeout(() => {
keyboardCommitTimerRef.current = null;
const latest = keyboardViewportRef.current;
if (!latest || latest.sourceKey !== sourceViewportKeyRef.current) return;
keyboardViewportRef.current = null;
commitDrag({ _tag: "freeform", width: latest.width, height: latest.height });
}, KEYBOARD_RESIZE_COMMIT_DELAY_MS);
};
const handleResizePointerDown = (
direction: BrowserViewportResizeDirection,
event: ReactPointerEvent<HTMLButtonElement>,
) => {
if (effectiveViewport._tag === "fill") return;
event.preventDefault();
event.stopPropagation();
if (keyboardCommitTimerRef.current !== null) {
clearTimeout(keyboardCommitTimerRef.current);
keyboardCommitTimerRef.current = null;
}
keyboardViewportRef.current = null;
dragCleanupRef.current?.();
dragVersionRef.current += 1;
const pointerId = event.pointerId;
const target = event.currentTarget;
const startX = event.clientX;
const startY = event.clientY;
const startWidth = effectiveViewport.width;
const startHeight = effectiveViewport.height;
const dragZoomFactor = normalizedZoomFactor * layout.viewportScale;
let latest = { width: startWidth, height: startHeight };
setDragViewport({
sourceKey: sourceViewportKey,
width: startWidth,
height: startHeight,
direction,
});
try {
target.setPointerCapture(pointerId);
} catch {
// Window listeners below keep the drag functional when capture is unavailable.
}
const sourceChanged = () => sourceViewportKeyRef.current !== sourceViewportKey;
const move = (moveEvent: PointerEvent) => {
if (moveEvent.pointerId !== pointerId) return;
if (sourceChanged()) {
cleanup();
dragVersionRef.current += 1;
clearDrag();
return;
}
moveEvent.preventDefault();
const { width, height } = resizeBrowserViewportFromRail(
{ width: startWidth, height: startHeight },
{
x: moveEvent.clientX - startX,
y: moveEvent.clientY - startY,
},
viewportContainerSize,
dragZoomFactor,
direction,
aspectRatio ?? undefined,
);
latest = { width, height };
setDragViewport({ sourceKey: sourceViewportKey, width, height, direction });
};
function cleanup() {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", finish);
window.removeEventListener("pointercancel", cancel);
dragCleanupRef.current = null;
try {
target.releasePointerCapture(pointerId);
} catch {
// The browser may already have released capture on pointerup.
}
}
function finish(upEvent: PointerEvent) {
if (upEvent.pointerId !== pointerId) return;
cleanup();
if (sourceChanged() || (latest.width === startWidth && latest.height === startHeight)) {
clearDrag();
return;
}
commitDrag({
_tag: "freeform",
width: latest.width,
height: latest.height,
});
}
function cancel(cancelEvent: PointerEvent) {
if (cancelEvent.pointerId !== pointerId) return;
cleanup();
dragVersionRef.current += 1;
clearDrag();
}
dragCleanupRef.current = cleanup;
window.addEventListener("pointermove", move, { passive: false });
window.addEventListener("pointerup", finish);
window.addEventListener("pointercancel", cancel);
};
return {
activeDrag,
commitViewportChange,
effectiveViewport,
handleResizeKeyDown,
handleResizePointerDown,
layout,
};
}
@@ -6,7 +6,6 @@ import {
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildThreadTurnInterruptInput,
createLocalDispatchSnapshot,
deriveComposerSendState,
getStartedThreadModelChangeBlockReason,
@@ -70,30 +69,6 @@ const readySession = {
updatedAt: "2026-03-29T00:00:10.000Z",
};
describe("buildThreadTurnInterruptInput", () => {
it("targets the session's active running turn", () => {
const activeTurnId = TurnId.make("turn-running");
expect(
buildThreadTurnInterruptInput(
makeThread({
session: {
...readySession,
status: "running",
activeTurnId,
},
}),
),
).toEqual({ threadId, turnId: activeTurnId });
});
it("omits a turn id when the session is not running", () => {
expect(buildThreadTurnInterruptInput(makeThread({ session: readySession }))).toEqual({
threadId,
});
});
});
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
const state = deriveComposerSendState({
-11
View File
@@ -74,17 +74,6 @@ export function shouldWriteThreadErrorToCurrentServerThread(input: {
);
}
export function buildThreadTurnInterruptInput(thread: Pick<Thread, "id" | "session">): {
threadId: ThreadId;
turnId?: TurnId;
} {
const runningTurnId = thread.session?.status === "running" ? thread.session.activeTurnId : null;
return {
threadId: thread.id,
...(runningTurnId !== null ? { turnId: runningTurnId } : {}),
};
}
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<string>;
openThreadIds: ReadonlyArray<string>;
+7 -7
View File
@@ -129,6 +129,7 @@ import { addBrowserSurface } from "./preview/addBrowserSurface";
import { closePreviewSession } from "./preview/closePreviewSession";
import { subscribePreviewAction } from "./preview/previewActionBus";
import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic";
import { PreviewAutomationOwner } from "./preview/PreviewAutomationOwner";
import { RightPanelTabs } from "./RightPanelTabs";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
@@ -214,7 +215,6 @@ import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildThreadTurnInterruptInput,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
@@ -3942,7 +3942,9 @@ function ChatViewContent(props: ChatViewProps) {
if (!activeThread) return;
const result = await interruptThreadTurn({
environmentId,
input: buildThreadTurnInterruptInput(activeThread),
input: {
threadId: activeThread.id,
},
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
@@ -4702,6 +4704,9 @@ function ChatViewContent(props: ChatViewProps) {
return (
<div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">
{isElectron && activeThreadRef ? (
<PreviewAutomationOwner threadRef={activeThreadRef} visible={previewPanelOpen} />
) : null}
{rightPanelOpen && !shouldUsePlanSidebarSheet ? panelLayoutControls : null}
<div
className={cn(
@@ -4770,11 +4775,6 @@ function ChatViewContent(props: ChatViewProps) {
listRef={legendListRef}
timelineEntries={timelineEntries}
latestTurn={activeLatestTurn}
runningTurnId={
activeThread.session?.status === "running"
? activeThread.session.activeTurnId
: null
}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
activeThreadEnvironmentId={activeThread.environmentId}
routeThreadKey={routeThreadKey}
@@ -894,16 +894,20 @@ interface ComposerPromptEditorProps {
editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
}
type ComposerCommandKey = "ArrowDown" | "ArrowUp" | "Enter" | "Tab";
type ComposerCommandKeyHandler = (key: ComposerCommandKey, event: KeyboardEvent) => boolean;
function ComposerCommandKeyPlugin(props: {
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
) => boolean;
}) {
const [editor] = useLexicalComposerContext();
function useComposerCommandKeyBindings(
editor: ReturnType<typeof useLexicalComposerContext>[0],
onCommandKeyDown: ComposerCommandKeyHandler | undefined,
) {
const handleCommandKeyDown = useEffectEvent(
(key: ComposerCommandKey, event: KeyboardEvent | null): boolean => {
if (!onCommandKeyDown || !event) {
useEffect(() => {
const handleCommand = (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent | null,
): boolean => {
if (!props.onCommandKeyDown || !event) {
return false;
}
@@ -912,34 +916,32 @@ function useComposerCommandKeyBindings(
return true;
}
const handled = onCommandKeyDown(key, event);
const handled = props.onCommandKeyDown(key, event);
if (handled) {
event.preventDefault();
event.stopPropagation();
}
return handled;
},
);
};
useEffect(() => {
const unregisterArrowDown = editor.registerCommand(
KEY_ARROW_DOWN_COMMAND,
(event) => handleCommandKeyDown("ArrowDown", event),
(event) => handleCommand("ArrowDown", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterArrowUp = editor.registerCommand(
KEY_ARROW_UP_COMMAND,
(event) => handleCommandKeyDown("ArrowUp", event),
(event) => handleCommand("ArrowUp", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterEnter = editor.registerCommand(
KEY_ENTER_COMMAND,
(event) => handleCommandKeyDown("Enter", event),
(event) => handleCommand("Enter", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterTab = editor.registerCommand(
KEY_TAB_COMMAND,
(event) => handleCommandKeyDown("Tab", event),
(event) => handleCommand("Tab", event),
COMMAND_PRIORITY_HIGH,
);
@@ -949,7 +951,9 @@ function useComposerCommandKeyBindings(
unregisterEnter();
unregisterTab();
};
}, [editor, handleCommandKeyDown]);
}, [editor, props]);
return null;
}
function ComposerInlineTokenArrowPlugin() {
@@ -1394,7 +1398,6 @@ function ComposerPromptEditorInner({
editorRef,
}: ComposerPromptEditorProps) {
const [editor] = useLexicalComposerContext();
useComposerCommandKeyBindings(editor, onCommandKeyDown);
const onChangeRef = useRef(onChange);
const initialCursor = clampCollapsedComposerCursor(value, cursor);
const terminalContextsSignature = terminalContextSignature(terminalContexts);
@@ -1626,6 +1629,7 @@ function ComposerPromptEditorInner({
ErrorBoundary={LexicalErrorBoundary}
/>
<OnChangePlugin onChange={handleEditorChange} />
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} skills={skills} />
<ComposerInlineTokenArrowPlugin />
<ComposerInlineTokenSelectionNormalizePlugin />
@@ -20,7 +20,6 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
@@ -347,7 +346,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
"workspace-topbar gap-1 pl-2",
props.mode === "inline" ? "pr-28" : "pr-3",
ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
data-right-panel-tabbar
>
@@ -794,67 +794,6 @@ describe("deriveMessagesTimelineRows", () => {
]);
});
it("does not fold the session's running turn when latestTurn regresses", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "previous-work-entry",
kind: "work",
createdAt: "2026-01-01T00:00:05Z",
entry: {
id: "previous-work",
createdAt: "2026-01-01T00:00:05Z",
turnId: "turn-1" as never,
label: "Read files",
tone: "tool" as const,
},
},
{
id: "user-followup-entry",
kind: "message",
createdAt: "2026-01-01T00:01:00Z",
message: {
id: "user-followup" as never,
role: "user",
text: "continue",
turnId: null,
createdAt: "2026-01-01T00:01:00Z",
updatedAt: "2026-01-01T00:01:00Z",
streaming: false,
},
},
{
id: "running-work-entry",
kind: "work",
createdAt: "2026-01-01T00:01:05Z",
entry: {
id: "running-work",
createdAt: "2026-01-01T00:01:05Z",
turnId: "turn-2" as never,
label: "Searched files",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "completed",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:25Z",
},
runningTurnId: "turn-2" as never,
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:01:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.turnId)).toEqual([
"turn-1",
]);
expect(rows.map((row) => row.id)).toContain("running-work-entry");
});
it("only shows assistant metadata on the terminal assistant message", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
@@ -149,20 +149,13 @@ interface TurnFold {
}
/**
* The session's running turn is authoritative when latestTurn briefly lags or
* regresses behind it. Otherwise, the latest turn counts as unsettled while it
* is still running (or has not recorded a completion). This is deliberately
* keyed on turn lifecycle rather than transient working state: right after the
* user sends a message, the previous turn is still the "active" one until the
* server creates the new turn, and folding must not flicker through that window.
* The latest turn counts as unsettled while it is still running (or has not
* recorded a completion). This is deliberately keyed on the turn's own
* lifecycle rather than transient working state: right after the user sends
* a message, the previous turn is still the "active" one until the server
* creates the new turn, and folding must not flicker through that window.
*/
function deriveUnsettledTurnId(
latestTurn: TimelineLatestTurn | null,
runningTurnId: TurnId | null,
): TurnId | null {
if (runningTurnId !== null) {
return runningTurnId;
}
function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null {
if (!latestTurn) {
return null;
}
@@ -298,7 +291,6 @@ function deriveTurnFolds(input: {
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
latestTurn?: TimelineLatestTurn | null;
runningTurnId?: TurnId | null;
expandedTurnIds?: ReadonlySet<TurnId>;
isWorking: boolean;
activeTurnStartedAt: string | null;
@@ -310,10 +302,7 @@ export function deriveMessagesTimelineRows(input: {
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
const unsettledTurnId = deriveUnsettledTurnId(
input.latestTurn ?? null,
input.runningTurnId ?? null,
);
const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null);
const foldsByAnchorEntryId = deriveTurnFolds({
timelineEntries: input.timelineEntries,
terminalAssistantMessageIds,
@@ -109,7 +109,6 @@ function buildProps() {
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
latestTurn: null,
runningTurnId: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
@@ -153,7 +153,6 @@ interface MessagesTimelineProps {
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
latestTurn: TimelineLatestTurn | null;
runningTurnId: TurnId | null;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
routeThreadKey: string;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
@@ -183,7 +182,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
listRef,
timelineEntries,
latestTurn,
runningTurnId,
turnDiffSummaryByAssistantMessageId,
routeThreadKey,
onOpenTurnDiff,
@@ -274,7 +272,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
deriveMessagesTimelineRows({
timelineEntries,
latestTurn,
runningTurnId,
expandedTurnIds,
isWorking,
activeTurnStartedAt,
@@ -284,7 +281,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
[
timelineEntries,
latestTurn,
runningTurnId,
expandedTurnIds,
isWorking,
activeTurnStartedAt,
@@ -5,7 +5,6 @@ import { MousePointer2 } from "lucide-react";
import { useEffect, useState } from "react";
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
import { agentBrowserCursorOpacity, type BrowserController } from "./agentBrowserCursorLogic";
@@ -18,7 +17,6 @@ export function AgentBrowserCursor(props: {
}) {
const { tabId, zoomFactor, controller } = props;
const event = useBrowserPointerStore((state) => state.byTabId[tabId] ?? null);
const content = useBrowserSurfaceStore((state) => state.byTabId[tabId]?.content ?? null);
if (!event) return null;
@@ -26,7 +24,6 @@ export function AgentBrowserCursor(props: {
<AgentBrowserCursorEvent
key={event.sequence}
event={event}
content={content}
zoomFactor={zoomFactor}
controller={controller}
/>
@@ -35,17 +32,10 @@ export function AgentBrowserCursor(props: {
function AgentBrowserCursorEvent(props: {
readonly event: DesktopPreviewPointerEvent;
readonly content: {
readonly x: number;
readonly y: number;
readonly scale: number;
readonly scrollLeft: number;
readonly scrollTop: number;
} | null;
readonly zoomFactor: number;
readonly controller: BrowserController;
}) {
const { event, content, zoomFactor, controller } = props;
const { event, zoomFactor, controller } = props;
const [active, setActive] = useState(true);
useEffect(() => {
@@ -58,7 +48,7 @@ function AgentBrowserCursorEvent(props: {
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 * (content?.scale ?? 1) + (content?.x ?? 0) - (content?.scrollLeft ?? 0)}px, ${event.y * zoomFactor * (content?.scale ?? 1) + (content?.y ?? 0) - (content?.scrollTop ?? 0)}px, 0)`,
transform: `translate3d(${event.x * zoomFactor}px, ${event.y * zoomFactor}px, 0)`,
}}
aria-hidden="true"
data-agent-browser-cursor
@@ -1,576 +0,0 @@
"use client";
import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
FILL_PREVIEW_VIEWPORT,
PREVIEW_AUTOMATION_OPERATIONS,
type EnvironmentId,
type PreviewAutomationNavigateInput,
type PreviewAutomationOpenInput,
type PreviewAutomationResizeInput,
type PreviewAutomationResizeResult,
type PreviewAutomationHost as PreviewAutomationHostState,
type PreviewAutomationRequest,
type PreviewAutomationStatus,
type PreviewRenderedViewportSize,
type PreviewViewportSetting,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { resolvePreviewViewport } from "@t3tools/shared/previewViewport";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { Atom } from "effect/unstable/reactivity";
import {
applyPreviewServerSnapshot,
readThreadPreviewState,
reconcilePreviewServerSessions,
updatePreviewServerSnapshot,
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
import {
readActiveBrowserRecordingTabId,
startBrowserRecording,
stopBrowserRecording,
} from "~/browser/browserRecording";
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
import { isElectron } from "~/env";
import { useEnvironments } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
import {
PreviewAutomationNavigationTimeoutError,
PreviewAutomationOperationError,
PreviewAutomationOverlayTimeoutError,
PreviewAutomationRecordingNotActiveError,
PreviewAutomationTargetUnavailableError,
PreviewAutomationViewportTimeoutError,
} from "./previewAutomationErrors";
import { previewAutomationOpenNeedsOverlay } from "./previewAutomationOpenReadiness";
import { createPreviewAutomationRequestConsumerAtom } from "./previewAutomationRequestConsumer";
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
import {
needsPreviewAutomationSessionSync,
resolvePreviewAutomationTarget,
} from "./previewAutomationTarget";
import { isPreviewViewportReady } from "./previewViewportReadiness";
const waitForDesktopOverlay = async (
threadRef: ScopedThreadRef,
requestId: string,
tabId: string,
timeoutMs: number,
): Promise<void> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
const state = readThreadPreviewState(threadRef);
if (state.desktopByTabId[tabId] && previewBridge) {
const status = await previewBridge.automation.status(tabId);
if (status.available) return;
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
throw new PreviewAutomationOverlayTimeoutError({
requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
timeoutMs,
});
};
const waitForNavigationReadiness = async (
threadRef: ScopedThreadRef,
requestId: string,
tabId: string,
readiness: PreviewAutomationNavigateInput["readiness"],
timeoutMs: number,
): Promise<void> => {
const targetReadiness = readiness ?? "load";
if (!previewBridge || targetReadiness === "none") return;
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
if (targetReadiness === "domContentLoaded") {
const readyState = await previewBridge.automation.evaluate(tabId, {
expression: "document.readyState",
});
if (readyState === "interactive" || readyState === "complete") return;
} else {
const status = await previewBridge.automation.status(tabId);
if (!status.loading) return;
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
throw new PreviewAutomationNavigationTimeoutError({
requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId,
readiness: targetReadiness,
timeoutMs,
});
};
interface ExecutablePreviewWebview extends Element {
readonly executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
}
const findPreviewWebview = (tabId: string): ExecutablePreviewWebview | null =>
Array.from(document.querySelectorAll<ExecutablePreviewWebview>("webview[data-preview-tab]")).find(
(candidate) => candidate.getAttribute("data-preview-tab") === tabId,
) ?? null;
const readWebviewViewport = async (
webview: ExecutablePreviewWebview,
): Promise<PreviewRenderedViewportSize | null> => {
const value = await webview.executeJavaScript(
"({ width: window.innerWidth, height: window.innerHeight })",
);
if (typeof value !== "object" || value === null) return null;
const { width, height } = value as { readonly width?: unknown; readonly height?: unknown };
return typeof width === "number" &&
Number.isInteger(width) &&
width > 0 &&
typeof height === "number" &&
Number.isInteger(height) &&
height > 0
? { width, height }
: null;
};
const readRenderedViewport = async (tabId: string): Promise<PreviewRenderedViewportSize | null> => {
const webview = findPreviewWebview(tabId);
if (!webview) return null;
return await readWebviewViewport(webview);
};
const readDeclaredViewport = (
webview: ExecutablePreviewWebview | null,
): PreviewRenderedViewportSize | null => {
const width = Number(webview?.getAttribute("data-preview-css-width"));
const height = Number(webview?.getAttribute("data-preview-css-height"));
return Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0
? { width, height }
: null;
};
const waitForRenderedViewport = async (
tabId: string,
setting: PreviewViewportSetting,
timeoutMs: number,
context: {
readonly requestId: PreviewAutomationRequest["requestId"];
readonly environmentId: EnvironmentId;
readonly threadId: PreviewAutomationRequest["threadId"];
},
): Promise<PreviewRenderedViewportSize> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
try {
const webview = findPreviewWebview(tabId);
const appliedSettingKey = webview?.getAttribute("data-preview-viewport-key") ?? null;
const declaredViewport = readDeclaredViewport(webview);
const renderedViewport = webview ? await readWebviewViewport(webview) : null;
if (
renderedViewport &&
isPreviewViewportReady({
setting,
appliedSettingKey,
declaredViewport,
renderedViewport,
})
) {
return renderedViewport;
}
} catch {
// Registration and navigation can transiently replace the guest while
// React applies the server snapshot. Retry until the operation deadline.
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
throw new PreviewAutomationViewportTimeoutError({
...context,
tabId,
timeoutMs,
});
};
const currentStatus = async (
threadRef: ScopedThreadRef,
requestedTabId: string | null,
): Promise<PreviewAutomationStatus> => {
const state = readThreadPreviewState(threadRef);
const { snapshot, tabId } = resolvePreviewAutomationTarget(state, requestedTabId);
const visible = tabId
? (useBrowserSurfaceStore.getState().byTabId[tabId]?.visible ?? false)
: false;
const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;
const viewport = tabId ? await readRenderedViewport(tabId).catch(() => null) : null;
const viewportStatus = {
...(viewportSetting === undefined ? {} : { viewportSetting }),
...(viewport === null ? {} : { viewport }),
};
if (tabId && previewBridge && state.desktopByTabId[tabId]) {
const status = await previewBridge.automation.status(tabId);
return { ...status, visible, ...viewportStatus };
}
const navStatus = snapshot?.navStatus;
return {
available: Boolean(previewBridge?.automation),
visible,
tabId,
url: navStatus && navStatus._tag !== "Idle" ? navStatus.url : null,
title: navStatus && navStatus._tag !== "Idle" ? navStatus.title : null,
loading: navStatus?._tag === "Loading",
...viewportStatus,
};
};
export function PreviewAutomationHosts() {
const { environments } = useEnvironments();
if (!isElectron || !previewBridge?.automation) return null;
return (
<>
{/*
* Host lifetime follows the desktop runtime's environment connections,
* not the routed thread. This keeps background threads automatable and
* lets the subscription runtime own reconnects for every saved target.
*/}
{environments.map((environment) => (
<PreviewAutomationHost
key={environment.environmentId}
environmentId={environment.environmentId}
/>
))}
</>
);
}
function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId }) {
const { environmentId } = props;
const registry = useContext(RegistryContext);
const [automationClientId] = useState(createPreviewAutomationClientId);
const initialAutomationHost = useMemo<PreviewAutomationHostState>(
() => ({
clientId: automationClientId,
environmentId,
supportedOperations: [...PREVIEW_AUTOMATION_OPERATIONS],
}),
[automationClientId, environmentId],
);
const automationRequestsAtom = previewEnvironment.automationRequests({
environmentId,
input: initialAutomationHost,
});
const listPreviews = useAtomQueryRunner(previewEnvironment.list, {
reportFailure: false,
});
const open = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const resize = useAtomCommand(previewEnvironment.resize, {
reportFailure: false,
});
const respondToAutomation = useAtomCommand(
previewEnvironment.respondToAutomation,
"preview automation response",
);
const focusAutomationHost = useAtomCommand(
previewEnvironment.focusAutomationHost,
"preview automation host focus",
);
const [automationConnectionAtom] = useState(() => Atom.make<string | null>(null));
const automationConnectionId = useAtomValue(automationConnectionAtom);
const handleRequest = useCallback(
async (request: PreviewAutomationRequest): Promise<unknown> => {
const threadRef: ScopedThreadRef = {
environmentId,
threadId: request.threadId,
};
let tabId = request.tabId ?? null;
try {
let state = readThreadPreviewState(threadRef);
const needsSessionSync = needsPreviewAutomationSessionSync(state, request.tabId);
if (needsSessionSync) {
const listTarget = {
environmentId,
input: { threadId: request.threadId },
} as const;
registry.refresh(previewEnvironment.list(listTarget));
const result = await listPreviews(listTarget);
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
reconcilePreviewServerSessions(threadRef, result.value.sessions);
state = readThreadPreviewState(threadRef);
}
tabId = request.tabId ?? state.snapshot?.tabId ?? null;
const unavailableTarget = {
requestId: request.requestId,
operation: request.operation,
environmentId,
threadId: request.threadId,
tabId,
bridgeAvailable: Boolean(previewBridge),
};
const requireReadyTab = async () => {
const bridge = previewBridge;
const readyTabId = tabId;
if (!bridge || !readyTabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
await waitForDesktopOverlay(threadRef, request.requestId, readyTabId, request.timeoutMs);
return { bridge, tabId: readyTabId };
};
switch (request.operation) {
case "status":
return await currentStatus(threadRef, tabId);
case "open": {
const input = request.input as PreviewAutomationOpenInput;
let activeTabId =
(input.reuseExistingTab ?? true) ? (state.snapshot?.tabId ?? null) : null;
let activeSnapshot = activeTabId
? (state.sessions[activeTabId] ?? state.snapshot ?? undefined)
: undefined;
const reusedExistingTab = activeTabId !== null;
tabId = activeTabId;
if (!activeTabId) {
const result = await open({
environmentId,
input: {
threadId: request.threadId,
...(input.url ? { url: input.url } : {}),
},
});
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
activeSnapshot = snapshot;
tabId = activeTabId;
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
await waitForDesktopOverlay(
threadRef,
request.requestId,
activeTabId,
request.timeoutMs,
);
}
if (reusedExistingTab && input.url && previewBridge) {
const resolution = resolveBrowserNavigationTarget(environmentId, {
kind: "url",
url: input.url,
});
await previewBridge.navigate(activeTabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
activeTabId,
"load",
request.timeoutMs,
);
}
return await currentStatus(threadRef, activeTabId);
}
case "navigate": {
const ready = await requireReadyTab();
const input = request.input as PreviewAutomationNavigateInput;
const resolution = resolveBrowserNavigationTarget(
environmentId,
input.target ?? {
kind: "url",
url: input.url!,
},
);
await ready.bridge.navigate(ready.tabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
ready.tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, ready.tabId);
}
case "resize": {
const ready = await requireReadyTab();
const input = request.input as PreviewAutomationResizeInput;
const setting = resolvePreviewViewport(input);
const result = await resize({
environmentId,
input: {
threadId: request.threadId,
tabId: ready.tabId,
viewport: setting,
},
});
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
updatePreviewServerSnapshot(threadRef, result.value);
const viewport = await waitForRenderedViewport(
ready.tabId,
setting,
input.timeoutMs ?? request.timeoutMs,
{
requestId: request.requestId,
environmentId,
threadId: request.threadId,
},
);
return {
tabId: ready.tabId,
setting,
viewport,
} satisfies PreviewAutomationResizeResult;
}
case "snapshot": {
const ready = await requireReadyTab();
return await ready.bridge.automation.snapshot(ready.tabId);
}
case "click": {
const ready = await requireReadyTab();
return await ready.bridge.automation.click(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.click>[1],
);
}
case "type": {
const ready = await requireReadyTab();
return await ready.bridge.automation.type(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.type>[1],
);
}
case "press": {
const ready = await requireReadyTab();
return await ready.bridge.automation.press(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.press>[1],
);
}
case "scroll": {
const ready = await requireReadyTab();
return await ready.bridge.automation.scroll(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.scroll>[1],
);
}
case "evaluate": {
const ready = await requireReadyTab();
return await ready.bridge.automation.evaluate(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.evaluate>[1],
);
}
case "waitFor": {
const ready = await requireReadyTab();
return await ready.bridge.automation.waitFor(
ready.tabId,
request.input as Parameters<typeof ready.bridge.automation.waitFor>[1],
);
}
case "recordingStart": {
const ready = await requireReadyTab();
const startedAt = await startBrowserRecording(ready.tabId);
return {
tabId: ready.tabId,
recording: true,
startedAt,
};
}
case "recordingStop": {
const recordingTabId = readActiveBrowserRecordingTabId();
const stopTabId = resolveBrowserRecordingStopTarget(recordingTabId);
const artifact = stopTabId ? await stopBrowserRecording(stopTabId) : null;
if (!artifact) {
throw new PreviewAutomationRecordingNotActiveError({
requestId: request.requestId,
environmentId,
threadId: request.threadId,
tabId,
});
}
return artifact;
}
}
} catch (cause) {
throw PreviewAutomationOperationError.fromCause({
requestId: request.requestId,
operation: request.operation,
environmentId,
threadId: request.threadId,
tabId,
cause,
});
}
},
[environmentId, listPreviews, open, registry, resize],
);
const [requestHandlerAtom] = useState(() => Atom.make({ handle: handleRequest }));
const setRequestHandler = useAtomSet(requestHandlerAtom);
useEffect(() => {
setRequestHandler({ handle: handleRequest });
}, [handleRequest, setRequestHandler]);
const automationRequestConsumerAtom = useMemo(
() =>
createPreviewAutomationRequestConsumerAtom({
requestsAtom: automationRequestsAtom,
clientId: automationClientId,
connectionAtom: automationConnectionAtom,
environmentId,
requestHandlerAtom,
respond: (response) =>
respondToAutomation({
environmentId,
input: response,
}),
label: `preview:automation-host:${environmentId}:${automationClientId}`,
}),
[
automationClientId,
automationConnectionAtom,
automationRequestsAtom,
requestHandlerAtom,
respondToAutomation,
environmentId,
],
);
useAtomValue(automationRequestConsumerAtom);
useEffect(() => {
const report = () => {
if (!automationConnectionId) return;
void focusAutomationHost({
environmentId,
input: {
clientId: automationClientId,
environmentId,
connectionId: automationConnectionId,
focused: document.hasFocus(),
},
});
};
report();
window.addEventListener("focus", report);
window.addEventListener("blur", report);
return () => {
window.removeEventListener("focus", report);
window.removeEventListener("blur", report);
};
}, [automationClientId, automationConnectionId, environmentId, focusAutomationHost]);
return null;
}
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vite-plus/test";
import { observeAutomationOwnerConnectedGeneration } from "./PreviewAutomationOwner";
describe("observeAutomationOwnerConnectedGeneration", () => {
it("reports ownership when the initial transport generation connects", () => {
const initial = observeAutomationOwnerConnectedGeneration(null, 1);
expect(initial).toEqual({
nextGeneration: 1,
shouldReport: true,
});
const disconnected = observeAutomationOwnerConnectedGeneration(initial.nextGeneration, null);
expect(disconnected).toEqual({
nextGeneration: 1,
shouldReport: false,
});
expect(observeAutomationOwnerConnectedGeneration(disconnected.nextGeneration, 2)).toEqual({
nextGeneration: 2,
shouldReport: true,
});
});
it("does not re-report for repeated connected state from the same generation", () => {
expect(observeAutomationOwnerConnectedGeneration(3, 3)).toEqual({
nextGeneration: 3,
shouldReport: false,
});
});
});
@@ -0,0 +1,426 @@
"use client";
import { useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
type PreviewAutomationNavigateInput,
type PreviewAutomationOpenInput,
type PreviewAutomationOwner as PreviewAutomationOwnerState,
type PreviewAutomationRequest,
type PreviewAutomationStatus,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { useCallback, useEffect, useEffectEvent, useId, useMemo, useRef, useState } from "react";
import {
applyPreviewServerSnapshot,
readThreadPreviewState,
subscribeThreadPreviewState,
} from "~/previewStateStore";
import { useRightPanelStore } from "~/rightPanelStore";
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
import { startBrowserRecording, stopBrowserRecording } from "~/browser/browserRecording";
import { previewEnvironment } from "~/state/preview";
import { useEnvironmentConnectionState } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
import {
PreviewAutomationNavigationTimeoutError,
PreviewAutomationOperationError,
PreviewAutomationOverlayTimeoutError,
PreviewAutomationRecordingNotActiveError,
PreviewAutomationStaleOwnerError,
PreviewAutomationTargetUnavailableError,
} from "./previewAutomationErrors";
import {
createLatestPreviewAutomationRequestHandler,
createPreviewAutomationRequestConsumerAtom,
} from "./previewAutomationRequestConsumer";
export function observeAutomationOwnerConnectedGeneration(
previousGeneration: number | null,
connectedGeneration: number | null,
): {
readonly nextGeneration: number | null;
readonly shouldReport: boolean;
} {
if (connectedGeneration === null) {
return {
nextGeneration: previousGeneration,
shouldReport: false,
};
}
return {
nextGeneration: connectedGeneration,
shouldReport: previousGeneration !== connectedGeneration,
};
}
const waitForDesktopOverlay = async (
threadRef: ScopedThreadRef,
requestId: string,
timeoutMs: number,
): Promise<void> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
const state = readThreadPreviewState(threadRef);
const tabId = state.snapshot?.tabId;
if (tabId && state.desktopOverlay && previewBridge) {
const status = await previewBridge.automation.status(tabId);
if (status.available) return;
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
throw new PreviewAutomationOverlayTimeoutError({
requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
timeoutMs,
});
};
const waitForNavigationReadiness = async (
threadRef: ScopedThreadRef,
requestId: string,
tabId: string,
readiness: PreviewAutomationNavigateInput["readiness"],
timeoutMs: number,
): Promise<void> => {
const targetReadiness = readiness ?? "load";
if (!previewBridge || targetReadiness === "none") return;
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
if (targetReadiness === "domContentLoaded") {
const readyState = await previewBridge.automation.evaluate(tabId, {
expression: "document.readyState",
});
if (readyState === "interactive" || readyState === "complete") return;
} else {
const status = await previewBridge.automation.status(tabId);
if (!status.loading) return;
}
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
}
throw new PreviewAutomationNavigationTimeoutError({
requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId,
readiness: targetReadiness,
timeoutMs,
});
};
const currentStatus = async (
threadRef: ScopedThreadRef,
visible: boolean,
): Promise<PreviewAutomationStatus> => {
const state = readThreadPreviewState(threadRef);
const tabId = state.snapshot?.tabId ?? null;
if (tabId && previewBridge && state.desktopOverlay) {
const status = await previewBridge.automation.status(tabId);
return { ...status, visible };
}
const navStatus = state.snapshot?.navStatus;
return {
available: Boolean(previewBridge?.automation),
visible,
tabId,
url: navStatus && navStatus._tag !== "Idle" ? navStatus.url : null,
title: navStatus && navStatus._tag !== "Idle" ? navStatus.title : null,
loading: navStatus?._tag === "Loading",
};
};
export function PreviewAutomationOwner(props: {
readonly threadRef: ScopedThreadRef;
readonly visible: boolean;
}) {
const { threadRef, visible } = props;
const automationClientId = useId();
const initialAutomationOwner = useMemo<PreviewAutomationOwnerState>(
() => ({
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId: null,
visible: false,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
}),
[automationClientId, threadRef.environmentId, threadRef.threadId],
);
const automationRequestsAtom = previewEnvironment.automationRequests({
environmentId: threadRef.environmentId,
input: initialAutomationOwner,
});
const connectionState = useEnvironmentConnectionState(threadRef.environmentId).data;
const connectedGeneration =
connectionState?.phase === "connected" ? connectionState.generation : null;
const open = useAtomCommand(previewEnvironment.open, {
reportFailure: false,
});
const respondToAutomation = useAtomCommand(
previewEnvironment.respondToAutomation,
"preview automation response",
);
const reportAutomationOwner = useAtomCommand(
previewEnvironment.reportAutomationOwner,
"preview automation owner report",
);
const clearAutomationOwner = useAtomCommand(
previewEnvironment.clearAutomationOwner,
"preview automation owner clear",
);
const connectedGenerationRef = useRef<number | null>(null);
const reportCurrentAutomationOwner = useEffectEvent(() => {
const state = readThreadPreviewState(threadRef);
return reportAutomationOwner({
environmentId: threadRef.environmentId,
input: {
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId: state.snapshot?.tabId ?? null,
visible,
supportsAutomation: Boolean(previewBridge?.automation),
focusedAt: new Date().toISOString(),
},
});
});
useEffect(() => {
void reportCurrentAutomationOwner();
}, [threadRef, visible]);
const handleRequest = useCallback(
async (request: PreviewAutomationRequest): Promise<unknown> => {
let tabId = request.tabId ?? null;
try {
if (request.threadId !== threadRef.threadId) {
throw new PreviewAutomationStaleOwnerError({
requestId: request.requestId,
environmentId: threadRef.environmentId,
expectedThreadId: threadRef.threadId,
requestedThreadId: request.threadId,
});
}
const state = readThreadPreviewState(threadRef);
tabId = request.tabId ?? state.snapshot?.tabId ?? null;
const unavailableTarget = {
requestId: request.requestId,
operation: request.operation,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId,
bridgeAvailable: Boolean(previewBridge),
};
switch (request.operation) {
case "status":
return await currentStatus(threadRef, visible);
case "open": {
const input = request.input as PreviewAutomationOpenInput;
let activeTabId =
(input.reuseExistingTab ?? true) ? (state.snapshot?.tabId ?? null) : null;
tabId = activeTabId;
if (!activeTabId) {
const result = await open({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
...(input.url ? { url: input.url } : {}),
},
});
if (result._tag === "Failure") {
throw squashAtomCommandFailure(result);
}
const snapshot = result.value;
applyPreviewServerSnapshot(threadRef, snapshot);
activeTabId = snapshot.tabId;
tabId = activeTabId;
} else if (input.url && previewBridge) {
await previewBridge.navigate(activeTabId, input.url);
}
if (input.show ?? true) {
useRightPanelStore.getState().openBrowser(threadRef, activeTabId);
}
await waitForDesktopOverlay(threadRef, request.requestId, request.timeoutMs);
return await currentStatus(threadRef, input.show ?? true);
}
case "navigate": {
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
const input = request.input as PreviewAutomationNavigateInput;
const resolution = resolveBrowserNavigationTarget(
threadRef.environmentId,
input.target ?? { kind: "url", url: input.url! },
);
await previewBridge.navigate(tabId, resolution.resolvedUrl);
await waitForNavigationReadiness(
threadRef,
request.requestId,
tabId,
input.readiness ?? "load",
input.timeoutMs ?? request.timeoutMs,
);
return await currentStatus(threadRef, visible);
}
case "snapshot":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.snapshot(tabId);
case "click":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.click(
tabId,
request.input as Parameters<typeof previewBridge.automation.click>[1],
);
case "type":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.type(
tabId,
request.input as Parameters<typeof previewBridge.automation.type>[1],
);
case "press":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.press(
tabId,
request.input as Parameters<typeof previewBridge.automation.press>[1],
);
case "scroll":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.scroll(
tabId,
request.input as Parameters<typeof previewBridge.automation.scroll>[1],
);
case "evaluate":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.evaluate(
tabId,
request.input as Parameters<typeof previewBridge.automation.evaluate>[1],
);
case "waitFor":
if (!previewBridge || !tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
return await previewBridge.automation.waitFor(
tabId,
request.input as Parameters<typeof previewBridge.automation.waitFor>[1],
);
case "recordingStart": {
if (!tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
const startedAt = await startBrowserRecording(tabId);
return {
tabId,
recording: true,
startedAt,
};
}
case "recordingStop": {
if (!tabId) {
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
}
const artifact = await stopBrowserRecording(tabId);
if (!artifact) {
throw new PreviewAutomationRecordingNotActiveError({
requestId: request.requestId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId,
});
}
return artifact;
}
}
} catch (cause) {
throw PreviewAutomationOperationError.fromCause({
requestId: request.requestId,
operation: request.operation,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
tabId,
cause,
});
}
},
[open, threadRef, visible],
);
const [requestHandler] = useState(() =>
createLatestPreviewAutomationRequestHandler(handleRequest),
);
useEffect(() => {
requestHandler.set(handleRequest);
}, [handleRequest, requestHandler]);
const automationRequestConsumerAtom = useMemo(
() =>
createPreviewAutomationRequestConsumerAtom({
requestsAtom: automationRequestsAtom,
environmentId: threadRef.environmentId,
handleRequest: requestHandler.handle,
respond: (response) =>
respondToAutomation({
environmentId: threadRef.environmentId,
input: response,
}),
label: `preview:automation-request-consumer:${automationClientId}`,
}),
[
automationClientId,
automationRequestsAtom,
requestHandler,
respondToAutomation,
threadRef.environmentId,
],
);
useAtomValue(automationRequestConsumerAtom);
useEffect(() => {
const observation = observeAutomationOwnerConnectedGeneration(
connectedGenerationRef.current,
connectedGeneration,
);
connectedGenerationRef.current = observation.nextGeneration;
if (!observation.shouldReport) return;
void reportCurrentAutomationOwner();
}, [connectedGeneration]);
useEffect(() => {
const report = () => void reportCurrentAutomationOwner();
window.addEventListener("focus", report);
const unsubscribe = subscribeThreadPreviewState(threadRef, (state, previous) => {
if (state.snapshot?.tabId !== previous.snapshot?.tabId) {
report();
}
});
return () => {
window.removeEventListener("focus", report);
unsubscribe();
void clearAutomationOwner({
environmentId: threadRef.environmentId,
input: {
clientId: automationClientId,
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
},
});
};
}, [automationClientId, clearAutomationOwner, threadRef]);
return null;
}
@@ -19,10 +19,6 @@ interface Props {
hasWebContents: boolean;
/** Current zoom factor as a number (1.0 = 100%). */
zoomFactor: number;
/** Fixed viewport modes expose the device toolbar and resize rails. */
deviceToolbarVisible: boolean;
/** Switches between fill-panel mode and a fixed responsive viewport. */
onToggleDeviceToolbar: () => void;
}
/**
@@ -30,13 +26,7 @@ interface Props {
* controls, and storage-clearing actions. Only mounted by `PreviewView`
* when the desktop bridge is present, so we can call it unconditionally.
*/
export function PreviewMoreMenu({
tabId,
hasWebContents,
zoomFactor,
deviceToolbarVisible,
onToggleDeviceToolbar,
}: Props) {
export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
if (!previewBridge) return null;
const bridge = previewBridge;
const tabDisabled = !tabId || !hasWebContents;
@@ -69,10 +59,6 @@ export function PreviewMoreMenu({
<MenuItem onClick={callTab(bridge.openDevTools)} disabled={tabDisabled}>
Open DevTools
</MenuItem>
<MenuItem onClick={onToggleDeviceToolbar} disabled={tabDisabled}>
{deviceToolbarVisible ? "Hide device toolbar" : "Show device toolbar"}
</MenuItem>
<MenuSeparator />
{/*
Zoom row: label + inline control cluster. `closeOnClick=false`
keeps the menu open while the user clicks the +/− buttons.
@@ -1,22 +1,13 @@
"use client";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
FILL_PREVIEW_VIEWPORT,
type PreviewViewportSetting,
type ScopedThreadRef,
} from "@t3tools/contracts";
import { type ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useEffect, useRef, useState } from "react";
import { useComposerDraftStore } from "~/composerDraftStore";
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
import { ensureLocalApi } from "~/localApi";
import {
rememberPreviewUrl,
updatePreviewServerSnapshot,
useThreadPreviewState,
} from "~/previewStateStore";
import { rememberPreviewUrl, useThreadPreviewState } from "~/previewStateStore";
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
import { previewEnvironment } from "~/state/preview";
@@ -29,16 +20,10 @@ import { PreviewChromeRow } from "./PreviewChromeRow";
import { formatPreviewUrl } from "./previewUrlPresentation";
import { PreviewEmptyState } from "./PreviewEmptyState";
import { PreviewMoreMenu } from "./PreviewMoreMenu";
import {
commitBrowserViewportChange,
subscribeBrowserViewportChange,
} from "~/browser/browserViewportActions";
import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
import { PreviewUnreachable } from "./PreviewUnreachable";
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
import { useLoadingProgress } from "./useLoadingProgress";
import { usePreviewSession } from "./usePreviewSession";
import { ZoomIndicator } from "./ZoomIndicator";
@@ -75,7 +60,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const environment = useEnvironment(threadRef.environmentId);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
const open = useAtomCommand(previewEnvironment.open);
const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
usePreviewSession(threadRef);
@@ -107,10 +91,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
environmentHttpBaseUrl,
}) ?? undefined)
: undefined;
const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
const panelRect = useBrowserSurfaceStore((state) =>
tabId ? (state.byTabId[tabId]?.rect ?? null) : null,
);
const handleSubmitUrl = useCallback(
async (next: string) => {
@@ -151,51 +131,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
}, [tabId]);
const handleViewportChange = useCallback(
async (nextViewport: PreviewViewportSetting) => {
if (!tabId) return;
const result = await resize({
environmentId: threadRef.environmentId,
input: {
threadId: threadRef.threadId,
tabId,
viewport: nextViewport,
},
});
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: "Unable to resize browser viewport",
description: error instanceof Error ? error.message : "An error occurred.",
});
throw error;
}
updatePreviewServerSnapshot(threadRef, result.value);
},
[resize, tabId, threadRef],
);
const handleToggleDeviceToolbar = () => {
if (!tabId) return;
if (viewport._tag !== "fill") {
void commitBrowserViewportChange(tabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
return;
}
const responsiveSize = panelRect
? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)
: { width: 1024, height: 768 };
void commitBrowserViewportChange(tabId, { _tag: "freeform", ...responsiveSize }).catch(
() => undefined,
);
};
useEffect(() => {
if (!tabId) return;
return subscribeBrowserViewportChange(tabId, handleViewportChange);
}, [handleViewportChange, tabId]);
const handleBack = useCallback(() => {
if (previewBridge && tabId) void previewBridge.goBack(tabId);
}, [tabId]);
@@ -592,8 +527,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
tabId={tabId}
hasWebContents={desktopOverlay !== null}
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
deviceToolbarVisible={viewport._tag !== "fill"}
onToggleDeviceToolbar={handleToggleDeviceToolbar}
/>
) : null
}
@@ -1,13 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
describe("createPreviewAutomationClientId", () => {
it("creates bounded cryptographically random identities for independent host lifetimes", () => {
const clientIds = Array.from({ length: 32 }, createPreviewAutomationClientId);
expect(new Set(clientIds).size).toBe(clientIds.length);
expect(clientIds.every((clientId) => clientId.startsWith("preview-"))).toBe(true);
expect(clientIds.every((clientId) => clientId.length <= 128)).toBe(true);
});
});
@@ -1,4 +0,0 @@
export function createPreviewAutomationClientId(): string {
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
return `preview-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}
@@ -1,6 +1,6 @@
import {
EnvironmentId,
type PreviewAutomationHost,
type PreviewAutomationOwner,
PreviewAutomationOperation,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
@@ -13,7 +13,7 @@ import * as Schema from "effect/Schema";
export interface PreviewAutomationOperationContext {
readonly requestId: PreviewAutomationRequest["requestId"];
readonly operation: PreviewAutomationRequest["operation"];
readonly environmentId: PreviewAutomationHost["environmentId"];
readonly environmentId: PreviewAutomationOwner["environmentId"];
readonly threadId: PreviewAutomationRequest["threadId"];
readonly tabId: Exclude<PreviewAutomationRequest["tabId"], undefined> | null;
}
@@ -56,22 +56,21 @@ export class PreviewAutomationNavigationTimeoutError extends Schema.TaggedErrorC
}
}
export class PreviewAutomationViewportTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationViewportTimeoutError>()(
"PreviewAutomationViewportTimeoutError",
export class PreviewAutomationStaleOwnerError extends Schema.TaggedErrorClass<PreviewAutomationStaleOwnerError>()(
"PreviewAutomationStaleOwnerError",
{
requestId: TrimmedNonEmptyString,
environmentId: EnvironmentId,
threadId: ThreadId,
tabId: PreviewTabId,
timeoutMs: Schema.Int,
expectedThreadId: ThreadId,
requestedThreadId: ThreadId,
},
) {
get responseTag() {
return "PreviewAutomationTimeoutError" as const;
return "PreviewAutomationUnavailableError" as const;
}
override get message(): string {
return `Preview viewport for request ${this.requestId} on environment ${this.environmentId} thread ${this.threadId} tab ${this.tabId} was not rendered within ${this.timeoutMs}ms.`;
return `Preview automation request ${this.requestId} targeted thread ${this.requestedThreadId}, but the owner for environment ${this.environmentId} is attached to thread ${this.expectedThreadId}.`;
}
}
@@ -101,7 +100,7 @@ export class PreviewAutomationRecordingNotActiveError extends Schema.TaggedError
requestId: TrimmedNonEmptyString,
environmentId: EnvironmentId,
threadId: ThreadId,
tabId: Schema.NullOr(PreviewTabId),
tabId: PreviewTabId,
},
) {
get responseTag() {
@@ -109,65 +108,10 @@ export class PreviewAutomationRecordingNotActiveError extends Schema.TaggedError
}
override get message(): string {
return `Preview automation request ${this.requestId} found no active recording for tab ${this.tabId ?? "unassigned"} on environment ${this.environmentId} thread ${this.threadId}.`;
return `Preview automation request ${this.requestId} found no active recording for tab ${this.tabId} on environment ${this.environmentId} thread ${this.threadId}.`;
}
}
export class PreviewAutomationTargetNotEditableHostError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableHostError>()(
"PreviewAutomationTargetNotEditableHostError",
{
requestId: TrimmedNonEmptyString,
operation: PreviewAutomationOperation,
environmentId: EnvironmentId,
threadId: ThreadId,
tabId: Schema.NullOr(PreviewTabId),
selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
},
) {
get responseTag() {
return "PreviewAutomationTargetNotEditableError" as const;
}
override get message(): string {
return `Preview automation ${this.operation} request ${this.requestId} requires an editable target in tab ${this.tabId ?? "unassigned"}.`;
}
}
const targetNotEditableDiagnostics = (
cause: unknown,
): {
readonly selectorKind?: "focused-element" | "locator" | "selector";
readonly selectorLength?: number;
} | null => {
if (
typeof cause !== "object" ||
cause === null ||
!("_tag" in cause) ||
cause._tag !== "PreviewAutomationTargetNotEditableError"
) {
return null;
}
const selectorKind =
"selectorKind" in cause &&
(cause.selectorKind === "focused-element" ||
cause.selectorKind === "locator" ||
cause.selectorKind === "selector")
? cause.selectorKind
: undefined;
const selectorLength =
"selectorLength" in cause &&
typeof cause.selectorLength === "number" &&
Number.isInteger(cause.selectorLength) &&
cause.selectorLength >= 0
? cause.selectorLength
: undefined;
return {
...(selectorKind === undefined ? {} : { selectorKind }),
...(selectorLength === undefined ? {} : { selectorLength }),
};
};
export class PreviewAutomationOperationError extends Schema.TaggedErrorClass<PreviewAutomationOperationError>()(
"PreviewAutomationOperationError",
{
@@ -181,18 +125,9 @@ export class PreviewAutomationOperationError extends Schema.TaggedErrorClass<Pre
) {
static fromCause(
input: PreviewAutomationOperationContext & { readonly cause: unknown },
): PreviewAutomationHostError {
if (isPreviewAutomationHostError(input.cause)) return input.cause;
const diagnostics = targetNotEditableDiagnostics(input.cause);
return diagnostics
? new PreviewAutomationTargetNotEditableHostError({
requestId: input.requestId,
operation: input.operation,
environmentId: input.environmentId,
threadId: input.threadId,
tabId: input.tabId,
...diagnostics,
})
): PreviewAutomationOwnerError {
return isPreviewAutomationOwnerError(input.cause)
? input.cause
: new PreviewAutomationOperationError(input);
}
@@ -205,21 +140,20 @@ export class PreviewAutomationOperationError extends Schema.TaggedErrorClass<Pre
}
}
export const PreviewAutomationHostError = Schema.Union([
export const PreviewAutomationOwnerError = Schema.Union([
PreviewAutomationOverlayTimeoutError,
PreviewAutomationNavigationTimeoutError,
PreviewAutomationViewportTimeoutError,
PreviewAutomationStaleOwnerError,
PreviewAutomationTargetUnavailableError,
PreviewAutomationRecordingNotActiveError,
PreviewAutomationTargetNotEditableHostError,
PreviewAutomationOperationError,
]);
export type PreviewAutomationHostError = typeof PreviewAutomationHostError.Type;
export type PreviewAutomationOwnerError = typeof PreviewAutomationOwnerError.Type;
export const isPreviewAutomationHostError = Schema.is(PreviewAutomationHostError);
export const isPreviewAutomationOwnerError = Schema.is(PreviewAutomationOwnerError);
export function serializePreviewAutomationHostError(
error: PreviewAutomationHostError,
export function serializePreviewAutomationOwnerError(
error: PreviewAutomationOwnerError,
): NonNullable<PreviewAutomationResponse["error"]> {
const detail = Object.fromEntries(
Object.entries(error).filter(
@@ -1,46 +0,0 @@
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { previewAutomationOpenNeedsOverlay } from "./previewAutomationOpenReadiness";
const snapshot = (navStatus: PreviewSessionSnapshot["navStatus"]): PreviewSessionSnapshot => ({
threadId: "thread-1",
tabId: "tab-1",
navStatus,
canGoBack: false,
canGoForward: false,
updatedAt: "2026-06-26T00:00:00.000Z",
});
describe("preview automation open readiness", () => {
it("does not wait for a desktop overlay when opening an empty tab", () => {
expect(
previewAutomationOpenNeedsOverlay(
{} as PreviewAutomationOpenInput,
snapshot({ _tag: "Idle" }),
),
).toBe(false);
});
it("waits when an empty tab is immediately given a URL", () => {
expect(
previewAutomationOpenNeedsOverlay(
{ url: "https://example.com" } as PreviewAutomationOpenInput,
snapshot({ _tag: "Idle" }),
),
).toBe(true);
});
it("waits for existing tabs that already have rendered content", () => {
expect(
previewAutomationOpenNeedsOverlay(
{} as PreviewAutomationOpenInput,
snapshot({
_tag: "Success",
url: "https://example.com/",
title: "Example",
}),
),
).toBe(true);
});
});
@@ -1,8 +0,0 @@
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
export function previewAutomationOpenNeedsOverlay(
input: PreviewAutomationOpenInput,
snapshot: PreviewSessionSnapshot,
): boolean {
return input.url !== undefined || snapshot.navStatus._tag !== "Idle";
}
@@ -2,18 +2,13 @@ import {
EnvironmentId,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
type PreviewAutomationStreamEvent,
PreviewTabId,
ThreadId,
} from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { describe, expect, it, vi } from "vite-plus/test";
import {
PreviewAutomationRecordingNotActiveError,
PreviewAutomationTargetUnavailableError,
PreviewAutomationViewportTimeoutError,
} from "./previewAutomationErrors";
import { PreviewAutomationTargetUnavailableError } from "./previewAutomationErrors";
import {
createPreviewAutomationRequestConsumerAtom,
serializePreviewAutomationError,
@@ -22,8 +17,6 @@ import {
const environmentId = EnvironmentId.make("environment-1");
const threadId = ThreadId.make("thread-1");
const tabId = PreviewTabId.make("tab-1");
const clientId = "client-1";
const connectionId = "connection-1";
const request = (
requestId: string,
@@ -37,88 +30,10 @@ const request = (
...overrides,
});
const requestEvent = (
requestId: string,
overrides: Partial<PreviewAutomationRequest> = {},
eventConnectionId = connectionId,
): PreviewAutomationStreamEvent => ({
type: "request",
connectionId: eventConnectionId,
request: request(requestId, overrides),
});
const consumerState = (handleRequest: (request: PreviewAutomationRequest) => Promise<unknown>) => ({
connectionAtom: Atom.make<string | null>(null),
requestHandlerAtom: Atom.make({ handle: handleRequest }),
});
describe("previewAutomationRequestConsumer", () => {
it("acknowledges a replacement stream before consuming requests from it", async () => {
const requestsAtom = Atom.make(
AsyncResult.success<PreviewAutomationStreamEvent, Error>({
type: "connected",
connectionId,
}),
);
const handleRequest = vi.fn(async () => undefined);
const respond = vi.fn(async () => undefined);
const state = consumerState(handleRequest);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
respond,
label: "test:preview-automation-connected",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-after-connect")));
await vi.waitFor(() => expect(registry.get(state.connectionAtom)).toBe(connectionId));
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
expect(handleRequest).toHaveBeenCalledTimes(1);
registry.dispose();
});
it("drops late requests from an older stream generation", async () => {
const requestsAtom = Atom.make(
AsyncResult.success<PreviewAutomationStreamEvent, Error>({
type: "connected",
connectionId: "connection-2",
}),
);
const handleRequest = vi.fn(async () => undefined);
const respond = vi.fn(async () => undefined);
const state = consumerState(handleRequest);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
respond,
label: "test:preview-automation-stale-generation",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
registry.set(
requestsAtom,
AsyncResult.success(requestEvent("request-stale", {}, "connection-1")),
);
await vi.waitFor(() => expect(registry.get(state.connectionAtom)).toBe("connection-2"));
expect(handleRequest).not.toHaveBeenCalled();
expect(respond).not.toHaveBeenCalled();
registry.dispose();
});
it("consumes every request emitted before React can render", async () => {
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationRequest, Error>>(
AsyncResult.initial<PreviewAutomationRequest, Error>(false),
);
const handleRequest = vi.fn(async (value: PreviewAutomationRequest) => ({
requestId: value.requestId,
@@ -127,21 +42,18 @@ describe("previewAutomationRequestConsumer", () => {
const respond = vi.fn(async (response: PreviewAutomationResponse) => {
responses.push(response);
});
const state = consumerState(handleRequest);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
handleRequest,
respond,
label: "test:preview-automation-consumer",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-1")));
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-2")));
registry.set(requestsAtom, AsyncResult.success(request("request-1")));
registry.set(requestsAtom, AsyncResult.success(request("request-2")));
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
expect(handleRequest.mock.calls.map(([value]) => value.requestId)).toEqual([
@@ -152,50 +64,15 @@ describe("previewAutomationRequestConsumer", () => {
registry.dispose();
});
it("uses the latest request handler without rebuilding the stream consumer", async () => {
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
);
const firstHandler = vi.fn(async () => "first");
const secondHandler = vi.fn(async () => "second");
const respond = vi.fn(async (_response: PreviewAutomationResponse) => undefined);
const state = consumerState(firstHandler);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
respond,
label: "test:preview-automation-latest-handler",
});
const registry = AtomRegistry.make();
registry.mount(consumerAtom);
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-first")));
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
registry.set(state.requestHandlerAtom, { handle: secondHandler });
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-second")));
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
expect(firstHandler).toHaveBeenCalledTimes(1);
expect(secondHandler).toHaveBeenCalledTimes(1);
expect(respond.mock.calls.map(([response]) => response.result)).toEqual(["first", "second"]);
registry.dispose();
});
it("consumes a request that arrived immediately before the consumer mounted", async () => {
const requestsAtom = Atom.make(
AsyncResult.success<PreviewAutomationStreamEvent, Error>(requestEvent("request-ready")),
AsyncResult.success<PreviewAutomationRequest, Error>(request("request-ready")),
);
const respond = vi.fn(async (_response: PreviewAutomationResponse) => undefined);
const state = consumerState(async () => undefined);
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
handleRequest: async () => undefined,
respond,
label: "test:preview-automation-initial-request",
});
@@ -204,12 +81,7 @@ describe("previewAutomationRequestConsumer", () => {
registry.mount(consumerAtom);
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
expect(respond).toHaveBeenCalledWith({
clientId,
connectionId,
requestId: "request-ready",
ok: true,
});
expect(respond).toHaveBeenCalledWith({ requestId: "request-ready", ok: true });
registry.dispose();
});
@@ -246,84 +118,6 @@ describe("previewAutomationRequestConsumer", () => {
});
});
it("reports a missing recording even when no preview tab remains", () => {
const error = new PreviewAutomationRecordingNotActiveError({
requestId: "request-recording-stop",
environmentId,
threadId,
tabId: null,
});
expect(
serializePreviewAutomationError(error, {
requestId: "request-recording-stop",
operation: "recordingStop",
environmentId,
threadId,
tabId: null,
}),
).toMatchObject({
_tag: "PreviewAutomationExecutionError",
detail: { tabId: null },
});
});
it("preserves viewport render timeouts as timeout responses", () => {
const error = new PreviewAutomationViewportTimeoutError({
requestId: "request-resize",
environmentId,
threadId,
tabId,
timeoutMs: 2_500,
});
expect(
serializePreviewAutomationError(error, {
requestId: "request-resize",
operation: "resize",
environmentId,
threadId,
tabId,
}),
).toMatchObject({
_tag: "PreviewAutomationTimeoutError",
detail: { tabId: "tab-1", timeoutMs: 2_500 },
});
});
it("maps desktop non-editable targets to the public typed response", () => {
expect(
serializePreviewAutomationError(
{
_tag: "PreviewAutomationTargetNotEditableError",
tabId: "tab-1",
selectorKind: "selector",
selectorLength: 6,
},
{
requestId: "request-type",
operation: "type",
environmentId,
threadId,
tabId,
},
),
).toEqual({
_tag: "PreviewAutomationTargetNotEditableError",
message:
"Preview automation type request request-type requires an editable target in tab tab-1.",
detail: {
requestId: "request-type",
operation: "type",
environmentId: "environment-1",
threadId: "thread-1",
tabId: "tab-1",
selectorKind: "selector",
selectorLength: 6,
},
});
});
it("correlates unexpected failures without exposing cause details", () => {
const cause = new Error("private bridge token: preview-secret");
const context = {
@@ -351,19 +145,16 @@ describe("previewAutomationRequestConsumer", () => {
});
it("sanitizes unexpected handler failures at the response boundary", async () => {
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationRequest, Error>>(
AsyncResult.initial<PreviewAutomationRequest, Error>(false),
);
const responses: PreviewAutomationResponse[] = [];
const state = consumerState(async () => {
throw new Error("desktop IPC secret: do-not-return");
});
const consumerAtom = createPreviewAutomationRequestConsumerAtom({
requestsAtom,
clientId,
connectionAtom: state.connectionAtom,
environmentId,
requestHandlerAtom: state.requestHandlerAtom,
handleRequest: async () => {
throw new Error("desktop IPC secret: do-not-return");
},
respond: async (response) => {
responses.push(response);
},
@@ -375,7 +166,7 @@ describe("previewAutomationRequestConsumer", () => {
registry.set(
requestsAtom,
AsyncResult.success(
requestEvent("request-failed", {
request("request-failed", {
operation: "click",
tabId,
}),
@@ -384,8 +175,6 @@ describe("previewAutomationRequestConsumer", () => {
await vi.waitFor(() => expect(responses).toHaveLength(1));
expect(responses[0]).toEqual({
clientId,
connectionId,
requestId: "request-failed",
ok: false,
error: {
@@ -1,121 +1,87 @@
import type {
PreviewAutomationHost,
PreviewAutomationOwner,
PreviewAutomationRequest,
PreviewAutomationResponse,
PreviewAutomationStreamEvent,
} from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import {
PreviewAutomationOperationError,
type PreviewAutomationOperationContext,
serializePreviewAutomationHostError,
serializePreviewAutomationOwnerError,
} from "./previewAutomationErrors";
type AutomationStreamResult<E> = AsyncResult.AsyncResult<PreviewAutomationStreamEvent, E>;
type AutomationRequestResult<E> = AsyncResult.AsyncResult<PreviewAutomationRequest, E>;
type AutomationRequestHandler = (request: PreviewAutomationRequest) => Promise<unknown>;
export function createLatestPreviewAutomationRequestHandler(initial: AutomationRequestHandler): {
readonly set: (handler: AutomationRequestHandler) => void;
readonly handle: AutomationRequestHandler;
} {
let current = initial;
return {
set: (handler) => {
current = handler;
},
handle: (request) => current(request),
};
}
export function serializePreviewAutomationError(
error: unknown,
context: PreviewAutomationOperationContext,
): NonNullable<PreviewAutomationResponse["error"]> {
return serializePreviewAutomationHostError(
return serializePreviewAutomationOwnerError(
PreviewAutomationOperationError.fromCause({ ...context, cause: error }),
);
}
export function createPreviewAutomationRequestConsumerAtom<E>(options: {
readonly requestsAtom: Atom.Atom<AutomationStreamResult<E>>;
readonly clientId: PreviewAutomationHost["clientId"];
readonly connectionAtom: Atom.Writable<PreviewAutomationStreamEvent["connectionId"] | null>;
readonly environmentId: PreviewAutomationHost["environmentId"];
readonly requestHandlerAtom: Atom.Atom<{
readonly handle: (request: PreviewAutomationRequest) => Promise<unknown>;
}>;
readonly requestsAtom: Atom.Atom<AutomationRequestResult<E>>;
readonly environmentId: PreviewAutomationOwner["environmentId"];
readonly handleRequest: (request: PreviewAutomationRequest) => Promise<unknown>;
readonly respond: (response: PreviewAutomationResponse) => Promise<unknown>;
readonly label: string;
}): Atom.Atom<void> {
return Atom.make((get) => {
get.mount(options.connectionAtom);
get.mount(options.requestHandlerAtom);
let disposed = false;
let activeConnectionId: PreviewAutomationStreamEvent["connectionId"] | null = null;
let connectionExplicitlyAnnounced = false;
let reportedConnectionId: PreviewAutomationStreamEvent["connectionId"] | null = null;
let requestsVersion = 0;
const consume = (result: AutomationStreamResult<E>) => {
const consume = (result: AutomationRequestResult<E>) => {
if (!AsyncResult.isSuccess(result)) return;
const event = result.value;
if (event.type === "connected") {
activeConnectionId = event.connectionId;
connectionExplicitlyAnnounced = true;
} else if (activeConnectionId === null) {
activeConnectionId = event.connectionId;
} else if (activeConnectionId !== event.connectionId) {
if (connectionExplicitlyAnnounced) return;
activeConnectionId = event.connectionId;
}
if (reportedConnectionId !== event.connectionId) {
reportedConnectionId = event.connectionId;
get.set(options.connectionAtom, event.connectionId);
}
if (event.type === "connected") {
return;
}
const request = event.request;
void get
.once(options.requestHandlerAtom)
.handle(request)
.then(
(value) =>
options.respond({
clientId: options.clientId,
connectionId: event.connectionId,
const request = result.value;
void options.handleRequest(request).then(
(value) =>
options.respond({
requestId: request.requestId,
ok: true,
...(value === undefined ? {} : { result: value }),
}),
(error) =>
options.respond({
requestId: request.requestId,
ok: false,
error: serializePreviewAutomationError(error, {
requestId: request.requestId,
ok: true,
...(value === undefined ? {} : { result: value }),
operation: request.operation,
environmentId: options.environmentId,
threadId: request.threadId,
tabId: request.tabId ?? null,
}),
(error) =>
options.respond({
clientId: options.clientId,
connectionId: event.connectionId,
requestId: request.requestId,
ok: false,
error: serializePreviewAutomationError(error, {
requestId: request.requestId,
operation: request.operation,
environmentId: options.environmentId,
threadId: request.threadId,
tabId: request.tabId ?? null,
}),
}),
);
}),
);
};
get.addFinalizer(() => {
disposed = true;
});
const initialRequest = get.once(options.requestsAtom);
if (AsyncResult.isSuccess(initialRequest)) {
activeConnectionId = initialRequest.value.connectionId;
connectionExplicitlyAnnounced = initialRequest.value.type === "connected";
if (initialRequest.value.type === "connected") {
reportedConnectionId = initialRequest.value.connectionId;
get.set(options.connectionAtom, initialRequest.value.connectionId);
}
}
get.subscribe(options.requestsAtom, (result) => {
requestsVersion += 1;
consume(result);
});
queueMicrotask(() => {
const initialConnectionWasSkipped =
AsyncResult.isSuccess(initialRequest) &&
initialRequest.value.connectionId === activeConnectionId &&
initialRequest.value.connectionId !== reportedConnectionId;
if (!disposed && (requestsVersion === 0 || initialConnectionWasSkipped)) {
consume(initialRequest);
}
if (!disposed && requestsVersion === 0) consume(initialRequest);
});
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(options.label));
}
@@ -1,45 +0,0 @@
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import {
needsPreviewAutomationSessionSync,
resolvePreviewAutomationTarget,
} from "./previewAutomationTarget";
const snapshot = (tabId: string): PreviewSessionSnapshot => ({
threadId: "thread-1",
tabId,
navStatus: { _tag: "Idle" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-01-01T00:00:00.000Z",
});
describe("preview automation target selection", () => {
it("refreshes authoritative sessions whenever the caller relies on the active tab", () => {
const active = snapshot("tab-active");
expect(
needsPreviewAutomationSessionSync(
{ snapshot: active, sessions: { [active.tabId]: active } },
undefined,
),
).toBe(true);
});
it("refreshes an explicit tab only when it is absent locally", () => {
const active = snapshot("tab-active");
const state = { snapshot: active, sessions: { [active.tabId]: active } };
expect(needsPreviewAutomationSessionSync(state, active.tabId)).toBe(false);
expect(needsPreviewAutomationSessionSync(state, "tab-missing")).toBe(true);
});
it("does not report the active tab under an unknown requested tab id", () => {
const active = snapshot("tab-active");
expect(
resolvePreviewAutomationTarget(
{ snapshot: active, sessions: { [active.tabId]: active } },
"tab-missing",
),
).toEqual({ tabId: null, snapshot: null });
});
});
@@ -1,25 +0,0 @@
import type { PreviewSessionSnapshot } from "@t3tools/contracts";
interface PreviewAutomationSessionIndex {
readonly snapshot: PreviewSessionSnapshot | null;
readonly sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
}
export function needsPreviewAutomationSessionSync(
state: PreviewAutomationSessionIndex,
requestedTabId: string | undefined,
): boolean {
return (
Object.keys(state.sessions).length === 0 ||
requestedTabId === undefined ||
state.sessions[requestedTabId] === undefined
);
}
export function resolvePreviewAutomationTarget(
state: PreviewAutomationSessionIndex,
requestedTabId: string | null,
): { readonly tabId: string | null; readonly snapshot: PreviewSessionSnapshot | null } {
const snapshot = requestedTabId ? (state.sessions[requestedTabId] ?? null) : state.snapshot;
return { tabId: snapshot?.tabId ?? null, snapshot };
}
@@ -1,72 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { browserViewportSettingKey } from "~/browser/browserViewportLayout";
import { isPreviewViewportReady } from "./previewViewportReadiness";
describe("isPreviewViewportReady", () => {
const landscape = {
_tag: "preset",
width: 844,
height: 390,
presetId: "iphone-12-pro",
} as const;
it("rejects a stale same-mode preset while React applies the requested orientation", () => {
expect(
isPreviewViewportReady({
setting: landscape,
appliedSettingKey: "preset:390:844:iphone-12-pro",
declaredViewport: { width: 390, height: 844 },
renderedViewport: { width: 390, height: 844 },
}),
).toBe(false);
});
it("requires both the declaration and guest viewport to match a fixed request", () => {
const appliedSettingKey = browserViewportSettingKey(landscape);
expect(
isPreviewViewportReady({
setting: landscape,
appliedSettingKey,
declaredViewport: { width: 390, height: 844 },
renderedViewport: { width: 844, height: 390 },
}),
).toBe(false);
expect(
isPreviewViewportReady({
setting: landscape,
appliedSettingKey,
declaredViewport: { width: 844, height: 390 },
renderedViewport: { width: 844, height: 390 },
}),
).toBe(true);
});
it("allows one pixel of Electron rounding tolerance in every mode", () => {
expect(
isPreviewViewportReady({
setting: { _tag: "fill" },
appliedSettingKey: "fill",
declaredViewport: { width: 500, height: 700 },
renderedViewport: { width: 501, height: 699 },
}),
).toBe(true);
expect(
isPreviewViewportReady({
setting: landscape,
appliedSettingKey: browserViewportSettingKey(landscape),
declaredViewport: { width: 844, height: 390 },
renderedViewport: { width: 845, height: 389 },
}),
).toBe(true);
expect(
isPreviewViewportReady({
setting: landscape,
appliedSettingKey: browserViewportSettingKey(landscape),
declaredViewport: { width: 844, height: 390 },
renderedViewport: { width: 846, height: 390 },
}),
).toBe(false);
});
});
@@ -1,37 +0,0 @@
import type { PreviewRenderedViewportSize, PreviewViewportSetting } from "@t3tools/contracts";
import { browserViewportSettingKey } from "~/browser/browserViewportLayout";
export function isPreviewViewportReady(input: {
readonly setting: PreviewViewportSetting;
readonly appliedSettingKey: string | null;
readonly declaredViewport: PreviewRenderedViewportSize | null;
readonly renderedViewport: PreviewRenderedViewportSize | null;
}): boolean {
const { setting, appliedSettingKey, declaredViewport, renderedViewport } = input;
if (
appliedSettingKey !== browserViewportSettingKey(setting) ||
declaredViewport === null ||
renderedViewport === null
) {
return false;
}
const expectedViewport =
setting._tag === "fill" ? declaredViewport : { width: setting.width, height: setting.height };
if (
setting._tag !== "fill" &&
(declaredViewport.width !== expectedViewport.width ||
declaredViewport.height !== expectedViewport.height)
) {
return false;
}
// Electron rounds CSS pixels through the guest's fractional zoom/device scale,
// so a successfully applied fixed viewport can measure one pixel either way.
const tolerance = 1;
return (
Math.abs(renderedViewport.width - expectedViewport.width) <= tolerance &&
Math.abs(renderedViewport.height - expectedViewport.height) <= tolerance
);
}
@@ -11,7 +11,6 @@ import {
applyPreviewServerEvent,
applyPreviewServerSnapshot,
readThreadPreviewState,
reconcilePreviewServerSessions,
} from "~/previewStateStore";
import { previewEnvironment } from "~/state/preview";
@@ -51,7 +50,9 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
if (result.value.sessions.length > 0) {
recoveringUrl = null;
recoveryId += 1;
reconcilePreviewServerSessions(threadRef, result.value.sessions);
for (const snapshot of result.value.sessions) {
applyPreviewServerSnapshot(threadRef, snapshot);
}
return;
}
-88
View File
@@ -11,12 +11,10 @@ import {
cancelPreviewSessionClose,
previewStateAtom,
readThreadPreviewState,
reconcilePreviewServerSessions,
rememberPreviewUrl,
removePreviewThread,
resetPreviewStateForTests,
setActivePreviewTab,
updatePreviewServerSnapshot,
} from "./previewStateStore";
const environmentId = "env-1" as EnvironmentId;
@@ -110,34 +108,6 @@ describe("previewStateStore (single-tab)", () => {
}
});
it("resized event updates tab viewport without changing the active tab", () => {
const active = makeSnapshot({ tabId: "tab_a" });
const background = makeSnapshot({ tabId: "tab_b" });
applyPreviewServerSnapshot(ref, background);
applyPreviewServerSnapshot(ref, active);
applyPreviewServerEvent(ref, {
type: "resized",
threadId: "thread-1",
tabId: background.tabId,
createdAt: "2026-01-01T00:00:01.000Z",
snapshot: {
...background,
viewport: { _tag: "preset", presetId: "pixel-8", width: 412, height: 915 },
updatedAt: "2026-01-01T00:00:01.000Z",
},
});
const state = readThreadPreviewState(ref);
expect(state.activeTabId).toBe(active.tabId);
expect(state.sessions[background.tabId]?.viewport).toEqual({
_tag: "preset",
presetId: "pixel-8",
width: 412,
height: 915,
});
});
it("failed event flips the snapshot to LoadFailed when tabId matches", () => {
const snapshot = makeSnapshot();
applyPreviewServerEvent(ref, {
@@ -322,64 +292,6 @@ describe("previewStateStore (single-tab)", () => {
expect(state.desktopOverlay?.canGoBack).toBe(true);
});
it("updates a background snapshot without changing the active tab", () => {
const background = makeSnapshot({ tabId: "tab_a" });
const active = makeSnapshot({
tabId: "tab_b",
updatedAt: "2026-01-01T00:00:01.000Z",
});
applyPreviewServerSnapshot(ref, background);
applyPreviewServerSnapshot(ref, active);
const resized = {
...background,
viewport: { _tag: "freeform" as const, width: 900, height: 700 },
updatedAt: "2026-01-01T00:00:02.000Z",
};
updatePreviewServerSnapshot(ref, resized);
const state = readThreadPreviewState(ref);
expect(state.activeTabId).toBe(active.tabId);
expect(state.snapshot?.tabId).toBe(active.tabId);
expect(state.sessions[background.tabId]).toEqual(resized);
});
it("reconciles an authoritative session list without focusing a background tab", () => {
const active = makeSnapshot({ tabId: "tab_a" });
const stale = makeSnapshot({
tabId: "tab_stale",
updatedAt: "2026-01-01T00:00:01.000Z",
});
applyPreviewServerSnapshot(ref, stale);
applyPreviewServerSnapshot(ref, active);
applyPreviewDesktopState(ref, stale.tabId, {
canGoBack: false,
canGoForward: false,
loading: false,
zoomFactor: 1,
controller: "none",
});
reconcilePreviewServerSessions(ref, [active]);
const state = readThreadPreviewState(ref);
expect(Object.keys(state.sessions)).toEqual([active.tabId]);
expect(state.activeTabId).toBe(active.tabId);
expect(state.snapshot).toEqual(active);
expect(state.desktopByTabId[stale.tabId]).toBeUndefined();
});
it("clears stale sessions when an authoritative list is empty", () => {
applyPreviewServerSnapshot(ref, makeSnapshot());
reconcilePreviewServerSessions(ref, []);
const state = readThreadPreviewState(ref);
expect(state.sessions).toEqual({});
expect(state.activeTabId).toBeNull();
expect(state.snapshot).toBeNull();
});
it("applyServerSnapshot null clears snapshot for a thread that had one", () => {
const snapshot = makeSnapshot();
applyPreviewServerSnapshot(ref, snapshot);
+9 -89
View File
@@ -112,26 +112,14 @@ const dedupeRecentUrls = (existing: string[], url: string): string[] => {
return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
};
const rememberSnapshotUrl = (
recentlySeenUrls: string[],
snapshot: PreviewSessionSnapshot,
): string[] =>
snapshot.navStatus._tag === "Idle"
? recentlySeenUrls
: dedupeRecentUrls(recentlySeenUrls, snapshot.navStatus.url);
const latestSnapshot = (
sessions: Record<string, PreviewSessionSnapshot>,
): PreviewSessionSnapshot | null =>
Object.values(sessions)
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
.at(-1) ?? null;
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 = latestSnapshot(sessions);
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;
@@ -175,8 +163,7 @@ export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEven
updateThreadPreviewState(ref, (current) => {
switch (event.type) {
case "opened":
case "navigated":
case "resized": {
case "navigated": {
const snapshot = event.snapshot;
if (current.suppressedTabIds.has(snapshot.tabId)) return current;
const recentlySeenUrls =
@@ -241,7 +228,10 @@ export function applyPreviewServerSnapshot(
if (current.suppressedTabIds.has(snapshot.tabId)) return current;
const existing = current.sessions[snapshot.tabId];
if (existing && existing.updatedAt > snapshot.updatedAt) return current;
const recentlySeenUrls = rememberSnapshotUrl(current.recentlySeenUrls, snapshot);
const recentlySeenUrls =
snapshot.navStatus._tag !== "Idle"
? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
: current.recentlySeenUrls;
return {
...current,
snapshot,
@@ -253,76 +243,6 @@ export function applyPreviewServerSnapshot(
});
}
/**
* Merge a server mutation without changing which tab the user is viewing.
*
* Commands such as resize can target background tabs. Their response is
* authoritative for that tab, but it is not a request to focus the tab.
*/
export function updatePreviewServerSnapshot(
ref: ScopedThreadRef,
snapshot: PreviewSessionSnapshot,
): void {
updateThreadPreviewState(ref, (current) => {
if (current.suppressedTabIds.has(snapshot.tabId)) return current;
const existing = current.sessions[snapshot.tabId];
if (existing && existing.updatedAt > snapshot.updatedAt) return current;
const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
const activeTabId =
current.activeTabId && sessions[current.activeTabId] ? current.activeTabId : snapshot.tabId;
const activeSnapshot = sessions[activeTabId] ?? snapshot;
return {
...current,
sessions,
activeTabId,
snapshot: activeSnapshot,
desktopOverlay: current.desktopByTabId[activeTabId] ?? null,
recentlySeenUrls: rememberSnapshotUrl(current.recentlySeenUrls, snapshot),
};
});
}
/**
* Replace the local session index from an authoritative preview.list result.
* Missing tabs are removed while the current active tab is preserved whenever
* it still exists in the server result.
*/
export function reconcilePreviewServerSessions(
ref: ScopedThreadRef,
snapshots: ReadonlyArray<PreviewSessionSnapshot>,
): void {
updateThreadPreviewState(ref, (current) => {
const sessions: Record<string, PreviewSessionSnapshot> = {};
let recentlySeenUrls = current.recentlySeenUrls;
for (const snapshot of snapshots) {
if (current.suppressedTabIds.has(snapshot.tabId)) continue;
const existing = current.sessions[snapshot.tabId];
const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
sessions[next.tabId] = next;
recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
}
const fallback = latestSnapshot(sessions);
const activeTabId =
current.activeTabId && sessions[current.activeTabId]
? current.activeTabId
: (fallback?.tabId ?? null);
const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
const desktopByTabId = Object.fromEntries(
Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
);
return {
...current,
sessions,
activeTabId,
snapshot,
desktopByTabId,
desktopOverlay: activeTabId ? (desktopByTabId[activeTabId] ?? null) : null,
recentlySeenUrls,
};
});
}
export function applyPreviewDesktopState(
ref: ScopedThreadRef,
tabId: string,
-1
View File
@@ -156,7 +156,6 @@ export default defineConfig(() => {
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host,
clientPort: port,
},
},
build: {
@@ -1,18 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { previewAutomationHostFocusConcurrencyKey } from "./preview.ts";
describe("preview state commands", () => {
it("keeps focus updates from replacement host connections independent", () => {
const first = previewAutomationHostFocusConcurrencyKey({
environmentId: "environment-1",
input: { clientId: "client-1", connectionId: "connection-1" },
});
const replacement = previewAutomationHostFocusConcurrencyKey({
environmentId: "environment-1",
input: { clientId: "client-1", connectionId: "connection-2" },
});
expect(first).not.toBe(replacement);
});
});
+15 -21
View File
@@ -9,14 +9,6 @@ import {
createEnvironmentRpcSubscriptionAtomFamily,
} from "./runtime.ts";
export const previewAutomationHostFocusConcurrencyKey = (value: {
readonly environmentId: string;
readonly input: {
readonly clientId: string;
readonly connectionId: string;
};
}): string => JSON.stringify([value.environmentId, value.input.clientId, value.input.connectionId]);
export function createPreviewEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
) {
@@ -62,12 +54,6 @@ export function createPreviewEnvironmentAtoms<R, E>(
scheduler: lifecycleScheduler,
concurrency: lifecycleConcurrency,
}),
resize: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:resize",
tag: WS_METHODS.previewResize,
scheduler: lifecycleScheduler,
concurrency: lifecycleConcurrency,
}),
refresh: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:refresh",
tag: WS_METHODS.previewRefresh,
@@ -96,17 +82,25 @@ export function createPreviewEnvironmentAtoms<R, E>(
scheduler: automationScheduler,
concurrency: {
mode: "singleFlight",
key: ({ environmentId, input }) =>
JSON.stringify([environmentId, input.connectionId, input.requestId]),
key: ({ environmentId, input }) => JSON.stringify([environmentId, input.requestId]),
},
}),
focusAutomationHost: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:automation-focus-host",
tag: WS_METHODS.previewAutomationFocusHost,
reportAutomationOwner: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:automation-report-owner",
tag: WS_METHODS.previewAutomationReportOwner,
scheduler: automationScheduler,
concurrency: {
mode: "latest",
key: previewAutomationHostFocusConcurrencyKey,
mode: "serial",
key: ({ environmentId, input }) => JSON.stringify([environmentId, input.clientId]),
},
}),
clearAutomationOwner: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:automation-clear-owner",
tag: WS_METHODS.previewAutomationClearOwner,
scheduler: automationScheduler,
concurrency: {
mode: "serial",
key: ({ environmentId, input }) => JSON.stringify([environmentId, input.clientId]),
},
}),
};
+7 -8
View File
@@ -69,20 +69,19 @@ import type {
PreviewOpenInput,
PreviewRefreshInput,
PreviewReportStatusInput,
PreviewResizeInput,
PreviewSessionSnapshot,
} from "./preview.ts";
import {
PreviewAutomationClickInput,
PreviewAutomationEvaluateInput,
PreviewAutomationHost,
PreviewAutomationHostFocus,
PreviewAutomationOwner,
PreviewAutomationOwnerIdentity,
PreviewAutomationPressInput,
PreviewAutomationRequest,
PreviewAutomationResponse,
PreviewAutomationScrollInput,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
PreviewAutomationStreamEvent,
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "./previewAutomation.ts";
@@ -1155,19 +1154,19 @@ export interface EnvironmentApi {
preview: {
open: (input: typeof PreviewOpenInput.Encoded) => Promise<PreviewSessionSnapshot>;
navigate: (input: typeof PreviewNavigateInput.Encoded) => Promise<PreviewSessionSnapshot>;
resize: (input: typeof PreviewResizeInput.Encoded) => Promise<PreviewSessionSnapshot>;
refresh: (input: typeof PreviewRefreshInput.Encoded) => Promise<void>;
close: (input: typeof PreviewCloseInput.Encoded) => Promise<void>;
list: (input: typeof PreviewListInput.Encoded) => Promise<PreviewListResult>;
reportStatus: (input: typeof PreviewReportStatusInput.Encoded) => Promise<void>;
automation: {
connect: (
input: PreviewAutomationHost,
callback: (event: PreviewAutomationStreamEvent) => void,
input: { clientId: string },
callback: (request: PreviewAutomationRequest) => void,
options?: { onResubscribe?: () => void },
) => () => void;
respond: (response: PreviewAutomationResponse) => Promise<void>;
focusHost: (input: PreviewAutomationHostFocus) => Promise<void>;
reportOwner: (owner: PreviewAutomationOwner) => Promise<void>;
clearOwner: (input: PreviewAutomationOwnerIdentity) => Promise<void>;
};
onEvent: (
callback: (event: PreviewEvent) => void,
-144
View File
@@ -6,26 +6,12 @@ import {
PreviewEvent,
PreviewNavStatus,
PreviewSessionSnapshot,
PreviewViewportSetting,
} from "./preview.ts";
import {
PreviewAutomationHost,
PreviewAutomationError,
PreviewAutomationResizeInput,
PreviewAutomationResizeResult,
PreviewAutomationStatus,
} from "./previewAutomation.ts";
const decodePreviewEvent = Schema.decodeUnknownSync(PreviewEvent);
const decodeSnapshot = Schema.decodeUnknownSync(PreviewSessionSnapshot);
const decodeNavStatus = Schema.decodeUnknownSync(PreviewNavStatus);
const decodeServer = Schema.decodeUnknownSync(DiscoveredLocalServer);
const decodeViewport = Schema.decodeUnknownSync(PreviewViewportSetting);
const decodeResizeInput = Schema.decodeUnknownSync(PreviewAutomationResizeInput);
const decodeResizeResult = Schema.decodeUnknownSync(PreviewAutomationResizeResult);
const decodeAutomationHost = Schema.decodeUnknownSync(PreviewAutomationHost);
const decodeAutomationError = Schema.decodeUnknownSync(PreviewAutomationError);
const decodeAutomationStatus = Schema.decodeUnknownSync(PreviewAutomationStatus);
describe("PreviewNavStatus", () => {
it("decodes Idle", () => {
@@ -82,117 +68,6 @@ describe("PreviewSessionSnapshot", () => {
});
});
describe("PreviewViewportSetting", () => {
it("decodes fill, freeform, and preset modes", () => {
expect(decodeViewport({ _tag: "fill" })).toEqual({ _tag: "fill" });
expect(decodeViewport({ _tag: "freeform", width: 1024, height: 768 })).toEqual({
_tag: "freeform",
width: 1024,
height: 768,
});
expect(
decodeViewport({
_tag: "preset",
presetId: "iphone-15-pro",
width: 393,
height: 852,
}),
).toMatchObject({ _tag: "preset", presetId: "iphone-15-pro" });
});
it("rejects unsafe dimensions and oversized render areas", () => {
expect(() => decodeViewport({ _tag: "freeform", width: 100, height: 800 })).toThrow();
expect(() => decodeViewport({ _tag: "freeform", width: 3840, height: 3840 })).toThrow();
});
});
describe("PreviewAutomationResizeInput", () => {
it("requires fields that match the selected mode", () => {
expect(decodeResizeInput({ mode: "fill" })).toEqual({ mode: "fill" });
expect(
decodeResizeInput({ mode: "preset", preset: "pixel-7", orientation: "landscape" }),
).toMatchObject({ mode: "preset", preset: "pixel-7" });
expect(() => decodeResizeInput({ mode: "preset", preset: "pixel-8" })).toThrow();
expect(() => decodeResizeInput({ mode: "freeform", width: 1024 })).toThrow();
expect(() => decodeResizeInput({ mode: "fill", width: 1024, height: 768 })).toThrow();
});
it("allows fill-mode measurements below the minimum selectable fixed size", () => {
expect(
decodeResizeResult({
tabId: "preview-t",
setting: { _tag: "fill" },
viewport: { width: 180, height: 120 },
}).viewport,
).toEqual({ width: 180, height: 120 });
});
});
describe("PreviewAutomationHost", () => {
it("accepts legacy hosts and current operation advertisements", () => {
expect(decodeAutomationHost({ clientId: "legacy", environmentId: "environment-1" })).toEqual({
clientId: "legacy",
environmentId: "environment-1",
});
expect(
decodeAutomationHost({
clientId: "current",
environmentId: "environment-1",
supportedOperations: ["status", "resize"],
}).supportedOperations,
).toEqual(["status", "resize"]);
});
});
describe("PreviewAutomationError", () => {
it("preserves a typed non-editable target failure", () => {
const error = decodeAutomationError({
_tag: "PreviewAutomationTargetNotEditableError",
operation: "type",
environmentId: "environment-1",
threadId: "thread-1",
providerSessionId: "provider-session-1",
providerInstanceId: "codex",
clientId: "client-1",
connectionId: "connection-1",
requestId: "request-1",
tabId: "tab-1",
timeoutMs: 1_000,
remoteTag: "PreviewAutomationTargetNotEditableError",
remoteMessageLength: 12,
cause: {},
selectorKind: "focused-element",
});
expect(error._tag).toBe("PreviewAutomationTargetNotEditableError");
if (error._tag === "PreviewAutomationTargetNotEditableError") {
expect(error.selectorKind).toBe("focused-element");
expect(error.message).toBe("Preview automation type requires an editable focused element.");
}
});
});
describe("PreviewAutomationStatus", () => {
it("accepts old hosts without viewport data and exposes it from current hosts", () => {
const base = {
available: true,
visible: false,
tabId: "preview-t",
url: "https://example.com",
title: "Example",
loading: false,
};
expect(decodeAutomationStatus(base)).toEqual(base);
expect(
decodeAutomationStatus({
...base,
viewportSetting: { _tag: "preset", presetId: "pixel-8", width: 412, height: 915 },
viewport: { width: 412, height: 915 },
}).viewport,
).toEqual({ width: 412, height: 915 });
});
});
describe("PreviewEvent", () => {
it("decodes opened", () => {
const event = decodePreviewEvent({
@@ -229,25 +104,6 @@ describe("PreviewEvent", () => {
}
});
it("decodes resized with tab viewport state", () => {
const event = decodePreviewEvent({
type: "resized",
threadId: "t",
tabId: "preview-t",
createdAt: "2026-01-01T00:00:00.000Z",
snapshot: {
threadId: "t",
tabId: "preview-t",
navStatus: { _tag: "Idle" },
canGoBack: false,
canGoForward: false,
viewport: { _tag: "freeform", width: 1024, height: 768 },
updatedAt: "2026-01-01T00:00:00.000Z",
},
});
expect(event.type).toBe("resized");
});
it("decodes closed without snapshot", () => {
const event = decodePreviewEvent({
type: "closed",
-110
View File
@@ -17,100 +17,6 @@ const Title = Schema.String.check(Schema.isMaxLength(512));
export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
export type PreviewTabId = typeof PreviewTabId.Type;
export const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;
export const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;
export const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;
const PreviewViewportDimension = Schema.Int.check(
Schema.isBetween({
minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,
maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,
}),
);
const viewportAreaFilter = Schema.makeFilter(
({ width, height }: { readonly width: number; readonly height: number }) =>
width * height <= PREVIEW_VIEWPORT_MAX_AREA ||
`Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,
);
export const PreviewViewportSize = Schema.Struct({
width: PreviewViewportDimension,
height: PreviewViewportDimension,
}).check(viewportAreaFilter);
export type PreviewViewportSize = typeof PreviewViewportSize.Type;
/**
* The page's measured viewport can be smaller than the minimum selectable
* fixed size while fill mode follows a narrow panel. Keep measurement
* validation separate from the stricter user-selectable size constraints.
*/
export const PreviewRenderedViewportSize = Schema.Struct({
width: Schema.Int.check(Schema.isGreaterThan(0)),
height: Schema.Int.check(Schema.isGreaterThan(0)),
});
export type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;
export const PREVIEW_VIEWPORT_PRESET_IDS = [
"iphone-se",
"iphone-xr",
"iphone-12-pro",
"iphone-14-pro-max",
"pixel-7",
"samsung-galaxy-s8-plus",
"samsung-galaxy-s20-ultra",
"ipad-mini",
"ipad-air",
"ipad-pro",
"surface-pro-7",
"surface-duo",
"galaxy-z-fold-5",
"asus-zenbook-fold",
"samsung-galaxy-a51-71",
"nest-hub",
"nest-hub-max",
] as const;
export const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);
export type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;
/**
* Preset IDs shipped before the Chrome-compatible catalog. Existing sessions
* can still reconnect with these values, but new resize requests only expose
* PREVIEW_VIEWPORT_PRESET_IDS.
*/
const LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [
"desktop-1920x1080",
"desktop-1440x900",
"laptop-1366x768",
"laptop-1280x800",
"ipad-pro-11",
"iphone-15-pro",
"pixel-8",
"galaxy-s24",
] as const;
const StoredPreviewViewportPresetId = Schema.Literals([
...PREVIEW_VIEWPORT_PRESET_IDS,
...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,
]);
export const PreviewViewportSetting = Schema.Union([
Schema.TaggedStruct("fill", {}),
Schema.TaggedStruct("freeform", {
...PreviewViewportSize.fields,
}).check(viewportAreaFilter),
Schema.TaggedStruct("preset", {
...PreviewViewportSize.fields,
presetId: StoredPreviewViewportPresetId,
}).check(viewportAreaFilter),
]);
export type PreviewViewportSetting = typeof PreviewViewportSetting.Type;
export const FILL_PREVIEW_VIEWPORT = {
_tag: "fill",
} as const satisfies PreviewViewportSetting;
export const PreviewNavStatus = Schema.Union([
Schema.TaggedStruct("Idle", {}),
Schema.TaggedStruct("Loading", {
@@ -136,8 +42,6 @@ export const PreviewSessionSnapshot = Schema.Struct({
navStatus: PreviewNavStatus,
canGoBack: Schema.Boolean,
canGoForward: Schema.Boolean,
/** Missing snapshots from older servers are treated as fill-panel mode. */
viewport: Schema.optional(PreviewViewportSetting),
updatedAt: Schema.String,
});
export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
@@ -172,13 +76,6 @@ export const PreviewRefreshInput = Schema.Struct({
});
export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
export const PreviewResizeInput = Schema.Struct({
threadId: ThreadId,
tabId: PreviewTabId,
viewport: PreviewViewportSetting,
});
export type PreviewResizeInput = typeof PreviewResizeInput.Type;
export const PreviewCloseInput = Schema.Struct({
threadId: ThreadId,
tabId: Schema.optional(PreviewTabId),
@@ -213,12 +110,6 @@ const PreviewNavigatedEvent = Schema.Struct({
snapshot: PreviewSessionSnapshot,
});
const PreviewResizedEvent = Schema.Struct({
...PreviewEventBaseSchema.fields,
type: Schema.Literal("resized"),
snapshot: PreviewSessionSnapshot,
});
const PreviewFailedEvent = Schema.Struct({
...PreviewEventBaseSchema.fields,
type: Schema.Literal("failed"),
@@ -236,7 +127,6 @@ const PreviewClosedEvent = Schema.Struct({
export const PreviewEvent = Schema.Union([
PreviewOpenedEvent,
PreviewNavigatedEvent,
PreviewResizedEvent,
PreviewFailedEvent,
PreviewClosedEvent,
]);
+31 -162
View File
@@ -1,14 +1,7 @@
import { Schema } from "effect";
import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import {
PREVIEW_VIEWPORT_MAX_AREA,
PreviewRenderedViewportSize,
PreviewTabId,
PreviewViewportPresetId,
PreviewViewportSetting,
PreviewViewportSize,
} from "./preview.ts";
import { PreviewTabId } from "./preview.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
const BoundedUrl = Schema.String.check(Schema.isTrimmed())
@@ -25,8 +18,7 @@ const OptionalTimeoutMs = Schema.optional(
.annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." }),
).annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." });
/** Operations understood by desktop hosts predating viewport resizing. */
export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
export const PreviewAutomationOperation = Schema.Literals([
"status",
"open",
"navigate",
@@ -39,15 +31,7 @@ export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
"waitFor",
"recordingStart",
"recordingStop",
] as const;
/** Advertised by current desktop hosts for mixed-version routing. */
export const PREVIEW_AUTOMATION_OPERATIONS = [
...PREVIEW_AUTOMATION_V1_OPERATIONS,
"resize",
] as const;
export const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_OPERATIONS);
]);
export type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;
export const PreviewAutomationStatus = Schema.Struct({
@@ -57,10 +41,6 @@ export const PreviewAutomationStatus = Schema.Struct({
url: Schema.NullOr(Schema.String),
title: Schema.NullOr(Schema.String),
loading: Schema.Boolean,
/** Optional for compatibility with desktop hosts predating viewport sizing. */
viewportSetting: Schema.optional(PreviewViewportSetting),
/** Measured guest-page viewport in CSS pixels when a webview is ready. */
viewport: Schema.optional(PreviewRenderedViewportSize),
});
export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
@@ -154,80 +134,6 @@ export const PreviewAutomationNavigateInput = Schema.Struct({
});
export type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;
export const PreviewAutomationResizeInput = Schema.Struct({
mode: Schema.Literals(["fill", "freeform", "preset"]).annotate({
description:
"Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.",
}),
preset: Schema.optional(
PreviewViewportPresetId.annotate({
description: "Named viewport from Chrome DevTools' standard device catalog.",
}),
).annotate({
description: "Named device size. Required only when mode is preset.",
}),
width: Schema.optional(
PreviewViewportSize.fields.width.annotate({
description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
}),
).annotate({
description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
}),
height: Schema.optional(
PreviewViewportSize.fields.height.annotate({
description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
}),
).annotate({
description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
}),
orientation: Schema.optional(
Schema.Literals(["portrait", "landscape"]).annotate({
description:
"Orientation for a fixed device preset. Defaults to the preset's native orientation.",
}),
).annotate({
description:
"Orientation for a named device preset. It is not accepted in fill or freeform mode.",
}),
timeoutMs: OptionalTimeoutMs,
})
.check(
Schema.makeFilter((input) => {
const hasPreset = input.preset !== undefined;
const hasWidth = input.width !== undefined;
const hasHeight = input.height !== undefined;
if (hasWidth !== hasHeight) return "Custom dimensions require both width and height.";
if (input.mode === "fill") {
return !hasPreset && !hasWidth && input.orientation === undefined
? true
: "Fill mode does not accept a preset, dimensions, or orientation.";
}
if (input.mode === "freeform") {
if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {
return "Freeform mode requires width and height and does not accept a preset or orientation.";
}
} else if (!hasPreset || hasWidth || hasHeight) {
return "Preset mode requires a preset and does not accept custom dimensions.";
}
if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {
return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;
}
return true;
}),
)
.annotate({
description:
"Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.",
});
export type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;
export const PreviewAutomationResizeResult = Schema.Struct({
tabId: PreviewTabId,
setting: PreviewViewportSetting,
viewport: PreviewRenderedViewportSize,
});
export type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;
const Locator = TrimmedNonEmptyString.annotate({
description:
"Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.",
@@ -505,33 +411,21 @@ export const PreviewAutomationRecordingArtifact = Schema.Struct({
});
export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
export const PreviewAutomationHostIdentity = Schema.Struct({
clientId: PreviewAutomationClientId,
export const PreviewAutomationOwnerIdentity = Schema.Struct({
clientId: TrimmedNonEmptyString,
environmentId: EnvironmentId,
threadId: ThreadId,
});
export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
export type PreviewAutomationOwnerIdentity = typeof PreviewAutomationOwnerIdentity.Type;
export const PreviewAutomationHost = Schema.Struct({
...PreviewAutomationHostIdentity.fields,
/**
* Missing means the pre-capability-negotiation V1 operation set. This lets
* a newer server safely coexist with an older desktop during rollout.
*/
supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
export const PreviewAutomationOwner = Schema.Struct({
...PreviewAutomationOwnerIdentity.fields,
tabId: Schema.NullOr(PreviewTabId),
visible: Schema.Boolean,
supportsAutomation: Schema.Boolean,
focusedAt: Schema.String,
});
export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
export const PreviewAutomationHostFocus = Schema.Struct({
...PreviewAutomationHostIdentity.fields,
connectionId: PreviewAutomationConnectionId,
focused: Schema.Boolean,
});
export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
export type PreviewAutomationOwner = typeof PreviewAutomationOwner.Type;
export const PreviewAutomationRequest = Schema.Struct({
requestId: TrimmedNonEmptyString,
@@ -543,22 +437,7 @@ export const PreviewAutomationRequest = Schema.Struct({
});
export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
export const PreviewAutomationStreamEvent = Schema.Union([
Schema.Struct({
type: Schema.Literal("connected"),
connectionId: PreviewAutomationConnectionId,
}),
Schema.Struct({
type: Schema.Literal("request"),
connectionId: PreviewAutomationConnectionId,
request: PreviewAutomationRequest,
}),
]);
export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
export const PreviewAutomationResponse = Schema.Struct({
clientId: PreviewAutomationClientId,
connectionId: PreviewAutomationConnectionId,
requestId: TrimmedNonEmptyString,
ok: Schema.Boolean,
result: Schema.optional(Schema.Unknown),
@@ -598,7 +477,6 @@ const PreviewAutomationScopeErrorFields = {
const PreviewAutomationRequestErrorFields = {
...PreviewAutomationScopeErrorFields,
clientId: TrimmedNonEmptyString,
connectionId: PreviewAutomationConnectionId,
requestId: TrimmedNonEmptyString,
tabId: Schema.optional(PreviewTabId),
timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
@@ -622,12 +500,11 @@ const PreviewAutomationOptionalRemoteDiagnosticFields = {
cause: Schema.optional(Schema.Defect()),
};
export class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorClass<PreviewAutomationNoAvailableHostError>()(
"PreviewAutomationNoAvailableHostError",
export class PreviewAutomationNoFocusedOwnerError extends Schema.TaggedErrorClass<PreviewAutomationNoFocusedOwnerError>()(
"PreviewAutomationNoFocusedOwnerError",
{
...PreviewAutomationScopeErrorFields,
clientId: Schema.optional(TrimmedNonEmptyString),
connectionId: Schema.optional(PreviewAutomationConnectionId),
requestId: Schema.optional(TrimmedNonEmptyString),
tabId: Schema.optional(PreviewTabId),
timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
@@ -635,7 +512,7 @@ export class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorCla
},
) {
override get message(): string {
const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;
const summary = `No focused preview automation owner is available for ${this.operation} in thread ${this.threadId}.`;
return summary;
}
}
@@ -721,26 +598,6 @@ export class PreviewAutomationInvalidSelectorError extends Schema.TaggedErrorCla
}
}
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
"PreviewAutomationTargetNotEditableError",
{
...PreviewAutomationRequestErrorFields,
...PreviewAutomationRemoteDiagnosticFields,
selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
},
) {
override get message(): string {
if (this.selectorKind === "focused-element") {
return `Preview automation ${this.operation} requires an editable focused element.`;
}
if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
}
return `Preview automation ${this.operation} requires an editable target.`;
}
}
export class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClass<PreviewAutomationResultTooLargeError>()(
"PreviewAutomationResultTooLargeError",
{
@@ -758,6 +615,18 @@ export class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClas
}
}
export class PreviewAutomationHostNotConnectedError extends Schema.TaggedErrorClass<PreviewAutomationHostNotConnectedError>()(
"PreviewAutomationHostNotConnectedError",
{
...PreviewAutomationScopeErrorFields,
clientId: TrimmedNonEmptyString,
},
) {
override get message(): string {
return `Preview automation host ${this.clientId} is not connected for ${this.operation}.`;
}
}
export class PreviewAutomationClientDisconnectedError extends Schema.TaggedErrorClass<PreviewAutomationClientDisconnectedError>()(
"PreviewAutomationClientDisconnectedError",
PreviewAutomationRequestErrorFields,
@@ -799,15 +668,15 @@ export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorC
export const PreviewAutomationError = Schema.Union([
PreviewAutomationUnavailableError,
PreviewAutomationNoAvailableHostError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationUnsupportedClientError,
PreviewAutomationTabNotFoundError,
PreviewAutomationTimeoutError,
PreviewAutomationControlInterruptedError,
PreviewAutomationExecutionError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationResultTooLargeError,
PreviewAutomationHostNotConnectedError,
PreviewAutomationClientDisconnectedError,
PreviewAutomationRequestQueueClosedError,
PreviewAutomationRemoteUnavailableError,
+17 -19
View File
@@ -103,15 +103,14 @@ import {
PreviewOpenInput,
PreviewRefreshInput,
PreviewReportStatusInput,
PreviewResizeInput,
PreviewSessionSnapshot,
} from "./preview.ts";
import {
PreviewAutomationError,
PreviewAutomationHost,
PreviewAutomationHostFocus,
PreviewAutomationOwner,
PreviewAutomationOwnerIdentity,
PreviewAutomationRequest,
PreviewAutomationResponse,
PreviewAutomationStreamEvent,
} from "./previewAutomation.ts";
import {
ServerConfigStreamEvent,
@@ -191,14 +190,14 @@ export const WS_METHODS = {
// Preview methods
previewOpen: "preview.open",
previewNavigate: "preview.navigate",
previewResize: "preview.resize",
previewRefresh: "preview.refresh",
previewClose: "preview.close",
previewList: "preview.list",
previewReportStatus: "preview.reportStatus",
previewAutomationConnect: "previewAutomation.connect",
previewAutomationRespond: "previewAutomation.respond",
previewAutomationFocusHost: "previewAutomation.focusHost",
previewAutomationReportOwner: "previewAutomation.reportOwner",
previewAutomationClearOwner: "previewAutomation.clearOwner",
// Server meta
serverGetConfig: "server.getConfig",
@@ -529,12 +528,6 @@ export const WsPreviewNavigateRpc = Rpc.make(WS_METHODS.previewNavigate, {
error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),
});
export const WsPreviewResizeRpc = Rpc.make(WS_METHODS.previewResize, {
payload: PreviewResizeInput,
success: PreviewSessionSnapshot,
error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),
});
export const WsPreviewRefreshRpc = Rpc.make(WS_METHODS.previewRefresh, {
payload: PreviewRefreshInput,
error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),
@@ -557,8 +550,8 @@ export const WsPreviewReportStatusRpc = Rpc.make(WS_METHODS.previewReportStatus,
});
export const WsPreviewAutomationConnectRpc = Rpc.make(WS_METHODS.previewAutomationConnect, {
payload: PreviewAutomationHost,
success: PreviewAutomationStreamEvent,
payload: PreviewAutomationOwner,
success: PreviewAutomationRequest,
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
stream: true,
});
@@ -568,9 +561,14 @@ export const WsPreviewAutomationRespondRpc = Rpc.make(WS_METHODS.previewAutomati
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
});
export const WsPreviewAutomationFocusHostRpc = Rpc.make(WS_METHODS.previewAutomationFocusHost, {
payload: PreviewAutomationHostFocus,
error: EnvironmentAuthorizationError,
export const WsPreviewAutomationReportOwnerRpc = Rpc.make(WS_METHODS.previewAutomationReportOwner, {
payload: PreviewAutomationOwner,
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
});
export const WsPreviewAutomationClearOwnerRpc = Rpc.make(WS_METHODS.previewAutomationClearOwner, {
payload: PreviewAutomationOwnerIdentity,
error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),
});
export const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, {
@@ -730,14 +728,14 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeTerminalMetadataRpc,
WsPreviewOpenRpc,
WsPreviewNavigateRpc,
WsPreviewResizeRpc,
WsPreviewRefreshRpc,
WsPreviewCloseRpc,
WsPreviewListRpc,
WsPreviewReportStatusRpc,
WsPreviewAutomationConnectRpc,
WsPreviewAutomationRespondRpc,
WsPreviewAutomationFocusHostRpc,
WsPreviewAutomationReportOwnerRpc,
WsPreviewAutomationClearOwnerRpc,
WsSubscribePreviewEventsRpc,
WsSubscribeDiscoveredLocalServersRpc,
WsSubscribeServerConfigRpc,
+1 -128
View File
@@ -17,59 +17,18 @@ import { it, assert } from "@effect/vitest";
import * as AcpClient from "./client.ts";
import * as AcpSchema from "./_generated/schema.gen.ts";
import * as AcpError from "./errors.ts";
import {
encodeJsonl,
jsonRpcNotification,
jsonRpcRequest,
jsonRpcResponse,
} from "./_internal/shared.ts";
import { encodeJsonl, jsonRpcRequest, jsonRpcResponse } from "./_internal/shared.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
const XAiPromptCompleteNotification = jsonRpcNotification(
"_x.ai/session/prompt_complete",
Schema.Struct({
sessionId: Schema.String,
promptId: Schema.String,
stopReason: Schema.String,
agentResult: Schema.NullOr(Schema.Unknown),
}),
);
const XAiQueueChangedNotification = jsonRpcNotification(
"_x.ai/queue/changed",
Schema.Struct({
sessionId: Schema.String,
entries: Schema.Array(Schema.Unknown),
}),
);
const XAiSessionsChangedNotification = jsonRpcNotification(
"_x.ai/sessions/changed",
Schema.Struct({
upserted: Schema.Array(Schema.Unknown),
removed: Schema.Array(Schema.Unknown),
}),
);
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
);
const mockPeerArgs = (path: string) => [path];
function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
let offset = 0;
for (const chunk of chunks) {
batch.set(chunk, offset);
offset += chunk.length;
}
return batch;
}
it.layer(NodeServices.layer)("effect-acp client", (it) => {
const makeHandle = (env?: Record<string, string>) =>
Effect.gen(function* () {
@@ -487,90 +446,4 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
yield* Scope.close(scope, Exit.void);
}),
);
it.effect(
"routes a standard prompt response after Grok extension notifications in the same batch",
() =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const scope = yield* Scope.make();
const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
const promptFiber = yield* acp.agent
.prompt({
sessionId: "grok-session-1",
prompt: [{ type: "text", text: "run the ls command" }],
})
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
const decodedPrompt = yield* decodePromptRequestLine(outbound);
const responseBatch = concatBytes(
yield* Effect.all([
encodeJsonl(XAiQueueChangedNotification, {
jsonrpc: "2.0",
method: "_x.ai/queue/changed",
params: { sessionId: "grok-session-1", entries: [] },
}),
encodeJsonl(XAiPromptCompleteNotification, {
jsonrpc: "2.0",
method: "_x.ai/session/prompt_complete",
params: {
sessionId: "grok-session-1",
promptId: "prompt-1",
stopReason: "end_turn",
agentResult: null,
},
}),
encodeJsonl(XAiSessionsChangedNotification, {
jsonrpc: "2.0",
method: "_x.ai/sessions/changed",
params: {
upserted: [
{
sessionId: "grok-session-1",
title: null,
cwd: process.cwd(),
isWorktree: false,
modelId: "grok-composer-2.5-fast",
yolo: false,
activity: "idle",
resident: true,
lastChangeUnixMs: 1_710_000_000_000,
origin: { kind: "local" },
},
],
removed: [],
},
}),
encodeJsonl(PromptResponse, {
jsonrpc: "2.0",
id: decodedPrompt.id,
result: {
stopReason: "end_turn",
_meta: {
sessionId: "grok-session-1",
requestId: "prompt-1",
promptId: "prompt-1",
modelId: "grok-composer-2.5-fast",
},
},
}),
]),
);
yield* Queue.offer(input, responseBatch);
assert.deepEqual(yield* Fiber.join(promptFiber), {
stopReason: "end_turn",
_meta: {
sessionId: "grok-session-1",
requestId: "prompt-1",
promptId: "prompt-1",
modelId: "grok-composer-2.5-fast",
},
});
yield* Scope.close(scope, Exit.void);
}),
);
});
-4
View File
@@ -163,10 +163,6 @@
"types": "./src/preview.ts",
"import": "./src/preview.ts"
},
"./previewViewport": {
"types": "./src/previewViewport.ts",
"import": "./src/previewViewport.ts"
},
"./filePreview": {
"types": "./src/filePreview.ts",
"import": "./src/filePreview.ts"
@@ -1,70 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
PREVIEW_VIEWPORT_PRESETS,
previewViewportLabel,
previewViewportPresetOrientation,
resolvePreviewViewport,
} from "./previewViewport.ts";
describe("previewViewport", () => {
it("resolves fill and exact freeform viewports", () => {
expect(resolvePreviewViewport({ mode: "fill" })).toEqual({ _tag: "fill" });
expect(resolvePreviewViewport({ mode: "freeform", width: 1024, height: 768 })).toEqual({
_tag: "freeform",
width: 1024,
height: 768,
});
});
it("resolves device presets in either orientation", () => {
expect(resolvePreviewViewport({ mode: "preset", preset: "iphone-12-pro" })).toEqual({
_tag: "preset",
width: 390,
height: 844,
presetId: "iphone-12-pro",
});
expect(
resolvePreviewViewport({
mode: "preset",
preset: "iphone-12-pro",
orientation: "landscape",
}),
).toEqual({
_tag: "preset",
width: 844,
height: 390,
presetId: "iphone-12-pro",
});
});
it("matches Chrome's standard device catalog ordering", () => {
expect(PREVIEW_VIEWPORT_PRESETS.map((preset) => preset.label)).toEqual([
"iPhone SE",
"iPhone XR",
"iPhone 12 Pro",
"iPhone 14 Pro Max",
"Pixel 7",
"Samsung Galaxy S8+",
"Samsung Galaxy S20 Ultra",
"iPad Mini",
"iPad Air",
"iPad Pro",
"Surface Pro 7",
"Surface Duo",
"Galaxy Z Fold 5",
"Asus Zenbook Fold",
"Samsung Galaxy A51/71",
"Nest Hub",
"Nest Hub Max",
]);
});
it("formats settings for compact UI", () => {
expect(previewViewportLabel({ _tag: "fill" })).toBe("Fill panel");
expect(previewViewportLabel({ _tag: "freeform", width: 393, height: 852 })).toBe("393 × 852");
expect(previewViewportPresetOrientation({ _tag: "freeform", width: 852, height: 393 })).toBe(
"landscape",
);
});
});
-186
View File
@@ -1,186 +0,0 @@
import type {
PreviewAutomationResizeInput,
PreviewViewportPresetId,
PreviewViewportSetting,
} from "@t3tools/contracts";
import { PREVIEW_VIEWPORT_PRESET_IDS } from "@t3tools/contracts";
export interface PreviewViewportPreset {
readonly id: PreviewViewportPresetId;
readonly label: string;
readonly category: "Desktop" | "Tablet" | "Phone";
readonly detail: string;
readonly width: number;
readonly height: number;
}
type PreviewViewportPresetDefinition = Omit<PreviewViewportPreset, "id">;
// Keep this in Chrome DevTools' default-device order. Dimensions are CSS
// viewport sizes from Chromium's EmulatedDevices.ts standard catalog.
const PREVIEW_VIEWPORT_PRESET_DEFINITIONS = {
"iphone-se": {
label: "iPhone SE",
category: "Phone",
detail: "375 × 667",
width: 375,
height: 667,
},
"iphone-xr": {
label: "iPhone XR",
category: "Phone",
detail: "414 × 896",
width: 414,
height: 896,
},
"iphone-12-pro": {
label: "iPhone 12 Pro",
category: "Phone",
detail: "390 × 844",
width: 390,
height: 844,
},
"iphone-14-pro-max": {
label: "iPhone 14 Pro Max",
category: "Phone",
detail: "430 × 932",
width: 430,
height: 932,
},
"pixel-7": {
label: "Pixel 7",
category: "Phone",
detail: "412 × 915",
width: 412,
height: 915,
},
"samsung-galaxy-s8-plus": {
label: "Samsung Galaxy S8+",
category: "Phone",
detail: "360 × 740",
width: 360,
height: 740,
},
"samsung-galaxy-s20-ultra": {
label: "Samsung Galaxy S20 Ultra",
category: "Phone",
detail: "412 × 915",
width: 412,
height: 915,
},
"ipad-mini": {
label: "iPad Mini",
category: "Tablet",
detail: "768 × 1024",
width: 768,
height: 1024,
},
"ipad-air": {
label: "iPad Air",
category: "Tablet",
detail: "820 × 1180",
width: 820,
height: 1180,
},
"ipad-pro": {
label: "iPad Pro",
category: "Tablet",
detail: "1024 × 1366",
width: 1024,
height: 1366,
},
"surface-pro-7": {
label: "Surface Pro 7",
category: "Tablet",
detail: "912 × 1368",
width: 912,
height: 1368,
},
"surface-duo": {
label: "Surface Duo",
category: "Phone",
detail: "540 × 720",
width: 540,
height: 720,
},
"galaxy-z-fold-5": {
label: "Galaxy Z Fold 5",
category: "Phone",
detail: "344 × 882",
width: 344,
height: 882,
},
"asus-zenbook-fold": {
label: "Asus Zenbook Fold",
category: "Tablet",
detail: "853 × 1280",
width: 853,
height: 1280,
},
"samsung-galaxy-a51-71": {
label: "Samsung Galaxy A51/71",
category: "Phone",
detail: "412 × 914",
width: 412,
height: 914,
},
"nest-hub": {
label: "Nest Hub",
category: "Tablet",
detail: "1024 × 600",
width: 1024,
height: 600,
},
"nest-hub-max": {
label: "Nest Hub Max",
category: "Tablet",
detail: "1280 × 800",
width: 1280,
height: 800,
},
} as const satisfies Record<PreviewViewportPresetId, PreviewViewportPresetDefinition>;
export const PREVIEW_VIEWPORT_PRESETS: ReadonlyArray<PreviewViewportPreset> =
PREVIEW_VIEWPORT_PRESET_IDS.map((id) => ({
id,
...PREVIEW_VIEWPORT_PRESET_DEFINITIONS[id],
}));
export function resolvePreviewViewport(
input: PreviewAutomationResizeInput,
): PreviewViewportSetting {
if (input.mode === "fill") return { _tag: "fill" };
if (input.mode === "preset" && input.preset !== undefined) {
const preset = PREVIEW_VIEWPORT_PRESETS.find((candidate) => candidate.id === input.preset);
if (!preset) throw new Error(`Unknown preview viewport preset: ${input.preset}`);
const landscape = input.orientation === "landscape";
const portrait = input.orientation === "portrait";
const nativePortrait = preset.height >= preset.width;
const shouldSwap = (landscape && nativePortrait) || (portrait && !nativePortrait);
return {
_tag: "preset",
width: shouldSwap ? preset.height : preset.width,
height: shouldSwap ? preset.width : preset.height,
presetId: preset.id,
};
}
if (input.width === undefined || input.height === undefined) {
throw new Error("Custom preview viewport requires width and height");
}
return {
_tag: "freeform",
width: input.width,
height: input.height,
};
}
export function previewViewportLabel(viewport: PreviewViewportSetting): string {
return viewport._tag === "fill" ? "Fill panel" : `${viewport.width} × ${viewport.height}`;
}
export function previewViewportPresetOrientation(
viewport: PreviewViewportSetting,
): "portrait" | "landscape" | null {
if (viewport._tag === "fill" || viewport.width === viewport.height) return null;
return viewport.width > viewport.height ? "landscape" : "portrait";
}
+30 -1
View File
@@ -1,7 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it as effectIt } from "@effect/vitest";
import { assert, it as effectIt } from "@effect/vitest";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { describe, expect, it, vi } from "vite-plus/test";
import {
@@ -364,6 +366,33 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
expect(result._tag).toBe("Failure");
}),
);
it.effect("resolves POSIX commands only when the candidate is executable", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-shell-executable-",
});
const executablePath = path.join(directory, "tool");
const nonExecutablePath = path.join(directory, "not-a-tool");
yield* fileSystem.writeFileString(executablePath, "#!/bin/sh\n");
yield* fileSystem.writeFileString(nonExecutablePath, "#!/bin/sh\n");
yield* fileSystem.chmod(executablePath, 0o700);
yield* fileSystem.chmod(nonExecutablePath, 0o600);
const resolved = yield* resolveCommandPath("tool", {
env: { PATH: directory },
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
const nonExecutableResult = yield* resolveCommandPath("not-a-tool", {
env: { PATH: directory },
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.result);
assert.strictEqual(resolved, executablePath);
assert.strictEqual(nonExecutableResult._tag, "Failure");
}).pipe(Effect.scoped),
);
});
effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
+41 -3
View File
@@ -6,6 +6,7 @@ import * as NodeFS from "node:fs";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { HostProcessEnvironment, HostProcessPlatform } from "./hostProcess.ts";
@@ -17,6 +18,11 @@ const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
const WINDOWS_PATH_DELIMITER = ";";
const POSIX_PATH_DELIMITER = ":";
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
const POSIX_USER_EXECUTE_MODE = 0o100;
const POSIX_GROUP_EXECUTE_MODE = 0o010;
const POSIX_OTHER_EXECUTE_MODE = 0o001;
const POSIX_ANY_EXECUTE_MODE =
POSIX_USER_EXECUTE_MODE | POSIX_GROUP_EXECUTE_MODE | POSIX_OTHER_EXECUTE_MODE;
type ExecFileSyncLike = (
file: string,
@@ -33,6 +39,38 @@ function canExecuteFile(filePath: string): boolean {
}
}
function getCurrentUid(): number | undefined {
return typeof process.getuid === "function" ? process.getuid() : undefined;
}
function getCurrentGids(): ReadonlyArray<number> {
if (typeof process.getgid !== "function") return [];
const primaryGid = process.getgid();
const supplementaryGids = typeof process.getgroups === "function" ? process.getgroups() : [];
return Array.from(new Set([primaryGid, ...supplementaryGids]));
}
function canExecuteFileInfo(info: FileSystem.File.Info): boolean {
if ((info.mode & POSIX_ANY_EXECUTE_MODE) === 0) return false;
const uid = getCurrentUid();
if (uid === 0) return true;
if (uid !== undefined && Option.isSome(info.uid)) {
return info.uid.value === uid
? (info.mode & POSIX_USER_EXECUTE_MODE) !== 0
: canExecuteFileInfoForGroups(info);
}
return canExecuteFileInfoForGroups(info) || (info.mode & POSIX_ANY_EXECUTE_MODE) !== 0;
}
function canExecuteFileInfoForGroups(info: FileSystem.File.Info): boolean {
if (Option.isSome(info.gid) && getCurrentGids().includes(info.gid.value)) {
return (info.mode & POSIX_GROUP_EXECUTE_MODE) !== 0;
}
return (info.mode & POSIX_OTHER_EXECUTE_MODE) !== 0;
}
export interface CommandAvailabilityOptions {
readonly env?: NodeJS.ProcessEnv;
readonly extendEnv?: boolean;
@@ -498,8 +536,8 @@ const isExecutableFile = Effect.fn("shell.isExecutableFile")(function* (
): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
if (stat === null || stat.type !== "File") return false;
const stat = yield* fileSystem.stat(filePath).pipe(Effect.option);
if (Option.isNone(stat) || stat.value.type !== "File") return false;
if (platform === "win32") {
const extension = path.extname(filePath);
@@ -507,7 +545,7 @@ const isExecutableFile = Effect.fn("shell.isExecutableFile")(function* (
return windowsPathExtensions.includes(extension.toUpperCase());
}
return canExecuteFile(filePath);
return canExecuteFileInfo(stat.value);
});
const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
+725 -1094
View File
File diff suppressed because it is too large. Load diff
+8 -4
View File
@@ -27,11 +27,13 @@ catalog:
"@pierre/diffs": 1.3.0-beta.5
"@types/node": 24.12.4
"@typescript/native-preview": 7.0.0-dev.20260604.1
"@vitest/runner": 4.1.8
effect: 4.0.0-beta.78
jose: 6.2.2
typescript: ~6.0.3
vite: npm:@voidzero-dev/vite-plus-core@0.2.1
vite-plus: 0.2.1
vite: npm:@voidzero-dev/vite-plus-core@0.1.24
vite-plus: 0.1.24
vitest: npm:@voidzero-dev/[email protected]
yaml: ^2.9.0
ignoredBuiltDependencies:
@@ -68,14 +70,14 @@ overrides:
"@effect/sql-pg": "catalog:"
"@effect/sql-sqlite-bun": "catalog:"
"@effect/vitest": "catalog:"
# @effect/vitest is patched to use vite-plus/test; do not auto-install its
# upstream Vitest peer and create a second Vite/Vitest toolchain.
"@effect/vitest>@vitest/runner": "-"
"@effect/vitest>vitest": "-"
"@expo/metro-config": 56.0.13
"@pierre/diffs>@shikijs/transformers": ^4.2.0
"@types/node": "catalog:"
effect: "catalog:"
vite: "catalog:"
vitest: "catalog:"
yaml: "catalog:"
packageExtensions:
@@ -100,5 +102,7 @@ patchedDependencies:
peerDependencyRules:
allowAny:
- vite
- vitest
allowedVersions:
vite: "*"
vitest: "*"
-1
View File
@@ -253,7 +253,6 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
T3CODE_MODE: "web",
T3CODE_NO_BROWSER: "0",
T3CODE_HOST: "0.0.0.0",
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
VITE_WS_URL: "ws://localhost:13773",
},
serverOffset: 0,
+8 -5
View File
@@ -158,6 +158,12 @@ const optionalIntegerConfig = (name: string): Config.Config<number | undefined>
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const optionalUrlConfig = (name: string): Config.Config<URL | undefined> =>
Config.url(name).pipe(
Config.option,
Config.map((value) => Option.getOrUndefined(value)),
);
const OffsetConfig = Config.all({
portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
@@ -615,11 +621,8 @@ const devRunnerCli = Command.make("dev-runner", {
),
devUrl: Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription(
"Explicit web dev URL override (forwards to VITE_DEV_SERVER_URL). Ambient VITE_DEV_SERVER_URL values are ignored so a parent dev app cannot redirect the child runner.",
),
Flag.optional,
Flag.map(Option.getOrUndefined),
Flag.withDescription("Web dev URL override (forwards to VITE_DEV_SERVER_URL)."),
Flag.withFallbackConfig(optionalUrlConfig("VITE_DEV_SERVER_URL")),
),
dryRun: Flag.boolean("dry-run").pipe(
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),