Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87ff841023 | ||
|
|
4f4335b7f7 | ||
|
|
24abab789e | ||
|
|
52b04b947e | ||
|
|
e9ed70c5b9 | ||
|
|
ffae5410e8 | ||
|
|
31dfe3596e | ||
|
|
c2776c2336 | ||
|
|
22f021ed69 |
No files matched your search
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
|
||||
return `'${value.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
|
||||
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
|
||||
export function makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath,
|
||||
desktopRoot,
|
||||
environment,
|
||||
}) {
|
||||
const envEntries = [
|
||||
["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],
|
||||
["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],
|
||||
["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,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
|
||||
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
|
||||
"",
|
||||
].join("\n"),
|
||||
makeDevelopmentLauncherScript({
|
||||
electronBinaryPath,
|
||||
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
|
||||
desktopRoot: desktopDir,
|
||||
environment: process.env,
|
||||
}),
|
||||
);
|
||||
NodeFS.chmodSync(targetBinaryPath, 0o755);
|
||||
}
|
||||
@@ -286,6 +302,12 @@ 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
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,7 +43,16 @@ describe("ElectronProtocol", () => {
|
||||
assert.isDefined(handler);
|
||||
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
|
||||
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",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(yield* Effect.promise(() => response.text()), "ok");
|
||||
assert.include(
|
||||
@@ -70,6 +79,11 @@ 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)),
|
||||
);
|
||||
@@ -99,6 +113,34 @@ 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");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -114,18 +115,60 @@ 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: request.headers,
|
||||
headers,
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") {
|
||||
init.body = request.body;
|
||||
(init as RequestInit & { duplex: "half" }).duplex = "half";
|
||||
}
|
||||
const response = await Electron.net.fetch(targetUrl.toString(), init);
|
||||
const response =
|
||||
request.method === "GET" || request.method === "HEAD"
|
||||
? await fetchWithTransientRetry(targetUrl.toString(), init)
|
||||
: 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);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
@@ -18,16 +19,25 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
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(),
|
||||
}));
|
||||
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(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
clipboard: {
|
||||
@@ -44,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
webContents: {
|
||||
fromId,
|
||||
getFocusedWebContents,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -81,6 +92,7 @@ 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);
|
||||
|
||||
@@ -97,6 +109,8 @@ const withManager = <A>(
|
||||
describe("PreviewManager", () => {
|
||||
beforeEach(() => {
|
||||
fromId.mockClear();
|
||||
getFocusedWebContents.mockReset();
|
||||
getFocusedWebContents.mockReturnValue(null);
|
||||
mkdir.mockClear();
|
||||
writeFile.mockClear();
|
||||
showItemInFolder.mockClear();
|
||||
@@ -250,6 +264,197 @@ 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* () {
|
||||
@@ -511,6 +716,178 @@ 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* () {
|
||||
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import {
|
||||
type BrowserWindow,
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -378,6 +380,7 @@ 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>();
|
||||
@@ -854,11 +857,24 @@ 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) => Effect.Effect<A, PreviewManagerError>,
|
||||
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
|
||||
) {
|
||||
const sequence = yield* nextCounter(actionSequenceRef);
|
||||
const startedAt = yield* currentIso;
|
||||
@@ -899,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result;
|
||||
},
|
||||
);
|
||||
return yield* use(send);
|
||||
// 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);
|
||||
});
|
||||
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
|
||||
exit: Exit.Exit<A, PreviewManagerError>,
|
||||
@@ -1091,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
yield* update(tabId, {
|
||||
navStatus: computeNavStatus(wc),
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
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;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState());
|
||||
const failed = (_event: Event, code: number, description: string): void => {
|
||||
if (code === -3) return;
|
||||
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;
|
||||
runFork(
|
||||
update(tabId, {
|
||||
navStatus: {
|
||||
kind: "LoadFailed",
|
||||
url: wc.getURL(),
|
||||
url: validatedUrl || wc.getURL(),
|
||||
title: wc.getTitle(),
|
||||
code,
|
||||
description,
|
||||
@@ -1161,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.off("did-navigate", sync);
|
||||
wc.off("did-navigate-in-page", sync);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
@@ -1173,8 +1244,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", sync);
|
||||
wc.on("did-navigate-in-page", sync);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
@@ -1280,21 +1351,40 @@ 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;
|
||||
}
|
||||
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(tab.webContentsId),
|
||||
detachListeners(tab.webContentsId),
|
||||
detachControlSession(replacedWebContentsId),
|
||||
detachListeners(replacedWebContentsId),
|
||||
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;
|
||||
@@ -1313,6 +1403,7 @@ 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 [
|
||||
@@ -1330,11 +1421,6 @@ 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),
|
||||
);
|
||||
@@ -1946,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationClickInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
yield* Effect.all(
|
||||
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
|
||||
{ concurrency: 2, discard: true },
|
||||
);
|
||||
yield* prepareAutomationInput(send, true);
|
||||
const point = yield* resolveClickPoint(tabId, send, input);
|
||||
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
|
||||
tabId,
|
||||
@@ -2011,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
|
||||
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
|
||||
tabId: string,
|
||||
send: SendCommand,
|
||||
input: PreviewAutomationTypeInput,
|
||||
@@ -2021,8 +2104,15 @@ 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 } | { notFound: true }
|
||||
| { ok: true }
|
||||
| { invalidSelector: true; message: string }
|
||||
| { notEditable: true }
|
||||
| { notFound: true }
|
||||
>(
|
||||
tabId,
|
||||
send,
|
||||
@@ -2030,12 +2120,54 @@ 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 (${input.clear ?? false}) {
|
||||
if ("value" in element) element.value = "";
|
||||
else if (element.isContentEditable) element.textContent = "";
|
||||
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
|
||||
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);
|
||||
}
|
||||
}
|
||||
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) };
|
||||
@@ -2059,6 +2191,12 @@ 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* (
|
||||
@@ -2066,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationTypeInput,
|
||||
send: SendCommand,
|
||||
) {
|
||||
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,
|
||||
);
|
||||
// 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);
|
||||
});
|
||||
|
||||
const automationType = Effect.fn("PreviewManager.automationType")(function* (
|
||||
@@ -2097,32 +2222,54 @@ 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,
|
||||
) {
|
||||
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* 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);
|
||||
}
|
||||
}, 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 });
|
||||
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));
|
||||
});
|
||||
|
||||
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
|
||||
@@ -2130,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
input: PreviewAutomationPressInput,
|
||||
) {
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* withControlSession(tabId, wc, "press", (send) =>
|
||||
performAutomationPress(tabId, input, send),
|
||||
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
|
||||
performAutomationPress(tabId, wc, input, send, sendCleanup),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2529,6 +2676,20 @@ 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",
|
||||
{
|
||||
@@ -2631,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
|
||||
PreviewAutomationDebuggerAttachedError,
|
||||
PreviewAutomationEvaluationError,
|
||||
PreviewAutomationTargetNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationCoordinatesOutsideViewportError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
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,6 +4,7 @@ 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";
|
||||
@@ -47,12 +48,14 @@ 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(),
|
||||
@@ -79,6 +82,7 @@ function makeFakeBrowserWindow() {
|
||||
window: window as unknown as Electron.BrowserWindow,
|
||||
loadURL: window.loadURL,
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
};
|
||||
@@ -237,6 +241,73 @@ 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();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
@@ -22,6 +23,16 @@ 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,
|
||||
@@ -86,6 +97,22 @@ 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,
|
||||
@@ -152,6 +179,7 @@ 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<
|
||||
@@ -277,7 +305,61 @@ 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(
|
||||
@@ -286,11 +368,22 @@ 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 }),
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -312,14 +405,13 @@ 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)));
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^6.0.4"
|
||||
"astro": "^7.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.7",
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
"@effect/atom-react": "catalog:",
|
||||
"@expo-google-fonts/dm-sans": "^0.4.2",
|
||||
"@expo/ui": "~56.0.8",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@noble/curves": "catalog:",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
@@ -93,9 +93,9 @@
|
||||
"react-native": "0.85.3",
|
||||
"react-native-gesture-handler": "~2.31.1",
|
||||
"react-native-image-viewing": "^0.2.2",
|
||||
"react-native-keyboard-controller": "1.21.6",
|
||||
"react-native-keyboard-controller": "1.21.7",
|
||||
"react-native-nitro-markdown": "^0.5.0",
|
||||
"react-native-nitro-modules": "^0.35.4",
|
||||
"react-native-nitro-modules": "0.35.9",
|
||||
"react-native-reanimated": "4.3.1",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
|
||||
@@ -835,7 +835,7 @@ describe("mobile cloud link environment client", () => {
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(connectRequestBody)).toMatchObject({
|
||||
deviceId: "device-1",
|
||||
clientKeyThumbprint: "client-proof-key-thumbprint",
|
||||
clientProofKeyThumbprint: "client-proof-key-thumbprint",
|
||||
});
|
||||
expect(createProofMock).toHaveBeenCalledWith({
|
||||
method: "POST",
|
||||
|
||||
@@ -484,6 +484,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
scopes: [RelayEnvironmentConnectScope],
|
||||
environmentId: input.environmentId,
|
||||
deviceId,
|
||||
client: authClientMetadata(),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -497,21 +498,30 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
message: "Relay returned credentials for a different environment.",
|
||||
});
|
||||
}
|
||||
if (!("credential" in connect)) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message:
|
||||
connect.approvalStatus === "rejected"
|
||||
? "This device was rejected by the environment. Approve it in the environment settings to connect."
|
||||
: "Waiting for this device to be approved in the environment settings.",
|
||||
});
|
||||
}
|
||||
const authorizedConnect = connect;
|
||||
if (input.expectedEnvironment) {
|
||||
yield* ensureConnectEndpointMatchesEnvironment({
|
||||
environment: input.expectedEnvironment,
|
||||
connect,
|
||||
connect: authorizedConnect,
|
||||
});
|
||||
}
|
||||
|
||||
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
|
||||
),
|
||||
);
|
||||
if (descriptor.environmentId !== connect.environmentId) {
|
||||
if (descriptor.environmentId !== authorizedConnect.environmentId) {
|
||||
return yield* new CloudEnvironmentLinkError({
|
||||
message: "Connected endpoint descriptor does not match the selected environment.",
|
||||
});
|
||||
@@ -520,12 +530,12 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
const bootstrapDpop = yield* signer
|
||||
.createProof({
|
||||
method: "POST",
|
||||
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
|
||||
url: new URL("/oauth/token", authorizedConnect.endpoint.httpBaseUrl).toString(),
|
||||
})
|
||||
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
|
||||
const bootstrap = yield* exchangeRemoteDpopAccessToken({
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
credential: connect.credential,
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
credential: authorizedConnect.credential,
|
||||
dpopProof: bootstrapDpop,
|
||||
clientMetadata: authClientMetadata(),
|
||||
}).pipe(
|
||||
@@ -533,16 +543,16 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
|
||||
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
|
||||
),
|
||||
);
|
||||
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
|
||||
const pairingUrl = new URL(authorizedConnect.endpoint.httpBaseUrl);
|
||||
pairingUrl.hash = new URLSearchParams([["token", authorizedConnect.credential]]).toString();
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
environmentLabel: descriptor.label,
|
||||
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
|
||||
displayUrl: connect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: connect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: connect.endpoint.wsBaseUrl,
|
||||
displayUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
|
||||
wsBaseUrl: authorizedConnect.endpoint.wsBaseUrl,
|
||||
bearerToken: null,
|
||||
authenticationMethod: "dpop",
|
||||
dpopAccessToken: bootstrap.access_token,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
@@ -91,7 +92,7 @@ export interface ThreadComposerProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
@@ -447,9 +448,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
void onSendMessage().then(() => {
|
||||
inputRef.current?.blur();
|
||||
});
|
||||
void onSendMessage();
|
||||
}, [onSendMessage]);
|
||||
const handleCommandSelect = useCallback(
|
||||
(item: ComposerCommandItem) => {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
@@ -13,8 +16,8 @@ import type {
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useHeaderHeight } from "expo-router/build/react-navigation/elements";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent, type LayoutChangeEvent } from "react-native";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { View, type GestureResponderEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -25,7 +28,7 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import type { LayoutVariant } from "../../lib/layout";
|
||||
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -73,7 +76,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
|
||||
readonly onRemoveDraftImage: (imageId: string) => void;
|
||||
readonly onStopThread: () => void;
|
||||
readonly onSendMessage: () => Promise<void>;
|
||||
readonly onSendMessage: () => Promise<MessageId | null>;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
@@ -206,25 +209,33 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const insets = useSafeAreaInsets();
|
||||
const headerHeight = useHeaderHeight();
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const composerRef = useRef<ComposerEditorHandle>(null);
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
const composerOverlayRef = useRef<View>(null);
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
|
||||
const selectedThreadKeyRef = useRef(selectedThreadKey);
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0;
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
|
||||
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
|
||||
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight + 8;
|
||||
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
|
||||
listRef,
|
||||
composerOverlayRef,
|
||||
estimatedOverlayHeight,
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
const selectedInstanceId = props.selectedThread.modelSelection.instanceId;
|
||||
useStreamingHaptics(props.selectedThread.id, props.selectedThreadFeed);
|
||||
const feedBottomInset = resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight,
|
||||
measuredOverlayHeight,
|
||||
gap: 8,
|
||||
});
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
props.serverConfig?.providers.find((provider) => provider.instanceId === selectedInstanceId)
|
||||
@@ -254,15 +265,67 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
[completeDrawerGesture, isSplitLayout],
|
||||
);
|
||||
|
||||
const handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
|
||||
setMeasuredOverlayHeight((current) =>
|
||||
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
|
||||
);
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
lastScrolledAnchorMessageIdRef.current === anchorMessageId ||
|
||||
contentPresentationKind !== "ready" ||
|
||||
!selectedThreadFeed.some((entry) => entry.type === "message" && entry.id === anchorMessageId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = anchorMessageId;
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
if (
|
||||
selectedThreadKeyRef.current !== targetThreadKey ||
|
||||
lastScrolledAnchorMessageIdRef.current !== anchorMessageId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
freeze.set(false);
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
anchorMessageId,
|
||||
freeze,
|
||||
contentPresentationKind,
|
||||
selectedThreadFeed,
|
||||
scrollMessageToEnd,
|
||||
selectedThreadKey,
|
||||
]);
|
||||
|
||||
const handleSendMessage = useCallback(async () => {
|
||||
const targetThreadKey = selectedThreadKey;
|
||||
const messageId = await props.onSendMessage();
|
||||
if (messageId === null || selectedThreadKeyRef.current !== targetThreadKey) {
|
||||
return messageId;
|
||||
}
|
||||
|
||||
setAnchorMessageId(messageId);
|
||||
composerEditorRef.current?.blur();
|
||||
return messageId;
|
||||
}, [props.onSendMessage, selectedThreadKey]);
|
||||
|
||||
const collapseComposer = useCallback(() => {
|
||||
composerRef.current?.blur();
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
@@ -315,10 +378,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={feedBottomInset}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
layoutVariant={layoutVariant}
|
||||
composerExpanded={composerExpanded}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
@@ -332,7 +398,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View onLayout={handleOverlayLayout}>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
@@ -361,7 +427,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerRef}
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
@@ -380,7 +446,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={props.onSendMessage}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Markdown,
|
||||
type CustomRenderers,
|
||||
@@ -15,8 +25,6 @@ import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
@@ -29,6 +37,7 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import type { SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import {
|
||||
@@ -64,14 +73,11 @@ import {
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
} from "../../lib/threadActivity";
|
||||
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
|
||||
import { relativeTime } from "../../lib/time";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
|
||||
const THREAD_FEED_END_THRESHOLD = 80;
|
||||
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
@@ -93,10 +99,13 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly composerExpanded?: boolean;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
}
|
||||
|
||||
@@ -646,7 +655,6 @@ function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
@@ -689,6 +697,18 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "work-toggle") {
|
||||
return (
|
||||
<ThreadWorkGroupToggle
|
||||
expanded={entry.expanded}
|
||||
hiddenCount={entry.hiddenCount}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onlyToolActivities={entry.onlyToolActivities}
|
||||
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "message") {
|
||||
const { message } = entry;
|
||||
const isUser = message.role === "user";
|
||||
@@ -812,39 +832,13 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === "queued-message") {
|
||||
return (
|
||||
<View className="mb-5 items-end">
|
||||
<View
|
||||
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
|
||||
style={{ backgroundColor: userBubbleColor }}
|
||||
>
|
||||
<Text className="font-sans text-base leading-[22px] text-white">
|
||||
{entry.queuedMessage.text}
|
||||
</Text>
|
||||
{entry.queuedMessage.attachments.length > 0 ? (
|
||||
<Text className="font-t3-medium text-xs text-white/75">
|
||||
{entry.queuedMessage.attachments.length} image
|
||||
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
/>
|
||||
);
|
||||
@@ -1122,17 +1116,13 @@ function ThreadFeedPlaceholder(props: {
|
||||
|
||||
export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const router = useRouter();
|
||||
const listRef = useRef<LegendListRef>(null);
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollFrameRef = useRef<number | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const suppressAutoFollowRef = useRef(false);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const isNearEndRef = useRef(true);
|
||||
const initialScrollReadyRef = useRef(false);
|
||||
const lastContentHeightRef = useRef(0);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1193,7 +1183,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1202,7 +1191,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1210,9 +1198,34 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
userBubbleColor,
|
||||
],
|
||||
);
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
if (expanded) {
|
||||
ids.add(groupId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [expandedWorkGroups]);
|
||||
const presentedFeed = useMemo(
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
),
|
||||
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
resolveChatListAnchoredEndSpace(
|
||||
presentedFeed,
|
||||
props.anchorMessageId,
|
||||
(entry) => (entry.type === "message" ? entry.id : null),
|
||||
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
|
||||
),
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
@@ -1229,54 +1242,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
|
||||
const scrollToEnd = useCallback(() => {
|
||||
if (scrollFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
scrollFrameRef.current = requestAnimationFrame(() => {
|
||||
scrollFrameRef.current = null;
|
||||
listRef.current?.scrollToEnd({ animated: false });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onListScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent> | NativeScrollEvent) => {
|
||||
const scrollEvent = "nativeEvent" in event ? event.nativeEvent : event;
|
||||
const { contentInset, contentOffset, contentSize, layoutMeasurement } = scrollEvent;
|
||||
isNearEndRef.current = isThreadFeedNearEnd(
|
||||
{
|
||||
contentHeight: contentSize.height,
|
||||
viewportHeight: layoutMeasurement.height,
|
||||
offsetY: contentOffset.y,
|
||||
bottomInset: contentInset.bottom,
|
||||
},
|
||||
THREAD_FEED_END_THRESHOLD,
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const onListContentSizeChange = useCallback(
|
||||
(_width: number, height: number) => {
|
||||
const contentGrew = height > lastContentHeightRef.current + 0.5;
|
||||
lastContentHeightRef.current = height;
|
||||
|
||||
if (
|
||||
initialScrollReadyRef.current &&
|
||||
contentGrew &&
|
||||
isNearEndRef.current &&
|
||||
!suppressAutoFollowRef.current
|
||||
) {
|
||||
scrollToEnd();
|
||||
}
|
||||
},
|
||||
[scrollToEnd],
|
||||
);
|
||||
|
||||
const onListLoad = useCallback(() => {
|
||||
initialScrollReadyRef.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
@@ -1308,9 +1273,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (copyFeedbackTimeoutRef.current) {
|
||||
clearTimeout(copyFeedbackTimeoutRef.current);
|
||||
}
|
||||
if (scrollFrameRef.current !== null) {
|
||||
cancelAnimationFrame(scrollFrameRef.current);
|
||||
}
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
@@ -1320,6 +1282,39 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
|
||||
disclosureAnchorKeyRef.current = anchorKey;
|
||||
setDisclosureToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
disclosureAnchorKeyRef.current = null;
|
||||
setDisclosureToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
|
||||
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
|
||||
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
|
||||
}, []);
|
||||
|
||||
const maintainVisibleContentPosition = useMemo(
|
||||
() => ({
|
||||
data: true,
|
||||
size: true,
|
||||
shouldRestorePosition: shouldRestoreVisibleContentPosition,
|
||||
}),
|
||||
[shouldRestoreVisibleContentPosition],
|
||||
);
|
||||
|
||||
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
|
||||
copyTextWithHaptic(value, {
|
||||
target: "thread-work-row",
|
||||
@@ -1337,51 +1332,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}, 1200);
|
||||
}, []);
|
||||
|
||||
const onToggleWorkGroup = useCallback((groupId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
const onToggleWorkGroup = useCallback(
|
||||
(groupId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkGroups: {
|
||||
...current.expandedWorkGroups,
|
||||
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onToggleWorkRow = useCallback((rowId: string) => {
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
...current.expandedWorkRows,
|
||||
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
|
||||
},
|
||||
}));
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
suppressAutoFollowRef.current = true;
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
suppressAutoFollowRef.current = false;
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
|
||||
setExpandedImage({ uri, headers });
|
||||
@@ -1392,7 +1385,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1412,7 +1404,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1458,59 +1449,60 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.feed.length === 0) {
|
||||
return (
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<View style={{ flex: 1 }}>
|
||||
<KeyboardAvoidingLegendList
|
||||
ref={listRef}
|
||||
<KeyboardAwareLegendList
|
||||
ref={props.listRef}
|
||||
key={props.threadId}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInset={{ top: 0, bottom: 0 }}
|
||||
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
|
||||
alignItemsAtEnd
|
||||
maintainScrollAtEnd={{
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
|
||||
freeze={props.freeze}
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: false,
|
||||
on: {
|
||||
dataChange: true,
|
||||
itemLayout: true,
|
||||
layout: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
maintainVisibleContentPosition={maintainVisibleContentPosition}
|
||||
data={presentedFeed}
|
||||
extraData={listAppearanceData}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(entry) => `${entry.type}:${entry.id}`}
|
||||
keyExtractor={(entry) => entry.id}
|
||||
getItemType={(entry) =>
|
||||
entry.type === "message" ? `message:${entry.message.role}` : entry.type
|
||||
}
|
||||
keyboardShouldPersistTaps="always"
|
||||
keyboardDismissMode="none"
|
||||
keyboardLiftBehavior="whenAtEnd"
|
||||
estimatedItemSize={180}
|
||||
initialScrollAtEnd
|
||||
onContentSizeChange={onListContentSizeChange}
|
||||
onLoad={onListLoad}
|
||||
onScroll={onListScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={<View style={{ height: topContentInset }} />}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
paddingBottom: bottomContentInset,
|
||||
paddingHorizontal: horizontalPadding,
|
||||
}}
|
||||
/>
|
||||
{props.feed.length === 0 ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
detail="Ask the agent to inspect the repo, run a command, or continue the active thread."
|
||||
topInset={topContentInset}
|
||||
bottomInset={bottomContentInset}
|
||||
horizontalPadding={horizontalPadding}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ImageViewing
|
||||
|
||||
@@ -6,7 +6,6 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -72,11 +71,9 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
@@ -89,14 +86,10 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -104,7 +97,7 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{visibleRows.map((row) => {
|
||||
{rows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.fullDetail !== null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
@@ -132,13 +125,13 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
className="rounded-md px-0.5 py-0"
|
||||
>
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={14}
|
||||
size={13}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
@@ -146,7 +139,7 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
|
||||
<Text
|
||||
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
|
||||
className="min-w-0 flex-1 text-xs leading-4 text-foreground"
|
||||
numberOfLines={1}
|
||||
>
|
||||
<Text
|
||||
@@ -199,7 +192,7 @@ export function ThreadWorkLog(props: {
|
||||
</Pressable>
|
||||
|
||||
{expanded && row.fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
@@ -221,41 +214,59 @@ export function ThreadWorkLog(props: {
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? "Show fewer tool calls"
|
||||
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadWorkGroupToggle(props: {
|
||||
readonly expanded: boolean;
|
||||
readonly hiddenCount: number;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onlyToolActivities: boolean;
|
||||
readonly onToggle: () => void;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,12 @@ import {
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
import {
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
@@ -86,7 +91,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
@@ -144,7 +149,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
@@ -209,7 +214,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread, [], null)[0];
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
@@ -271,7 +276,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
@@ -359,7 +364,7 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
@@ -399,11 +404,65 @@ describe("buildThreadFeed", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread, [], null);
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
fullDetail: null,
|
||||
copyText: id,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status,
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
|
||||
expect(collapsed[1]).toMatchObject({
|
||||
type: "work-toggle",
|
||||
groupId: "work-group-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"activity-1",
|
||||
"activity-2",
|
||||
"activity-3",
|
||||
"work-toggle:work-group-1",
|
||||
]);
|
||||
expect(expanded.at(-1)).toMatchObject({
|
||||
type: "work-toggle",
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
|
||||
import type {
|
||||
MessageId,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
@@ -10,7 +9,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
import type { QueuedThreadMessage } from "../state/thread-outbox-model";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
|
||||
@@ -57,6 +55,8 @@ export interface ThreadFeedActivity {
|
||||
readonly status: "success" | "failure" | "neutral" | null;
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
|
||||
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
|
||||
|
||||
interface WorkLogEntry {
|
||||
@@ -88,13 +88,6 @@ type RawThreadFeedEntry =
|
||||
readonly createdAt: string;
|
||||
readonly message: OrchestrationThread["messages"][number];
|
||||
}
|
||||
| {
|
||||
readonly type: "queued-message";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly queuedMessage: QueuedThreadMessage;
|
||||
readonly sending: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "activity";
|
||||
readonly id: string;
|
||||
@@ -104,7 +97,7 @@ type RawThreadFeedEntry =
|
||||
};
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
readonly type: "activity-group";
|
||||
readonly id: string;
|
||||
@@ -112,6 +105,16 @@ export type ThreadFeedEntry =
|
||||
readonly turnId: TurnId | null;
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
}
|
||||
| {
|
||||
readonly type: "work-toggle";
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly groupId: string;
|
||||
readonly hiddenCount: number;
|
||||
readonly expanded: boolean;
|
||||
readonly onlyToolActivities: boolean;
|
||||
}
|
||||
| {
|
||||
readonly type: "turn-fold";
|
||||
readonly id: string;
|
||||
@@ -1101,8 +1104,11 @@ export function deriveThreadFeedPresentation(
|
||||
feed: ReadonlyArray<ThreadFeedEntry>,
|
||||
latestTurn: ThreadFeedLatestTurn | null,
|
||||
expandedTurnIds: ReadonlySet<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
|
||||
): ThreadFeedEntry[] {
|
||||
const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
|
||||
const sourceFeed = feed.filter(
|
||||
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
|
||||
);
|
||||
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
for (const fold of foldsByAnchorId.values()) {
|
||||
@@ -1127,12 +1133,62 @@ export function deriveThreadFeedPresentation(
|
||||
});
|
||||
}
|
||||
if (!collapsedEntryIds.has(entry.id)) {
|
||||
result.push(entry);
|
||||
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function appendPresentedFeedEntry(
|
||||
result: ThreadFeedEntry[],
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
result.push(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
const activities = entry.activities.filter(
|
||||
(activity) => !(activity.toolLike && activity.status === "neutral"),
|
||||
);
|
||||
if (activities.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
|
||||
result.push({
|
||||
...entry,
|
||||
activities,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const groupId = entry.id;
|
||||
const expanded = expandedWorkGroupIds.has(groupId);
|
||||
const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
|
||||
|
||||
for (const activity of visibleActivities) {
|
||||
result.push({
|
||||
type: "activity-group",
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
activities: [activity],
|
||||
});
|
||||
}
|
||||
result.push({
|
||||
type: "work-toggle",
|
||||
id: `work-toggle:${groupId}`,
|
||||
createdAt: entry.createdAt,
|
||||
turnId: entry.turnId,
|
||||
groupId,
|
||||
hiddenCount,
|
||||
expanded,
|
||||
onlyToolActivities: activities.every((activity) => activity.toolLike),
|
||||
});
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
@@ -1255,8 +1311,6 @@ export function buildPendingUserInputAnswers(
|
||||
|
||||
export function buildThreadFeed(
|
||||
thread: OrchestrationThread,
|
||||
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
|
||||
dispatchingQueuedMessageId: MessageId | null,
|
||||
options?: {
|
||||
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
|
||||
},
|
||||
@@ -1273,13 +1327,6 @@ export function buildThreadFeed(
|
||||
createdAt: message.createdAt,
|
||||
message,
|
||||
})),
|
||||
...queuedMessages.map<RawThreadFeedEntry>((queuedMessage) => ({
|
||||
type: "queued-message",
|
||||
id: queuedMessage.messageId,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
queuedMessage,
|
||||
sending: queuedMessage.messageId === dispatchingQueuedMessageId,
|
||||
})),
|
||||
...workLogEntries
|
||||
.filter((entry) => {
|
||||
if (options?.loadedMessages === undefined) {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isThreadFeedNearEnd,
|
||||
resolveThreadFeedBottomInset,
|
||||
threadFeedDistanceFromEnd,
|
||||
} from "./threadFeedLayout";
|
||||
|
||||
describe("thread feed layout", () => {
|
||||
it("accounts for the bottom inset when measuring distance from the end", () => {
|
||||
const metrics = {
|
||||
contentHeight: 900,
|
||||
viewportHeight: 600,
|
||||
offsetY: 380,
|
||||
bottomInset: 100,
|
||||
};
|
||||
|
||||
expect(threadFeedDistanceFromEnd(metrics)).toBe(20);
|
||||
expect(isThreadFeedNearEnd(metrics, 50)).toBe(true);
|
||||
expect(isThreadFeedNearEnd(metrics, 10)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not double count chrome already included in the measured composer overlay", () => {
|
||||
expect(
|
||||
resolveThreadFeedBottomInset({
|
||||
estimatedOverlayHeight: 162,
|
||||
measuredOverlayHeight: 182,
|
||||
gap: 8,
|
||||
}),
|
||||
).toBe(190);
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
export interface ThreadFeedScrollMetrics {
|
||||
readonly contentHeight: number;
|
||||
readonly viewportHeight: number;
|
||||
readonly offsetY: number;
|
||||
readonly bottomInset: number;
|
||||
}
|
||||
|
||||
export function threadFeedDistanceFromEnd(metrics: ThreadFeedScrollMetrics): number {
|
||||
return metrics.contentHeight + metrics.bottomInset - metrics.viewportHeight - metrics.offsetY;
|
||||
}
|
||||
|
||||
export function isThreadFeedNearEnd(metrics: ThreadFeedScrollMetrics, threshold: number): boolean {
|
||||
return threadFeedDistanceFromEnd(metrics) <= threshold;
|
||||
}
|
||||
|
||||
export function resolveThreadFeedBottomInset(input: {
|
||||
readonly estimatedOverlayHeight: number;
|
||||
readonly measuredOverlayHeight: number;
|
||||
readonly gap: number;
|
||||
}): number {
|
||||
return Math.max(input.estimatedOverlayHeight, input.measuredOverlayHeight) + input.gap;
|
||||
}
|
||||
@@ -40,7 +40,6 @@ import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox-drain";
|
||||
|
||||
export function appendReviewCommentToDraft(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -77,7 +76,6 @@ export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -91,17 +89,9 @@ export function useThreadComposerState() {
|
||||
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
|
||||
const selectedThreadFeed = useMemo(
|
||||
() =>
|
||||
selectedThreadDetail
|
||||
? buildThreadFeed(
|
||||
selectedThreadDetail,
|
||||
selectedThreadQueuedMessages,
|
||||
dispatchingQueuedMessageId,
|
||||
)
|
||||
: [],
|
||||
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
@@ -125,7 +115,6 @@ export function useThreadComposerState() {
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
@@ -135,14 +124,9 @@ export function useThreadComposerState() {
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadSessionActivity,
|
||||
queuedSendStartedAt,
|
||||
null,
|
||||
);
|
||||
}, [
|
||||
queuedSendStartedAt,
|
||||
selectedThreadDetail,
|
||||
selectedThreadSessionActivity,
|
||||
selectedThreadShell,
|
||||
]);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
@@ -150,7 +134,7 @@ export function useThreadComposerState() {
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
@@ -159,15 +143,16 @@ export function useThreadComposerState() {
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const metadata = makeQueuedMessageMetadata();
|
||||
const messageId = MessageId.make(metadata.messageId);
|
||||
try {
|
||||
await enqueueThreadOutboxMessage({
|
||||
environmentId: selectedThreadShell.environmentId,
|
||||
threadId: selectedThreadShell.id,
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
messageId,
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
@@ -177,10 +162,12 @@ export function useThreadComposerState() {
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
return messageId;
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
|
||||
@@ -19,6 +19,23 @@ 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;
|
||||
@@ -36,8 +53,21 @@ 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;
|
||||
@@ -45,6 +75,10 @@ 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);
|
||||
@@ -284,22 +318,66 @@ 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) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
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,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
@@ -356,19 +434,152 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
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" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
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";
|
||||
|
||||
@@ -599,6 +810,42 @@ 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: {
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
import {
|
||||
AuthConnectSecurityMode,
|
||||
type AuthClientMetadata,
|
||||
type AuthClientPresentationMetadata,
|
||||
type AuthConnectClient,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
|
||||
import type { AuthConnectClientRepositoryError } from "../persistence/Errors.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
const CONNECT_SECURITY_MODE_SECRET = "connect-security-mode";
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
const connectClientInternalErrorContext = {
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class ConnectSecurityModeLoadError extends Schema.TaggedErrorClass<ConnectSecurityModeLoadError>()(
|
||||
"ConnectSecurityModeLoadError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to load Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ConnectSecurityModeUpdateError>()(
|
||||
"ConnectSecurityModeUpdateError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to update Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientsLoadError extends Schema.TaggedErrorClass<ConnectClientsLoadError>()(
|
||||
"ConnectClientsLoadError",
|
||||
{
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to load Connect clients.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRequestError extends Schema.TaggedErrorClass<ConnectClientRequestError>()(
|
||||
"ConnectClientRequestError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to record Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientApprovalError extends Schema.TaggedErrorClass<ConnectClientApprovalError>()(
|
||||
"ConnectClientApprovalError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to approve Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRejectionError extends Schema.TaggedErrorClass<ConnectClientRejectionError>()(
|
||||
"ConnectClientRejectionError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to reject Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ConnectClientRevocationError extends Schema.TaggedErrorClass<ConnectClientRevocationError>()(
|
||||
"ConnectClientRevocationError",
|
||||
{
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
...connectClientInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to revoke Connect client '${this.clientProofKeyThumbprint}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ConnectClientStoreError = Schema.Union([
|
||||
ConnectSecurityModeLoadError,
|
||||
ConnectSecurityModeUpdateError,
|
||||
ConnectClientsLoadError,
|
||||
ConnectClientRequestError,
|
||||
ConnectClientApprovalError,
|
||||
ConnectClientRejectionError,
|
||||
ConnectClientRevocationError,
|
||||
]);
|
||||
export type ConnectClientStoreError = typeof ConnectClientStoreError.Type;
|
||||
export const isConnectClientStoreError = Schema.is(ConnectClientStoreError);
|
||||
|
||||
export type ConnectClientChange =
|
||||
| {
|
||||
readonly type: "connectSecurityModeUpdated";
|
||||
readonly mode: AuthConnectSecurityMode;
|
||||
}
|
||||
| {
|
||||
readonly type: "connectClientUpserted";
|
||||
readonly client: AuthConnectClient;
|
||||
}
|
||||
| {
|
||||
readonly type: "connectClientRemoved";
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
};
|
||||
|
||||
export type ConnectClientAuthorization =
|
||||
| {
|
||||
readonly mode: "account";
|
||||
readonly status: "approved";
|
||||
}
|
||||
| {
|
||||
readonly mode: "client-approval";
|
||||
readonly status: "pending" | "approved" | "rejected";
|
||||
readonly client: AuthConnectClient;
|
||||
};
|
||||
|
||||
export class ConnectClientStore extends Context.Service<
|
||||
ConnectClientStore,
|
||||
{
|
||||
readonly getSecurityMode: () => Effect.Effect<
|
||||
AuthConnectSecurityMode,
|
||||
ConnectSecurityModeLoadError
|
||||
>;
|
||||
readonly setSecurityMode: (
|
||||
mode: AuthConnectSecurityMode,
|
||||
) => Effect.Effect<AuthConnectSecurityMode, ConnectSecurityModeUpdateError>;
|
||||
readonly listClients: () => Effect.Effect<
|
||||
ReadonlyArray<AuthConnectClient>,
|
||||
ConnectClientsLoadError
|
||||
>;
|
||||
readonly requestClient: (input: {
|
||||
readonly cloudUserId: string;
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
readonly deviceId?: string;
|
||||
readonly client?: AuthClientPresentationMetadata;
|
||||
}) => Effect.Effect<
|
||||
ConnectClientAuthorization,
|
||||
ConnectClientRequestError | ConnectSecurityModeLoadError
|
||||
>;
|
||||
readonly approve: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientApprovalError>;
|
||||
readonly reject: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientRejectionError>;
|
||||
readonly revoke: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<boolean, ConnectClientRevocationError>;
|
||||
readonly streamChanges: Stream.Stream<ConnectClientChange>;
|
||||
}
|
||||
>()("t3/auth/ConnectClientStore") {}
|
||||
|
||||
function toAuthClientMetadata(
|
||||
record: AuthConnectClients.AuthConnectClientMetadataRecord,
|
||||
): AuthClientMetadata {
|
||||
return {
|
||||
...(record.label ? { label: record.label } : {}),
|
||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
||||
deviceType: record.deviceType,
|
||||
...(record.os ? { os: record.os } : {}),
|
||||
...(record.browser ? { browser: record.browser } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthConnectClient(
|
||||
record: AuthConnectClients.AuthConnectClientRecord,
|
||||
): AuthConnectClient {
|
||||
return {
|
||||
clientProofKeyThumbprint: record.clientProofKeyThumbprint,
|
||||
cloudUserId: record.cloudUserId,
|
||||
...(record.deviceId ? { deviceId: record.deviceId } : {}),
|
||||
status: record.status,
|
||||
client: toAuthClientMetadata(record.client),
|
||||
requestedAt: DateTime.toUtc(record.requestedAt),
|
||||
updatedAt: DateTime.toUtc(record.updatedAt),
|
||||
approvedAt: record.approvedAt === null ? null : DateTime.toUtc(record.approvedAt),
|
||||
rejectedAt: record.rejectedAt === null ? null : DateTime.toUtc(record.rejectedAt),
|
||||
lastSeenAt: record.lastSeenAt === null ? null : DateTime.toUtc(record.lastSeenAt),
|
||||
};
|
||||
}
|
||||
|
||||
function fromPresentationMetadata(
|
||||
client: AuthClientPresentationMetadata | undefined,
|
||||
): AuthConnectClients.AuthConnectClientMetadataRecord {
|
||||
return {
|
||||
label: client?.label ?? null,
|
||||
ipAddress: null,
|
||||
userAgent: null,
|
||||
deviceType: client?.deviceType ?? "unknown",
|
||||
os: client?.os ?? null,
|
||||
browser: null,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeSecurityMode(bytes: Uint8Array): AuthConnectSecurityMode {
|
||||
const value = textDecoder.decode(bytes).trim();
|
||||
return value === "client-approval" ? "client-approval" : "account";
|
||||
}
|
||||
|
||||
function encodeSecurityMode(mode: AuthConnectSecurityMode): Uint8Array {
|
||||
return textEncoder.encode(mode);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const repository = yield* AuthConnectClients.AuthConnectClientRepository;
|
||||
const changesPubSub = yield* PubSub.unbounded<ConnectClientChange>();
|
||||
|
||||
const emitMode = (mode: AuthConnectSecurityMode) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectSecurityModeUpdated",
|
||||
mode,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitUpsert = (client: AuthConnectClient) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectClientUpserted",
|
||||
client,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (clientProofKeyThumbprint: string) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "connectClientRemoved",
|
||||
clientProofKeyThumbprint,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const getSecurityMode: ConnectClientStore["Service"]["getSecurityMode"] = () =>
|
||||
secrets.get(CONNECT_SECURITY_MODE_SECRET).pipe(
|
||||
Effect.map((mode) =>
|
||||
Option.isSome(mode) ? decodeSecurityMode(mode.value) : ("account" as const),
|
||||
),
|
||||
Effect.mapError((cause) => new ConnectSecurityModeLoadError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.getSecurityMode"),
|
||||
);
|
||||
|
||||
const setSecurityMode: ConnectClientStore["Service"]["setSecurityMode"] = (mode) =>
|
||||
secrets.set(CONNECT_SECURITY_MODE_SECRET, encodeSecurityMode(mode)).pipe(
|
||||
Effect.as(mode),
|
||||
Effect.tap(emitMode),
|
||||
Effect.mapError((cause) => new ConnectSecurityModeUpdateError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.setSecurityMode"),
|
||||
);
|
||||
|
||||
const listClients: ConnectClientStore["Service"]["listClients"] = () =>
|
||||
repository.listActive().pipe(
|
||||
Effect.map((clients) => clients.map(toAuthConnectClient)),
|
||||
Effect.mapError((cause) => new ConnectClientsLoadError({ cause })),
|
||||
Effect.withSpan("ConnectClientStore.listClients"),
|
||||
);
|
||||
|
||||
const requestClient: ConnectClientStore["Service"]["requestClient"] = Effect.fn(
|
||||
"ConnectClientStore.requestClient",
|
||||
)(function* (input) {
|
||||
const mode = yield* getSecurityMode();
|
||||
if (mode === "account") {
|
||||
return { mode, status: "approved" as const };
|
||||
}
|
||||
|
||||
const requestedAt = yield* DateTime.now;
|
||||
const record = yield* repository
|
||||
.upsertRequest({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cloudUserId: input.cloudUserId,
|
||||
deviceId: input.deviceId ?? null,
|
||||
client: fromPresentationMetadata(input.client),
|
||||
requestedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRequestError({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const visibleClient = toAuthConnectClient(record);
|
||||
yield* emitUpsert(visibleClient);
|
||||
|
||||
if (record.status !== "approved") {
|
||||
return { mode, status: record.status, client: visibleClient };
|
||||
}
|
||||
|
||||
const seenAt = yield* DateTime.now;
|
||||
const seen = yield* repository
|
||||
.markSeen({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
seenAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRequestError({
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Option.isSome(seen)) {
|
||||
const seenClient = toAuthConnectClient(seen.value);
|
||||
yield* emitUpsert(seenClient);
|
||||
return { mode, status: "approved" as const, client: seenClient };
|
||||
}
|
||||
|
||||
return { mode, status: "rejected" as const, client: visibleClient };
|
||||
});
|
||||
|
||||
const updateDecision = <E extends ConnectClientApprovalError | ConnectClientRejectionError>(
|
||||
clientProofKeyThumbprint: string,
|
||||
status: "approved" | "rejected",
|
||||
toError: (cause: AuthConnectClientRepositoryError) => E,
|
||||
): Effect.Effect<Option.Option<AuthConnectClient>, E> =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((decidedAt) =>
|
||||
repository.updateStatus({
|
||||
clientProofKeyThumbprint,
|
||||
status,
|
||||
decidedAt,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(toError),
|
||||
Effect.map((updated) => Option.map(updated, toAuthConnectClient)),
|
||||
Effect.tap((updated) => (Option.isSome(updated) ? emitUpsert(updated.value) : Effect.void)),
|
||||
);
|
||||
|
||||
const approve: ConnectClientStore["Service"]["approve"] = (clientProofKeyThumbprint) =>
|
||||
updateDecision(
|
||||
clientProofKeyThumbprint,
|
||||
"approved",
|
||||
(cause) =>
|
||||
new ConnectClientApprovalError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
).pipe(Effect.withSpan("ConnectClientStore.approve"));
|
||||
|
||||
const reject: ConnectClientStore["Service"]["reject"] = (clientProofKeyThumbprint) =>
|
||||
updateDecision(
|
||||
clientProofKeyThumbprint,
|
||||
"rejected",
|
||||
(cause) =>
|
||||
new ConnectClientRejectionError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
).pipe(Effect.withSpan("ConnectClientStore.reject"));
|
||||
|
||||
const revoke: ConnectClientStore["Service"]["revoke"] = (clientProofKeyThumbprint) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.flatMap((revokedAt) =>
|
||||
repository.revoke({
|
||||
clientProofKeyThumbprint,
|
||||
revokedAt,
|
||||
}),
|
||||
),
|
||||
Effect.tap((revoked) => (revoked ? emitRemoved(clientProofKeyThumbprint) : Effect.void)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectClientRevocationError({
|
||||
clientProofKeyThumbprint,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("ConnectClientStore.revoke"),
|
||||
);
|
||||
|
||||
return ConnectClientStore.of({
|
||||
getSecurityMode,
|
||||
setSecurityMode,
|
||||
listClients,
|
||||
requestClient,
|
||||
approve,
|
||||
reject,
|
||||
revoke,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ConnectClientStore, make).pipe(
|
||||
Layer.provideMerge(AuthConnectClients.layer),
|
||||
);
|
||||
@@ -3,6 +3,9 @@ import {
|
||||
AuthAccessWriteScope,
|
||||
AuthAdministrativeScopes,
|
||||
AuthStandardClientScopes,
|
||||
type AuthClientPresentationMetadata,
|
||||
type AuthConnectClient,
|
||||
type AuthConnectSecurityMode,
|
||||
type AuthAccessTokenResult,
|
||||
type AuthBrowserSessionResult,
|
||||
type AuthClientMetadata,
|
||||
@@ -26,9 +29,11 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
|
||||
import * as ConnectClientStore from "./ConnectClientStore.ts";
|
||||
import * as PairingGrantStore from "./PairingGrantStore.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
import * as SessionStore from "./SessionStore.ts";
|
||||
@@ -307,6 +312,83 @@ export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectSecurityModeReadError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeReadError>()(
|
||||
"ServerAuthConnectSecurityModeReadError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to read Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeUpdateError>()(
|
||||
"ServerAuthConnectSecurityModeUpdateError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to update Connect security mode.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientsListError extends Schema.TaggedErrorClass<ServerAuthConnectClientsListError>()(
|
||||
"ServerAuthConnectClientsListError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to list Connect clients.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRequestError extends Schema.TaggedErrorClass<ServerAuthConnectClientRequestError>()(
|
||||
"ServerAuthConnectClientRequestError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to authorize Connect client request.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientApprovalError extends Schema.TaggedErrorClass<ServerAuthConnectClientApprovalError>()(
|
||||
"ServerAuthConnectClientApprovalError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to approve Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRejectionError extends Schema.TaggedErrorClass<ServerAuthConnectClientRejectionError>()(
|
||||
"ServerAuthConnectClientRejectionError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to reject Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ServerAuthConnectClientRevocationError extends Schema.TaggedErrorClass<ServerAuthConnectClientRevocationError>()(
|
||||
"ServerAuthConnectClientRevocationError",
|
||||
{
|
||||
...serverAuthInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to revoke Connect client.";
|
||||
}
|
||||
}
|
||||
|
||||
export const ServerAuthInternalError = Schema.Union([
|
||||
ServerAuthBootstrapCredentialValidationError,
|
||||
ServerAuthSessionCredentialValidationError,
|
||||
@@ -330,6 +412,13 @@ export const ServerAuthInternalError = Schema.Union([
|
||||
ServerAuthCloudRelayIssuerMissingError,
|
||||
ServerAuthCloudHealthJwtSigningError,
|
||||
ServerAuthCloudMintJwtSigningError,
|
||||
ServerAuthConnectSecurityModeReadError,
|
||||
ServerAuthConnectSecurityModeUpdateError,
|
||||
ServerAuthConnectClientsListError,
|
||||
ServerAuthConnectClientRequestError,
|
||||
ServerAuthConnectClientApprovalError,
|
||||
ServerAuthConnectClientRejectionError,
|
||||
ServerAuthConnectClientRevocationError,
|
||||
]);
|
||||
export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
|
||||
export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
|
||||
@@ -476,6 +565,33 @@ export class EnvironmentAuth extends Context.Service<
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, ServerAuthInternalError>;
|
||||
readonly getConnectSecurityMode: () => Effect.Effect<
|
||||
AuthConnectSecurityMode,
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly setConnectSecurityMode: (
|
||||
mode: AuthConnectSecurityMode,
|
||||
) => Effect.Effect<AuthConnectSecurityMode, ServerAuthInternalError>;
|
||||
readonly listConnectClients: () => Effect.Effect<
|
||||
ReadonlyArray<AuthConnectClient>,
|
||||
ServerAuthInternalError
|
||||
>;
|
||||
readonly authorizeConnectClientRequest: (input: {
|
||||
readonly cloudUserId: string;
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
readonly deviceId?: string;
|
||||
readonly client?: AuthClientPresentationMetadata;
|
||||
}) => Effect.Effect<ConnectClientStore.ConnectClientAuthorization, ServerAuthInternalError>;
|
||||
readonly approveConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
|
||||
readonly rejectConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
|
||||
readonly revokeConnectClient: (
|
||||
clientProofKeyThumbprint: string,
|
||||
) => Effect.Effect<boolean, ServerAuthInternalError>;
|
||||
readonly streamConnectClientChanges: Stream.Stream<ConnectClientStore.ConnectClientChange>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
|
||||
@@ -557,6 +673,7 @@ export const make = Effect.gen(function* () {
|
||||
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
|
||||
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const connectClients = yield* ConnectClientStore.ConnectClientStore;
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
@@ -903,6 +1020,59 @@ export const make = Effect.gen(function* () {
|
||||
Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
|
||||
);
|
||||
|
||||
const getConnectSecurityMode: EnvironmentAuth["Service"]["getConnectSecurityMode"] = () =>
|
||||
connectClients.getSecurityMode().pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectSecurityModeReadError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.getConnectSecurityMode"),
|
||||
);
|
||||
|
||||
const setConnectSecurityMode: EnvironmentAuth["Service"]["setConnectSecurityMode"] = (mode) =>
|
||||
connectClients.setSecurityMode(mode).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectSecurityModeUpdateError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.setConnectSecurityMode"),
|
||||
);
|
||||
|
||||
const listConnectClients: EnvironmentAuth["Service"]["listConnectClients"] = () =>
|
||||
connectClients.listClients().pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientsListError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.listConnectClients"),
|
||||
);
|
||||
|
||||
const authorizeConnectClientRequest: EnvironmentAuth["Service"]["authorizeConnectClientRequest"] =
|
||||
(input) =>
|
||||
connectClients.requestClient(input).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectSecurityModeLoadError"
|
||||
? new ServerAuthConnectSecurityModeReadError({ cause })
|
||||
: new ServerAuthConnectClientRequestError({ cause }),
|
||||
),
|
||||
Effect.withSpan("EnvironmentAuth.authorizeConnectClientRequest"),
|
||||
);
|
||||
|
||||
const approveConnectClient: EnvironmentAuth["Service"]["approveConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.approve(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientApprovalError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.approveConnectClient"),
|
||||
);
|
||||
|
||||
const rejectConnectClient: EnvironmentAuth["Service"]["rejectConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.reject(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientRejectionError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.rejectConnectClient"),
|
||||
);
|
||||
|
||||
const revokeConnectClient: EnvironmentAuth["Service"]["revokeConnectClient"] = (
|
||||
clientProofKeyThumbprint,
|
||||
) =>
|
||||
connectClients.revoke(clientProofKeyThumbprint).pipe(
|
||||
Effect.mapError((cause) => new ServerAuthConnectClientRevocationError({ cause })),
|
||||
Effect.withSpan("EnvironmentAuth.revokeConnectClient"),
|
||||
);
|
||||
|
||||
const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
|
||||
issueStartupPairingCredential().pipe(
|
||||
Effect.map((issued) => {
|
||||
@@ -973,6 +1143,14 @@ export const make = Effect.gen(function* () {
|
||||
listClientSessions,
|
||||
revokeClientSession,
|
||||
revokeOtherClientSessions,
|
||||
getConnectSecurityMode,
|
||||
setConnectSecurityMode,
|
||||
listConnectClients,
|
||||
authorizeConnectClientRequest,
|
||||
approveConnectClient,
|
||||
rejectConnectClient,
|
||||
revokeConnectClient,
|
||||
streamConnectClientChanges: connectClients.streamChanges,
|
||||
authenticateHttpRequest,
|
||||
authenticateWebSocketUpgrade,
|
||||
issueWebSocketTicket,
|
||||
@@ -983,6 +1161,7 @@ export const make = Effect.gen(function* () {
|
||||
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
|
||||
Layer.provideMerge(PairingGrantStore.layer),
|
||||
Layer.provideMerge(SessionStore.layer),
|
||||
Layer.provideMerge(ConnectClientStore.layer),
|
||||
Layer.provideMerge(EnvironmentAuthPolicy.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Cookies from "effect/unstable/http/Cookies";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -419,6 +420,81 @@ export const authHttpApiLayer = HttpApiBuilder.group(
|
||||
failEnvironmentInternal("client_session_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"connectSecurityMode",
|
||||
Effect.fn("environment.auth.connectSecurityMode")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const mode = yield* serverAuth.setConnectSecurityMode(args.payload.mode);
|
||||
return { mode };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_security_mode_update_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"connectClients",
|
||||
Effect.fn("environment.auth.connectClients")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessReadScope);
|
||||
return yield* serverAuth.listConnectClients();
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_clients_load_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"approveConnectClient",
|
||||
Effect.fn("environment.auth.approveConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const client = yield* serverAuth.approveConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { client: Option.getOrNull(client) };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_approval_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"rejectConnectClient",
|
||||
Effect.fn("environment.auth.rejectConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const client = yield* serverAuth.rejectConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { client: Option.getOrNull(client) };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_rejection_failed", error),
|
||||
),
|
||||
),
|
||||
)
|
||||
.handle(
|
||||
"revokeConnectClient",
|
||||
Effect.fn("environment.auth.revokeConnectClient")(
|
||||
function* (args) {
|
||||
yield* annotateEnvironmentRequest(args.endpoint.name);
|
||||
yield* requireEnvironmentScope(AuthAccessWriteScope);
|
||||
const revoked = yield* serverAuth.revokeConnectClient(
|
||||
args.payload.clientProofKeyThumbprint,
|
||||
);
|
||||
return { revoked };
|
||||
},
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentInternal("connect_client_revoke_failed", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
+253
-11
@@ -1,14 +1,19 @@
|
||||
import {
|
||||
AuthConnectClient,
|
||||
AuthConnectSecurityMode,
|
||||
AuthRelayWriteScope,
|
||||
EnvironmentHttpApi,
|
||||
type AuthConnectClient as AuthConnectClientType,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type RelayClientInstallProgressStage,
|
||||
} from "@t3tools/contracts";
|
||||
import { RelayOkResponse } from "@t3tools/contracts/relay";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Console from "effect/Console";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
@@ -16,7 +21,8 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
@@ -52,9 +58,69 @@ interface CloudCliStatus {
|
||||
readonly linked: boolean;
|
||||
readonly cloudUserId: string | null;
|
||||
readonly relayUrl: string | null;
|
||||
readonly connectSecurityMode: AuthConnectSecurityMode;
|
||||
readonly relayClient: RelayClient.RelayClientStatus;
|
||||
}
|
||||
|
||||
const ConnectSecurityModeOutput = Schema.Struct({
|
||||
mode: AuthConnectSecurityMode,
|
||||
});
|
||||
const encodeConnectSecurityModeOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityModeOutput),
|
||||
);
|
||||
const ConnectSecurityClientsOutput = Schema.Struct({
|
||||
clients: Schema.Array(AuthConnectClient),
|
||||
});
|
||||
const ConnectSecurityClientDecisionOutput = Schema.Struct({
|
||||
client: Schema.NullOr(AuthConnectClient),
|
||||
});
|
||||
const ConnectSecurityClientRevokeOutput = Schema.Struct({
|
||||
revoked: Schema.Boolean,
|
||||
});
|
||||
const encodeConnectSecurityClientsOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientsOutput),
|
||||
);
|
||||
const encodeConnectSecurityClientDecisionOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientDecisionOutput),
|
||||
);
|
||||
const encodeConnectSecurityClientRevokeOutputJson = Schema.encodeUnknownEffect(
|
||||
fromJsonStringPretty(ConnectSecurityClientRevokeOutput),
|
||||
);
|
||||
|
||||
function formatConnectClientLabel(client: AuthConnectClientType): string {
|
||||
return (
|
||||
client.client.label ??
|
||||
client.client.os ??
|
||||
`client ${client.clientProofKeyThumbprint.slice(0, 12)}`
|
||||
);
|
||||
}
|
||||
|
||||
function formatConnectClientDetails(client: AuthConnectClientType): string {
|
||||
const details = [
|
||||
client.client.deviceType !== "unknown" ? client.client.deviceType : null,
|
||||
client.client.os ?? null,
|
||||
client.deviceId ? `device ${client.deviceId}` : null,
|
||||
client.lastSeenAt ? `last seen ${DateTime.formatIso(client.lastSeenAt)}` : null,
|
||||
`requested ${DateTime.formatIso(client.requestedAt)}`,
|
||||
].filter((value): value is string => value !== null);
|
||||
return details.join(", ");
|
||||
}
|
||||
|
||||
function formatConnectClientList(clients: ReadonlyArray<AuthConnectClientType>): string {
|
||||
if (clients.length === 0) {
|
||||
return "No T3 Connect clients are registered.";
|
||||
}
|
||||
return [
|
||||
"T3 Connect clients",
|
||||
...clients.map(
|
||||
(client) =>
|
||||
` ${client.clientProofKeyThumbprint} ${client.status} ${formatConnectClientLabel(
|
||||
client,
|
||||
)} (${formatConnectClientDetails(client)})`,
|
||||
),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
|
||||
switch (executable.status) {
|
||||
case "available": {
|
||||
@@ -103,6 +169,9 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
|
||||
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
|
||||
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
|
||||
` Environment link: ${provisioned}`,
|
||||
` Client approval: ${
|
||||
status.connectSecurityMode === "client-approval" ? "required" : "account-wide"
|
||||
}`,
|
||||
` Relay: ${status.relayUrl ?? "not provisioned"}`,
|
||||
...formatRelayClientStatus(status.relayClient),
|
||||
...(nextStep ? ["", `Next: ${nextStep}`] : []),
|
||||
@@ -411,22 +480,26 @@ const connectStatusCommand = Command.make("status", {
|
||||
const secrets = yield* ServerSecretStore.ServerSecretStore;
|
||||
const relayClient = yield* RelayClient.RelayClient;
|
||||
const tokens = yield* CliTokenManager.CloudCliTokenManager;
|
||||
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const [desired, authenticated, cloudUserId, relayUrl, connectSecurityMode, executable] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
CliState.readCliDesiredCloudLink,
|
||||
tokens.hasCredential,
|
||||
secrets.get(CLOUD_LINKED_USER_ID),
|
||||
secrets.get(RELAY_URL_SECRET),
|
||||
environmentAuth.getConnectSecurityMode(),
|
||||
relayClient.resolve,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const status: CloudCliStatus = {
|
||||
desired,
|
||||
authenticated,
|
||||
linked: Option.isSome(cloudUserId),
|
||||
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
|
||||
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
|
||||
connectSecurityMode,
|
||||
relayClient: executable,
|
||||
};
|
||||
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
|
||||
@@ -438,6 +511,174 @@ const connectStatusCommand = Command.make("status", {
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityModeFlag = Flag.choice("mode", ["account", "client-approval"] as const).pipe(
|
||||
Flag.withDescription("Connect security mode."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const connectClientThumbprintArgument = Argument.string("client-proof-key-thumbprint").pipe(
|
||||
Argument.withDescription("T3 Connect client proof key thumbprint."),
|
||||
);
|
||||
|
||||
const connectSecurityClientsCommand = Command.make("clients", {
|
||||
...projectLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List T3 Connect clients registered for approval."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const clients = yield* environmentAuth.listConnectClients();
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientsOutputJson({ clients });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(formatConnectClientList(clients));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityApproveCommand = Command.make("approve", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Approve a T3 Connect client."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const client = yield* environmentAuth.approveConnectClient(flags.clientProofKeyThumbprint);
|
||||
const clientOrNull = Option.getOrNull(client);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
|
||||
client: clientOrNull,
|
||||
});
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
clientOrNull
|
||||
? `Approved T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityRejectCommand = Command.make("reject", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Reject a T3 Connect client."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const client = yield* environmentAuth.rejectConnectClient(flags.clientProofKeyThumbprint);
|
||||
const clientOrNull = Option.getOrNull(client);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
|
||||
client: clientOrNull,
|
||||
});
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
clientOrNull
|
||||
? `Rejected T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityRevokeCommand = Command.make("revoke", {
|
||||
...projectLocationFlags,
|
||||
clientProofKeyThumbprint: connectClientThumbprintArgument,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke a T3 Connect client approval record."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const revoked = yield* environmentAuth.revokeConnectClient(flags.clientProofKeyThumbprint);
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityClientRevokeOutputJson({ revoked });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked T3 Connect client ${flags.clientProofKeyThumbprint}.`
|
||||
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const connectSecurityCommand = Command.make("security", {
|
||||
...projectLocationFlags,
|
||||
mode: connectSecurityModeFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Read or update T3 Connect client-approval mode."),
|
||||
Command.withHandler((flags) =>
|
||||
runCloudCommand(
|
||||
flags,
|
||||
Effect.gen(function* () {
|
||||
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
const mode = Option.isSome(flags.mode)
|
||||
? yield* environmentAuth.setConnectSecurityMode(flags.mode.value)
|
||||
: yield* environmentAuth.getConnectSecurityMode();
|
||||
if (flags.json) {
|
||||
const output = yield* encodeConnectSecurityModeOutputJson({ mode });
|
||||
yield* Console.log(output);
|
||||
return;
|
||||
}
|
||||
yield* Console.log(
|
||||
mode === "client-approval"
|
||||
? "T3 Connect client approval is required."
|
||||
: "T3 Connect uses account-wide access.",
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
Command.withSubcommands([
|
||||
connectSecurityClientsCommand,
|
||||
connectSecurityApproveCommand,
|
||||
connectSecurityRejectCommand,
|
||||
connectSecurityRevokeCommand,
|
||||
]),
|
||||
);
|
||||
|
||||
const connectUnlinkCommand = Command.make("unlink", {
|
||||
...projectLocationFlags,
|
||||
}).pipe(
|
||||
@@ -462,6 +703,7 @@ export const connectCommand = Command.make("connect").pipe(
|
||||
connectLoginCommand,
|
||||
connectLinkCommand,
|
||||
connectStatusCommand,
|
||||
connectSecurityCommand,
|
||||
connectUnlinkCommand,
|
||||
connectLogoutCommand,
|
||||
]),
|
||||
|
||||
@@ -608,15 +608,17 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
|
||||
dependencies: CloudHttpDependencies,
|
||||
) {
|
||||
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
|
||||
[
|
||||
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
|
||||
dependencies.secrets.get(RELAY_URL_SECRET),
|
||||
dependencies.secrets.get(RELAY_ISSUER_SECRET),
|
||||
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
|
||||
],
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity, connectSecurityMode] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
|
||||
dependencies.secrets.get(RELAY_URL_SECRET),
|
||||
dependencies.secrets.get(RELAY_ISSUER_SECRET),
|
||||
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
|
||||
dependencies.environmentAuth.getConnectSecurityMode(),
|
||||
],
|
||||
{ concurrency: 5 },
|
||||
);
|
||||
return {
|
||||
linked: Option.isSome(cloudUserId),
|
||||
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
|
||||
@@ -625,6 +627,7 @@ const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function
|
||||
publishAgentActivity: Option.isSome(publishAgentActivity)
|
||||
? bytesToString(publishAgentActivity.value) === "true"
|
||||
: false,
|
||||
connectSecurityMode,
|
||||
} satisfies EnvironmentCloudLinkStateResult;
|
||||
});
|
||||
|
||||
@@ -637,6 +640,9 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
|
||||
@@ -680,6 +686,9 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
|
||||
ServerSecretStore.isSecretStoreError,
|
||||
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
|
||||
),
|
||||
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
|
||||
failEnvironmentCloudInternalError(error.message)(error),
|
||||
),
|
||||
);
|
||||
|
||||
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
|
||||
@@ -868,6 +877,54 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
|
||||
}
|
||||
|
||||
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
|
||||
const connectAuthorization = yield* dependencies.environmentAuth.authorizeConnectClientRequest({
|
||||
cloudUserId: linkedCloudUserId,
|
||||
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
|
||||
...(proof.deviceId ? { deviceId: proof.deviceId } : {}),
|
||||
...(proof.client ? { client: proof.client } : {}),
|
||||
});
|
||||
if (
|
||||
connectAuthorization.mode === "client-approval" &&
|
||||
connectAuthorization.status !== "approved"
|
||||
) {
|
||||
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const responsePayload = {
|
||||
iss: `t3-env:${environmentId}`,
|
||||
aud: normalizeRelayIssuer(relayIssuer),
|
||||
sub: environmentId,
|
||||
jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
|
||||
iat: nowSeconds,
|
||||
exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
|
||||
environmentId,
|
||||
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
|
||||
requestNonce: proof.nonce,
|
||||
status: "pending_approval",
|
||||
approvalStatus: connectAuthorization.status,
|
||||
} satisfies RelayEnvironmentMintResponseProofPayload;
|
||||
const responseProof = yield* signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
typ: RELAY_MINT_RESPONSE_TYP,
|
||||
payload: responsePayload,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const response = {
|
||||
status: "pending_approval",
|
||||
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
|
||||
approvalStatus: connectAuthorization.status,
|
||||
requestedAt: DateTime.formatIso(connectAuthorization.client.requestedAt),
|
||||
proof: responseProof,
|
||||
} satisfies RelayEnvironmentMintResponseShape;
|
||||
|
||||
yield* appendCloudCredentialResponseHeaders;
|
||||
return response;
|
||||
}
|
||||
|
||||
const issued = yield* dependencies.environmentAuth.createPairingLink({
|
||||
scopes: AuthStandardClientScopes,
|
||||
subject: "cloud-connect",
|
||||
|
||||
@@ -44,13 +44,18 @@ 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], credentials: true } : {}),
|
||||
...(devOrigin
|
||||
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
|
||||
: {}),
|
||||
allowedMethods: browserApiCorsAllowedMethods,
|
||||
allowedHeaders: browserApiCorsAllowedHeaders,
|
||||
maxAge: 600,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
@@ -34,7 +35,7 @@ const client = McpSchema.McpServerClient.of({
|
||||
});
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -54,36 +55,26 @@ it.effect("returns bounded structural preview snapshot failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-failure-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "PreviewAutomationExecutionError",
|
||||
message: "sensitive renderer failure",
|
||||
detail: { consoleOutput: "sensitive browser output" },
|
||||
},
|
||||
}),
|
||||
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" },
|
||||
},
|
||||
}),
|
||||
).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: {} })
|
||||
@@ -163,60 +154,50 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const requests = yield* broker.connect({
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-test-client",
|
||||
environmentId,
|
||||
threadId,
|
||||
tabId,
|
||||
visible: true,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
});
|
||||
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,
|
||||
},
|
||||
}),
|
||||
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,
|
||||
},
|
||||
}),
|
||||
).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);
|
||||
|
||||
@@ -214,7 +214,4 @@ const McpTransportLive = McpServer.layerHttp({
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpTransportLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
);
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -1,20 +1,28 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewTabId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationStreamEvent,
|
||||
} 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"),
|
||||
@@ -22,27 +30,42 @@ const scope = {
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["preview"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
|
||||
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
|
||||
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
tabId: null,
|
||||
visible: false,
|
||||
supportsAutomation: true,
|
||||
focusedAt: "2026-06-11T00:00:00.000Z",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it.effect("atomically registers a connected owner and correlates its response", () =>
|
||||
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", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
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: true,
|
||||
result: { available: true },
|
||||
@@ -61,6 +84,39 @@ it.effect("atomically registers a connected owner 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.";
|
||||
@@ -72,10 +128,12 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
|
||||
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,
|
||||
@@ -88,6 +146,7 @@ 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);
|
||||
@@ -121,13 +180,61 @@ 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* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: false }),
|
||||
broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: false,
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -150,13 +257,14 @@ it.effect("distinguishes malformed remote failures", () =>
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects calls when no focused owner exists", () =>
|
||||
it.effect("rejects calls when no connected host exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const broker = yield* makeBroker;
|
||||
const error = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "status",
|
||||
environmentId: scope.environmentId,
|
||||
@@ -167,32 +275,425 @@ it.effect("rejects calls when no focused owner exists", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes interactive commands to a hidden durable browser host", () =>
|
||||
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", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
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;
|
||||
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);
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
const consumer = yield* Stream.runDrain(requests).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);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
|
||||
it.effect("routes requests for background threads through an environment-level host", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ tabId: null }));
|
||||
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()));
|
||||
let routedTabId: string | undefined;
|
||||
yield* Stream.runForEach(requests, (request) => {
|
||||
routedTabId = request.tabId;
|
||||
return broker.respond({ requestId: request.requestId, ok: true });
|
||||
return broker.respond({
|
||||
clientId: "client-1",
|
||||
connectionId: request.connectionId,
|
||||
requestId: request.requestId,
|
||||
ok: true,
|
||||
});
|
||||
}).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -203,61 +704,55 @@ it.effect("lets the browser host resolve an active tab that has not been reporte
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves current owner metadata when its request stream reconnects", () =>
|
||||
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const firstRequests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
let firstConnectionId = "";
|
||||
let replacementConnectionId = "";
|
||||
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
|
||||
firstConnectionId = connectionId;
|
||||
});
|
||||
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;
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
|
||||
|
||||
expect(routedTabId).toBe("tab-current");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner());
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true }),
|
||||
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.clearOwner({
|
||||
clientId: "client-1",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: ThreadId.make("thread-stale"),
|
||||
});
|
||||
|
||||
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
|
||||
expect(replacementConnectionId).not.toBe(firstConnectionId);
|
||||
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
|
||||
expect(result).toBe("replacement");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
|
||||
it.effect("fails requests assigned to the stream that is replaced", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const _requests = yield* broker.connect(makeOwner());
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
|
||||
const pending = yield* broker
|
||||
.invoke<void>({ scope, operation: "status", input: {} })
|
||||
.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const _replacementRequests = yield* broker.connect(makeOwner());
|
||||
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
|
||||
|
||||
const error = yield* Fiber.join(pending);
|
||||
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
|
||||
@@ -275,25 +770,40 @@ it.effect("fails requests assigned to a browser stream when that stream reconnec
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
|
||||
it.effect("accepts responses only from the host that received the request", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const broker = yield* PreviewAutomationBroker.make;
|
||||
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
|
||||
const broker = yield* makeBroker;
|
||||
const requests = requestsFrom(yield* broker.connect(makeHost()));
|
||||
yield* Stream.runForEach(requests, (request) =>
|
||||
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
|
||||
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",
|
||||
});
|
||||
}),
|
||||
).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("connected");
|
||||
expect(result).toBe("owner");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,26 +1,29 @@
|
||||
import {
|
||||
PREVIEW_AUTOMATION_V1_OPERATIONS,
|
||||
PreviewAutomationClientDisconnectedError,
|
||||
PreviewAutomationControlInterruptedError,
|
||||
PreviewAutomationExecutionError,
|
||||
PreviewAutomationHostNotConnectedError,
|
||||
PreviewAutomationInvalidSelectorError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationNoFocusedOwnerError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationResultTooLargeError,
|
||||
PreviewAutomationTabNotFoundError,
|
||||
PreviewAutomationTargetNotEditableError,
|
||||
PreviewAutomationTimeoutError,
|
||||
PreviewAutomationUnsupportedClientError,
|
||||
type PreviewAutomationError,
|
||||
type PreviewAutomationOperation,
|
||||
type PreviewAutomationOwner,
|
||||
type PreviewAutomationOwnerIdentity,
|
||||
type PreviewAutomationRequest,
|
||||
type PreviewAutomationHost,
|
||||
type PreviewAutomationHostFocus,
|
||||
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";
|
||||
@@ -43,12 +46,9 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
PreviewAutomationBroker,
|
||||
{
|
||||
readonly connect: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
|
||||
readonly reportOwner: (
|
||||
owner: PreviewAutomationOwner,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
|
||||
host: PreviewAutomationHost,
|
||||
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
|
||||
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
|
||||
readonly respond: (
|
||||
response: PreviewAutomationResponse,
|
||||
) => Effect.Effect<void, PreviewAutomationError>;
|
||||
@@ -60,7 +60,12 @@ export class PreviewAutomationBroker extends Context.Service<
|
||||
|
||||
interface ClientConnection {
|
||||
readonly clientId: string;
|
||||
readonly queue: Queue.Queue<PreviewAutomationRequest>;
|
||||
readonly connectionId: string;
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
|
||||
readonly focused: boolean;
|
||||
readonly focusOrder: number;
|
||||
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
|
||||
}
|
||||
|
||||
interface PendingRequest {
|
||||
@@ -69,6 +74,13 @@ 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"];
|
||||
@@ -76,6 +88,7 @@ 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;
|
||||
@@ -85,11 +98,36 @@ interface PreviewAutomationRequestErrorContext {
|
||||
|
||||
interface BrokerState {
|
||||
readonly clients: ReadonlyMap<string, ClientConnection>;
|
||||
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
|
||||
readonly assignments: ReadonlyMap<string, HostAssignment>;
|
||||
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"> => {
|
||||
@@ -103,6 +141,14 @@ 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 {
|
||||
@@ -131,8 +177,8 @@ const classifyResponseError = (
|
||||
cause: error,
|
||||
};
|
||||
switch (error._tag) {
|
||||
case "PreviewAutomationNoFocusedOwnerError":
|
||||
return new PreviewAutomationNoFocusedOwnerError({
|
||||
case "PreviewAutomationNoAvailableHostError":
|
||||
return new PreviewAutomationNoAvailableHostError({
|
||||
...context,
|
||||
...remoteDiagnostics,
|
||||
});
|
||||
@@ -162,6 +208,36 @@ 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;
|
||||
@@ -193,36 +269,21 @@ const classifyResponseError = (
|
||||
};
|
||||
|
||||
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const state = yield* SynchronizedRef.make<BrokerState>({
|
||||
clients: new Map(),
|
||||
owners: new Map(),
|
||||
assignments: new Map(),
|
||||
pending: new Map(),
|
||||
requestSequence: 0,
|
||||
focusSequence: 0,
|
||||
});
|
||||
|
||||
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
|
||||
clientId: string,
|
||||
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
|
||||
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(
|
||||
toFail,
|
||||
disconnected,
|
||||
({ deferred, context }) =>
|
||||
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
|
||||
{ discard: true },
|
||||
@@ -230,54 +291,89 @@ 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",
|
||||
)(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)));
|
||||
});
|
||||
)((host) =>
|
||||
Effect.succeed(
|
||||
Stream.unwrap(
|
||||
Effect.acquireRelease(acquireConnection(host), (connection) =>
|
||||
disconnect(connection.clientId, connection.queue),
|
||||
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
|
||||
"PreviewAutomationBroker.reportOwner",
|
||||
)(function* (owner) {
|
||||
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
|
||||
"PreviewAutomationBroker.focusHost",
|
||||
)(function* (host) {
|
||||
yield* SynchronizedRef.update(state, (current) => {
|
||||
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);
|
||||
const currentHost = current.clients.get(host.clientId);
|
||||
if (
|
||||
!currentOwner ||
|
||||
currentOwner.environmentId !== owner.environmentId ||
|
||||
currentOwner.threadId !== owner.threadId
|
||||
!currentHost ||
|
||||
currentHost.environmentId !== host.environmentId ||
|
||||
currentHost.connectionId !== host.connectionId
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
const owners = new Map(current.owners);
|
||||
owners.delete(owner.clientId);
|
||||
return { ...current, owners };
|
||||
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 };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -286,7 +382,13 @@ 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) return [undefined, current] as const;
|
||||
if (
|
||||
!entry ||
|
||||
entry.context.clientId !== response.clientId ||
|
||||
entry.context.connectionId !== response.connectionId
|
||||
) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const next = new Map(current.pending);
|
||||
next.delete(response.requestId);
|
||||
return [entry, { ...current, pending: next }] as const;
|
||||
@@ -307,52 +409,60 @@ 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 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,
|
||||
});
|
||||
}
|
||||
return yield* new PreviewAutomationNoFocusedOwnerError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
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 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;
|
||||
}
|
||||
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,
|
||||
@@ -360,19 +470,30 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
clientId: owner.clientId,
|
||||
clientId: connection.clientId,
|
||||
connectionId: connection.connectionId,
|
||||
requestId,
|
||||
...(tabId === undefined ? {} : { tabId }),
|
||||
timeoutMs,
|
||||
...selectorDiagnostics,
|
||||
};
|
||||
const pending = new Map(next.pending);
|
||||
const pending = new Map(current.pending);
|
||||
pending.set(requestId, { queue: connection.queue, deferred, context });
|
||||
return [
|
||||
[requestId, context] as const,
|
||||
{ ...next, pending, requestSequence: next.requestSequence + 1 },
|
||||
{ connection, requestId, requestContext: context },
|
||||
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
|
||||
] as const;
|
||||
});
|
||||
if (!route) {
|
||||
return yield* new PreviewAutomationNoAvailableHostError({
|
||||
operation: input.operation,
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
});
|
||||
}
|
||||
const { connection, requestId, requestContext } = route;
|
||||
const removePending = SynchronizedRef.update(state, (next) => {
|
||||
if (!next.pending.has(requestId)) return next;
|
||||
const pending = new Map(next.pending);
|
||||
@@ -381,12 +502,16 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
});
|
||||
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
|
||||
const offered = yield* Queue.offer(connection.queue, {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
type: "request",
|
||||
connectionId: connection.connectionId,
|
||||
request: {
|
||||
requestId,
|
||||
threadId: input.scope.threadId,
|
||||
tabId: requestContext.tabId,
|
||||
operation: input.operation,
|
||||
input: input.input,
|
||||
timeoutMs,
|
||||
},
|
||||
});
|
||||
if (!offered) {
|
||||
const completion = yield* Deferred.poll(deferred);
|
||||
@@ -404,7 +529,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
|
||||
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
|
||||
});
|
||||
|
||||
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
|
||||
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
|
||||
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
|
||||
|
||||
export const layer = Layer.effect(PreviewAutomationBroker, make);
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -39,6 +40,8 @@ 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)),
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
PreviewAutomationPressInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeInput,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScrollInput,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
@@ -35,7 +37,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, and loading state.",
|
||||
"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.",
|
||||
success: PreviewAutomationStatus,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
@@ -69,6 +71,19 @@ 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:
|
||||
@@ -168,6 +183,7 @@ export const PreviewToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewSnapshotTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
@@ -183,6 +199,7 @@ export const PreviewStandardToolkit = Toolkit.make(
|
||||
PreviewStatusTool,
|
||||
PreviewOpenTool,
|
||||
PreviewNavigateTool,
|
||||
PreviewResizeTool,
|
||||
PreviewClickTool,
|
||||
PreviewTypeTool,
|
||||
PreviewPressTool,
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { AuthClientMetadataDeviceType, AuthConnectClientStatus } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
type AuthConnectClientRepositoryError,
|
||||
PersistenceDecodeError,
|
||||
type PersistenceErrorCorrelation,
|
||||
PersistenceSqlError,
|
||||
} from "./Errors.ts";
|
||||
|
||||
export const AuthConnectClientMetadataRecord = Schema.Struct({
|
||||
label: Schema.NullOr(Schema.String),
|
||||
ipAddress: Schema.NullOr(Schema.String),
|
||||
userAgent: Schema.NullOr(Schema.String),
|
||||
deviceType: AuthClientMetadataDeviceType,
|
||||
os: Schema.NullOr(Schema.String),
|
||||
browser: Schema.NullOr(Schema.String),
|
||||
});
|
||||
export type AuthConnectClientMetadataRecord = typeof AuthConnectClientMetadataRecord.Type;
|
||||
|
||||
export const AuthConnectClientRecord = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
cloudUserId: Schema.String,
|
||||
deviceId: Schema.NullOr(Schema.String),
|
||||
status: AuthConnectClientStatus,
|
||||
client: AuthConnectClientMetadataRecord,
|
||||
requestedAt: Schema.DateTimeUtcFromString,
|
||||
updatedAt: Schema.DateTimeUtcFromString,
|
||||
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
export type AuthConnectClientRecord = typeof AuthConnectClientRecord.Type;
|
||||
|
||||
export const UpsertAuthConnectClientRequestInput = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
cloudUserId: Schema.String,
|
||||
deviceId: Schema.NullOr(Schema.String),
|
||||
client: AuthConnectClientMetadataRecord,
|
||||
requestedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type UpsertAuthConnectClientRequestInput = typeof UpsertAuthConnectClientRequestInput.Type;
|
||||
|
||||
export const UpdateAuthConnectClientStatusInput = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
status: Schema.Literals(["approved", "rejected"]),
|
||||
decidedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type UpdateAuthConnectClientStatusInput = typeof UpdateAuthConnectClientStatusInput.Type;
|
||||
|
||||
export const RevokeAuthConnectClientInput = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
revokedAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type RevokeAuthConnectClientInput = typeof RevokeAuthConnectClientInput.Type;
|
||||
|
||||
export const MarkAuthConnectClientSeenInput = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
seenAt: Schema.DateTimeUtcFromString,
|
||||
});
|
||||
export type MarkAuthConnectClientSeenInput = typeof MarkAuthConnectClientSeenInput.Type;
|
||||
|
||||
export class AuthConnectClientRepository extends Context.Service<
|
||||
AuthConnectClientRepository,
|
||||
{
|
||||
readonly upsertRequest: (
|
||||
input: UpsertAuthConnectClientRequestInput,
|
||||
) => Effect.Effect<AuthConnectClientRecord, AuthConnectClientRepositoryError>;
|
||||
readonly updateStatus: (
|
||||
input: UpdateAuthConnectClientStatusInput,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
|
||||
readonly revoke: (
|
||||
input: RevokeAuthConnectClientInput,
|
||||
) => Effect.Effect<boolean, AuthConnectClientRepositoryError>;
|
||||
readonly markSeen: (
|
||||
input: MarkAuthConnectClientSeenInput,
|
||||
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthConnectClientRecord>,
|
||||
AuthConnectClientRepositoryError
|
||||
>;
|
||||
}
|
||||
>()("t3/persistence/AuthConnectClients/AuthConnectClientRepository") {}
|
||||
|
||||
const AuthConnectClientDbRow = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
cloudUserId: Schema.String,
|
||||
deviceId: Schema.NullOr(Schema.String),
|
||||
status: AuthConnectClientStatus,
|
||||
clientLabel: Schema.NullOr(Schema.String),
|
||||
clientIpAddress: Schema.NullOr(Schema.String),
|
||||
clientUserAgent: Schema.NullOr(Schema.String),
|
||||
clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
|
||||
clientOs: Schema.NullOr(Schema.String),
|
||||
clientBrowser: Schema.NullOr(Schema.String),
|
||||
requestedAt: Schema.DateTimeUtcFromString,
|
||||
updatedAt: Schema.DateTimeUtcFromString,
|
||||
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
|
||||
const AuthConnectClientRawDbRow = Schema.Struct({
|
||||
clientProofKeyThumbprint: Schema.String,
|
||||
cloudUserId: Schema.Unknown,
|
||||
deviceId: Schema.Unknown,
|
||||
status: Schema.Unknown,
|
||||
clientLabel: Schema.Unknown,
|
||||
clientIpAddress: Schema.Unknown,
|
||||
clientUserAgent: Schema.Unknown,
|
||||
clientDeviceType: Schema.Unknown,
|
||||
clientOs: Schema.Unknown,
|
||||
clientBrowser: Schema.Unknown,
|
||||
requestedAt: Schema.Unknown,
|
||||
updatedAt: Schema.Unknown,
|
||||
approvedAt: Schema.Unknown,
|
||||
rejectedAt: Schema.Unknown,
|
||||
revokedAt: Schema.Unknown,
|
||||
lastSeenAt: Schema.Unknown,
|
||||
});
|
||||
|
||||
const decodeAuthConnectClientDbRow = Schema.decodeUnknownEffect(AuthConnectClientDbRow);
|
||||
|
||||
function toAuthConnectClientRecord(
|
||||
row: typeof AuthConnectClientDbRow.Type,
|
||||
): AuthConnectClientRecord {
|
||||
return {
|
||||
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
|
||||
cloudUserId: row.cloudUserId,
|
||||
deviceId: row.deviceId,
|
||||
status: row.status,
|
||||
client: {
|
||||
label: row.clientLabel,
|
||||
ipAddress: row.clientIpAddress,
|
||||
userAgent: row.clientUserAgent,
|
||||
deviceType: row.clientDeviceType,
|
||||
os: row.clientOs,
|
||||
browser: row.clientBrowser,
|
||||
},
|
||||
requestedAt: row.requestedAt,
|
||||
updatedAt: row.updatedAt,
|
||||
approvedAt: row.approvedAt,
|
||||
rejectedAt: row.rejectedAt,
|
||||
revokedAt: row.revokedAt,
|
||||
lastSeenAt: row.lastSeenAt,
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(
|
||||
sqlOperation: string,
|
||||
decodeOperation: string,
|
||||
correlation?: PersistenceErrorCorrelation,
|
||||
) {
|
||||
return (cause: unknown): AuthConnectClientRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
|
||||
: new PersistenceSqlError({
|
||||
operation: sqlOperation,
|
||||
...(correlation === undefined ? {} : { correlation }),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
const rowSelection = `
|
||||
client_proof_key_thumbprint AS "clientProofKeyThumbprint",
|
||||
cloud_user_id AS "cloudUserId",
|
||||
device_id AS "deviceId",
|
||||
status AS "status",
|
||||
client_label AS "clientLabel",
|
||||
client_ip_address AS "clientIpAddress",
|
||||
client_user_agent AS "clientUserAgent",
|
||||
client_device_type AS "clientDeviceType",
|
||||
client_os AS "clientOs",
|
||||
client_browser AS "clientBrowser",
|
||||
requested_at AS "requestedAt",
|
||||
updated_at AS "updatedAt",
|
||||
approved_at AS "approvedAt",
|
||||
rejected_at AS "rejectedAt",
|
||||
revoked_at AS "revokedAt",
|
||||
last_seen_at AS "lastSeenAt"
|
||||
`;
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertRequestRow = SqlSchema.findOne({
|
||||
Request: UpsertAuthConnectClientRequestInput,
|
||||
Result: AuthConnectClientRawDbRow,
|
||||
execute: (input) =>
|
||||
sql`
|
||||
INSERT INTO auth_connect_clients (
|
||||
client_proof_key_thumbprint,
|
||||
cloud_user_id,
|
||||
device_id,
|
||||
status,
|
||||
client_label,
|
||||
client_ip_address,
|
||||
client_user_agent,
|
||||
client_device_type,
|
||||
client_os,
|
||||
client_browser,
|
||||
requested_at,
|
||||
updated_at,
|
||||
approved_at,
|
||||
rejected_at,
|
||||
revoked_at,
|
||||
last_seen_at
|
||||
)
|
||||
VALUES (
|
||||
${input.clientProofKeyThumbprint},
|
||||
${input.cloudUserId},
|
||||
${input.deviceId},
|
||||
'pending',
|
||||
${input.client.label},
|
||||
${input.client.ipAddress},
|
||||
${input.client.userAgent},
|
||||
${input.client.deviceType},
|
||||
${input.client.os},
|
||||
${input.client.browser},
|
||||
${input.requestedAt},
|
||||
${input.requestedAt},
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL
|
||||
)
|
||||
ON CONFLICT(client_proof_key_thumbprint) DO UPDATE SET
|
||||
cloud_user_id = excluded.cloud_user_id,
|
||||
device_id = excluded.device_id,
|
||||
status = CASE
|
||||
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.status
|
||||
ELSE 'pending'
|
||||
END,
|
||||
client_label = excluded.client_label,
|
||||
client_ip_address = excluded.client_ip_address,
|
||||
client_user_agent = excluded.client_user_agent,
|
||||
client_device_type = excluded.client_device_type,
|
||||
client_os = excluded.client_os,
|
||||
client_browser = excluded.client_browser,
|
||||
requested_at = excluded.requested_at,
|
||||
updated_at = excluded.updated_at,
|
||||
approved_at = CASE
|
||||
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.approved_at
|
||||
ELSE NULL
|
||||
END,
|
||||
rejected_at = CASE
|
||||
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.rejected_at
|
||||
ELSE NULL
|
||||
END,
|
||||
last_seen_at = CASE
|
||||
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.last_seen_at
|
||||
ELSE NULL
|
||||
END,
|
||||
revoked_at = NULL
|
||||
RETURNING ${sql.unsafe(rowSelection)}
|
||||
`,
|
||||
});
|
||||
|
||||
const updateStatusRow = SqlSchema.findOneOption({
|
||||
Request: UpdateAuthConnectClientStatusInput,
|
||||
Result: AuthConnectClientRawDbRow,
|
||||
execute: ({ clientProofKeyThumbprint, status, decidedAt }) =>
|
||||
sql`
|
||||
UPDATE auth_connect_clients
|
||||
SET
|
||||
status = ${status},
|
||||
updated_at = ${decidedAt},
|
||||
approved_at = CASE WHEN ${status} = 'approved' THEN ${decidedAt} ELSE approved_at END,
|
||||
rejected_at = CASE WHEN ${status} = 'rejected' THEN ${decidedAt} ELSE rejected_at END,
|
||||
revoked_at = NULL
|
||||
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
|
||||
AND revoked_at IS NULL
|
||||
RETURNING ${sql.unsafe(rowSelection)}
|
||||
`,
|
||||
});
|
||||
|
||||
const revokeRow = SqlSchema.findAll({
|
||||
Request: RevokeAuthConnectClientInput,
|
||||
Result: Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
|
||||
execute: ({ clientProofKeyThumbprint, revokedAt }) =>
|
||||
sql`
|
||||
UPDATE auth_connect_clients
|
||||
SET
|
||||
revoked_at = ${revokedAt},
|
||||
updated_at = ${revokedAt}
|
||||
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
|
||||
AND revoked_at IS NULL
|
||||
RETURNING client_proof_key_thumbprint AS "clientProofKeyThumbprint"
|
||||
`,
|
||||
});
|
||||
|
||||
const markSeenRow = SqlSchema.findOneOption({
|
||||
Request: MarkAuthConnectClientSeenInput,
|
||||
Result: AuthConnectClientRawDbRow,
|
||||
execute: ({ clientProofKeyThumbprint, seenAt }) =>
|
||||
sql`
|
||||
UPDATE auth_connect_clients
|
||||
SET
|
||||
last_seen_at = ${seenAt},
|
||||
updated_at = ${seenAt}
|
||||
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
|
||||
AND status = 'approved'
|
||||
AND revoked_at IS NULL
|
||||
RETURNING ${sql.unsafe(rowSelection)}
|
||||
`,
|
||||
});
|
||||
|
||||
const listRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: AuthConnectClientRawDbRow,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT ${sql.unsafe(rowSelection)}
|
||||
FROM auth_connect_clients
|
||||
WHERE revoked_at IS NULL
|
||||
ORDER BY
|
||||
CASE status
|
||||
WHEN 'pending' THEN 0
|
||||
WHEN 'approved' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
updated_at DESC,
|
||||
client_proof_key_thumbprint DESC
|
||||
`,
|
||||
});
|
||||
|
||||
const decodeRow = (
|
||||
row: typeof AuthConnectClientRawDbRow.Type,
|
||||
operation: string,
|
||||
): Effect.Effect<AuthConnectClientRecord, PersistenceDecodeError> =>
|
||||
decodeAuthConnectClientDbRow(row).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
PersistenceDecodeError.fromSchemaError(operation, cause, {
|
||||
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
|
||||
}),
|
||||
),
|
||||
Effect.map(toAuthConnectClientRecord),
|
||||
);
|
||||
|
||||
const upsertRequest: AuthConnectClientRepository["Service"]["upsertRequest"] = (input) =>
|
||||
upsertRequestRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"AuthConnectClientRepository.upsertRequest:query",
|
||||
"AuthConnectClientRepository.upsertRequest:decodeRow",
|
||||
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((row) =>
|
||||
decodeRow(row, "AuthConnectClientRepository.upsertRequest:decodeRow"),
|
||||
),
|
||||
);
|
||||
|
||||
const updateStatus: AuthConnectClientRepository["Service"]["updateStatus"] = (input) =>
|
||||
updateStatusRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"AuthConnectClientRepository.updateStatus:query",
|
||||
"AuthConnectClientRepository.updateStatus:decodeRow",
|
||||
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rowOption) =>
|
||||
Option.match(rowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeRow(row, "AuthConnectClientRepository.updateStatus:decodeRow").pipe(
|
||||
Effect.map(Option.some),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revoke: AuthConnectClientRepository["Service"]["revoke"] = (input) =>
|
||||
revokeRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"AuthConnectClientRepository.revoke:query",
|
||||
"AuthConnectClientRepository.revoke:decodeRows",
|
||||
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
|
||||
),
|
||||
),
|
||||
Effect.map((rows) => rows.length > 0),
|
||||
);
|
||||
|
||||
const markSeen: AuthConnectClientRepository["Service"]["markSeen"] = (input) =>
|
||||
markSeenRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"AuthConnectClientRepository.markSeen:query",
|
||||
"AuthConnectClientRepository.markSeen:decodeRow",
|
||||
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rowOption) =>
|
||||
Option.match(rowOption, {
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeRow(row, "AuthConnectClientRepository.markSeen:decodeRow").pipe(
|
||||
Effect.map(Option.some),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: AuthConnectClientRepository["Service"]["listActive"] = () =>
|
||||
listRows().pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"AuthConnectClientRepository.listActive:query",
|
||||
"AuthConnectClientRepository.listActive:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeRow(row, "AuthConnectClientRepository.listActive:decodeRows"),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsertRequest,
|
||||
updateStatus,
|
||||
revoke,
|
||||
markSeen,
|
||||
listActive,
|
||||
} satisfies AuthConnectClientRepository["Service"];
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(AuthConnectClientRepository, make);
|
||||
@@ -23,6 +23,7 @@ export const PersistenceErrorCorrelation = Schema.Union([
|
||||
Schema.Struct({ sessionId: Schema.String }),
|
||||
Schema.Struct({ currentSessionId: Schema.String }),
|
||||
Schema.Struct({ pairingLinkId: Schema.String }),
|
||||
Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
|
||||
Schema.Struct({ threadId: Schema.String }),
|
||||
]);
|
||||
export type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;
|
||||
@@ -134,5 +135,6 @@ export type OrchestrationCommandReceiptRepositoryError =
|
||||
export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;
|
||||
export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;
|
||||
export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
|
||||
export type AuthConnectClientRepositoryError = PersistenceSqlError | PersistenceDecodeError;
|
||||
|
||||
export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
|
||||
@@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
|
||||
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
|
||||
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_AuthConnectClientApprovals.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -89,6 +90,7 @@ export const migrationEntries = [
|
||||
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
|
||||
[31, "AuthAuthorizationScopes", Migration0031],
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "AuthConnectClientApprovals", Migration0033],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS auth_connect_clients (
|
||||
client_proof_key_thumbprint TEXT PRIMARY KEY,
|
||||
cloud_user_id TEXT NOT NULL,
|
||||
device_id TEXT,
|
||||
status TEXT NOT NULL,
|
||||
client_label TEXT,
|
||||
client_ip_address TEXT,
|
||||
client_user_agent TEXT,
|
||||
client_device_type TEXT NOT NULL DEFAULT 'unknown',
|
||||
client_os TEXT,
|
||||
client_browser TEXT,
|
||||
requested_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
approved_at TEXT,
|
||||
rejected_at TEXT,
|
||||
revoked_at TEXT,
|
||||
last_seen_at TEXT
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_active
|
||||
ON auth_connect_clients(revoked_at, status, updated_at)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_cloud_user
|
||||
ON auth_connect_clients(cloud_user_id, revoked_at)
|
||||
`;
|
||||
});
|
||||
@@ -151,6 +151,61 @@ 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();
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type PreviewOpenInput,
|
||||
type PreviewRefreshInput,
|
||||
type PreviewReportStatusInput,
|
||||
type PreviewResizeInput,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
PreviewSessionLookupError,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -45,6 +47,9 @@ 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>;
|
||||
@@ -114,6 +119,7 @@ const buildLoadingSnapshot = (input: {
|
||||
navStatus: { _tag: "Loading", url: input.url, title: input.title },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -127,6 +133,7 @@ const buildIdleSnapshot = (input: {
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport: FILL_PREVIEW_VIEWPORT,
|
||||
updatedAt: input.updatedAt,
|
||||
});
|
||||
|
||||
@@ -237,6 +244,7 @@ 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 {
|
||||
@@ -269,6 +277,7 @@ 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 =
|
||||
@@ -299,6 +308,34 @@ 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
|
||||
@@ -360,6 +397,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
open,
|
||||
navigate,
|
||||
reportStatus,
|
||||
resize,
|
||||
refresh,
|
||||
close,
|
||||
list,
|
||||
|
||||
@@ -113,6 +113,23 @@ 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
|
||||
@@ -1004,7 +1021,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
assert.equal(turnCompleted.payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
const requests = yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(entry) => entry.method === "session/cancel",
|
||||
);
|
||||
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
|
||||
assert.isTrue(
|
||||
requests.some(
|
||||
|
||||
@@ -785,6 +785,9 @@ 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,20 +10,23 @@ 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,
|
||||
ThreadId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -45,7 +48,11 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
|
||||
function waitForFileContent(
|
||||
filePath: string,
|
||||
attempts = 40,
|
||||
expectedContent?: string,
|
||||
): Effect.Effect<string> {
|
||||
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
|
||||
Effect.gen(function* () {
|
||||
if (remainingAttempts <= 0) {
|
||||
@@ -54,7 +61,10 @@ function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<stri
|
||||
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
if (raw.trim().length > 0) {
|
||||
if (
|
||||
raw.trim().length > 0 &&
|
||||
(expectedContent === undefined || raw.includes(expectedContent))
|
||||
) {
|
||||
return raw;
|
||||
}
|
||||
yield* Effect.sleep("25 millis");
|
||||
@@ -79,6 +89,39 @@ 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* () {
|
||||
@@ -175,6 +218,783 @@ 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());
|
||||
@@ -331,6 +1151,7 @@ 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);
|
||||
|
||||
@@ -22,6 +22,7 @@ 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";
|
||||
@@ -62,6 +63,7 @@ import {
|
||||
extractXAiAskUserQuestions,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
@@ -108,6 +110,8 @@ 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. */
|
||||
@@ -136,10 +140,38 @@ 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;
|
||||
@@ -170,6 +202,28 @@ 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");
|
||||
@@ -240,6 +294,144 @@ 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;
|
||||
@@ -271,6 +463,8 @@ 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<{
|
||||
@@ -282,17 +476,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
method: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
|
||||
if (ctx.lastPlanFingerprint === fingerprint) {
|
||||
return;
|
||||
}
|
||||
ctx.lastPlanFingerprint = fingerprint;
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId,
|
||||
payload,
|
||||
source: "acp.jsonrpc",
|
||||
method,
|
||||
@@ -424,13 +618,14 @@ 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: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractXAiAskUserQuestions(params) },
|
||||
raw: {
|
||||
@@ -447,7 +642,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolvedAnswers },
|
||||
raw: {
|
||||
@@ -486,13 +681,14 @@ 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: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
@@ -512,7 +708,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: sessions.get(input.threadId)?.activeTurnId,
|
||||
turnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
@@ -578,6 +774,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
@@ -586,14 +783,39 @@ 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: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
@@ -602,40 +824,44 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
case "AssistantItemCompleted":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
itemId: event.itemId,
|
||||
lifecycle: "item.completed",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "PlanUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
stamp,
|
||||
event.payload,
|
||||
event.rawPayload,
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
toolCall: event.toolCall,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
turnId: notificationTurnId,
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
@@ -697,6 +923,15 @@ 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 =
|
||||
@@ -765,12 +1000,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
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.",
|
||||
});
|
||||
}
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
@@ -796,13 +1046,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
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,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
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
|
||||
@@ -810,6 +1074,18 @@ 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),
|
||||
),
|
||||
@@ -820,38 +1096,88 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
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 }] },
|
||||
];
|
||||
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);
|
||||
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 (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
// 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);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -860,9 +1186,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
stopReason: completedStopReason,
|
||||
},
|
||||
});
|
||||
ctx.interruptedTurnIds.delete(prepared.turnId);
|
||||
yield* Ref.set(promptSettled, true);
|
||||
} else if (remainingPrompts > 0) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -874,27 +1204,153 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.get(promptSettled)) {
|
||||
return;
|
||||
}
|
||||
}),
|
||||
|
||||
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) =>
|
||||
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
|
||||
Effect.gen(function* () {
|
||||
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),
|
||||
),
|
||||
),
|
||||
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,
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ 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";
|
||||
|
||||
@@ -113,6 +116,122 @@ 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;
|
||||
@@ -346,6 +465,109 @@ 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,6 +8,8 @@ import {
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
describe("AcpRuntimeModel", () => {
|
||||
@@ -59,6 +61,95 @@ 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,3 +1,8 @@
|
||||
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";
|
||||
@@ -6,6 +11,40 @@ 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;
|
||||
@@ -414,6 +453,58 @@ 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>;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
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 Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
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";
|
||||
@@ -23,6 +27,9 @@ import {
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
waitForSessionLoadReplayIdle,
|
||||
type SessionLoadGate,
|
||||
type AcpParsedSessionEvent,
|
||||
type AcpSessionModeState,
|
||||
type AcpToolCallState,
|
||||
@@ -32,6 +39,16 @@ 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>;
|
||||
@@ -43,6 +60,8 @@ 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;
|
||||
@@ -160,7 +179,9 @@ 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<AcpParsedSessionEvent, never>;
|
||||
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
|
||||
/** Waits until the current event consumer has processed every queued event. */
|
||||
readonly drainEvents: Effect.Effect<void>;
|
||||
/** 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. */
|
||||
@@ -254,12 +275,17 @@ export const make = (
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
|
||||
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;
|
||||
@@ -331,15 +357,40 @@ export const make = (
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: 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,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
@@ -499,27 +550,74 @@ export const make = (
|
||||
cwd: options.cwd,
|
||||
mcpServers: options.mcpServers ?? [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
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),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
return loaded;
|
||||
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
@@ -596,25 +694,48 @@ 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) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
promptSerializationSemaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const started = yield* getStartedState;
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
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());
|
||||
}),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
@@ -626,7 +747,17 @@ export const make = (
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
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));
|
||||
}),
|
||||
),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
@@ -705,7 +836,7 @@ const handleSessionUpdate = ({
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
@@ -801,7 +932,7 @@ const ensureActiveAssistantSegment = ({
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
@@ -838,7 +969,7 @@ const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ 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";
|
||||
@@ -68,9 +69,10 @@ export const makeGrokAcpRuntime = (
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
|
||||
Effect.provide(acpContext),
|
||||
);
|
||||
return yield* makeXAiPromptCompletionRuntime(runtime);
|
||||
});
|
||||
|
||||
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
|
||||
|
||||
@@ -1,12 +1,39 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
// @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 * 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);
|
||||
|
||||
@@ -247,4 +274,59 @@ 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,5 +1,29 @@
|
||||
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,
|
||||
@@ -171,3 +195,238 @@ 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";
|
||||
}
|
||||
}
|
||||
@@ -653,6 +653,7 @@ 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,
|
||||
@@ -3233,6 +3234,32 @@ 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();
|
||||
@@ -4099,6 +4126,46 @@ 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;
|
||||
|
||||
@@ -36,6 +36,7 @@ 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";
|
||||
@@ -357,7 +358,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
).pipe(Layer.provide(browserApiCorsLayer));
|
||||
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
|
||||
|
||||
export const makeServerLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
|
||||
+54
-22
@@ -110,6 +110,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
|
||||
import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import * as ConnectClientStore from "./auth/ConnectClientStore.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
|
||||
@@ -330,14 +331,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.previewAutomationReportOwner, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationClearOwner, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.previewAutomationFocusHost, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribePreviewEvents, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeDiscoveredLocalServers, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],
|
||||
@@ -346,7 +347,10 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
]);
|
||||
|
||||
function toAuthAccessStreamEvent(
|
||||
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
|
||||
change:
|
||||
| PairingGrantStore.BootstrapCredentialChange
|
||||
| SessionStore.SessionCredentialChange
|
||||
| ConnectClientStore.ConnectClientChange,
|
||||
revision: number,
|
||||
currentSessionId: AuthSessionId,
|
||||
): AuthAccessStreamEvent {
|
||||
@@ -382,10 +386,34 @@ function toAuthAccessStreamEvent(
|
||||
type: "clientRemoved",
|
||||
payload: { sessionId: change.sessionId },
|
||||
};
|
||||
case "connectSecurityModeUpdated":
|
||||
return {
|
||||
version: 1,
|
||||
revision,
|
||||
type: "connectSecurityModeUpdated",
|
||||
payload: { mode: change.mode },
|
||||
};
|
||||
case "connectClientUpserted":
|
||||
return {
|
||||
version: 1,
|
||||
revision,
|
||||
type: "connectClientUpserted",
|
||||
payload: change.client,
|
||||
};
|
||||
case "connectClientRemoved":
|
||||
return {
|
||||
version: 1,
|
||||
revision,
|
||||
type: "connectClientRemoved",
|
||||
payload: { clientProofKeyThumbprint: change.clientProofKeyThumbprint },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
const makeWsRpcLayer = (
|
||||
currentSession: EnvironmentAuth.AuthenticatedSession,
|
||||
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
|
||||
) =>
|
||||
WsRpcGroup.toLayer(
|
||||
Effect.gen(function* () {
|
||||
const currentSessionId = currentSession.sessionId;
|
||||
@@ -400,7 +428,6 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
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;
|
||||
@@ -510,6 +537,8 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
|
||||
const loadAuthAccessSnapshot = () =>
|
||||
Effect.all({
|
||||
connectSecurityMode: serverAuth.getConnectSecurityMode(),
|
||||
connectClients: serverAuth.listConnectClients(),
|
||||
pairingLinks: serverAuth.listPairingLinks(),
|
||||
clientSessions: serverAuth.listClientSessions(currentSessionId),
|
||||
}).pipe(
|
||||
@@ -1622,6 +1651,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
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",
|
||||
@@ -1650,16 +1683,10 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
previewAutomationBroker.respond(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.previewAutomationReportOwner]: (input) =>
|
||||
[WS_METHODS.previewAutomationFocusHost]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.previewAutomationReportOwner,
|
||||
previewAutomationBroker.reportOwner(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.previewAutomationClearOwner]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.previewAutomationClearOwner,
|
||||
previewAutomationBroker.clearOwner(input),
|
||||
WS_METHODS.previewAutomationFocusHost,
|
||||
previewAutomationBroker.focusHost(input),
|
||||
{ "rpc.aggregate": "preview-automation" },
|
||||
),
|
||||
[WS_METHODS.subscribePreviewEvents]: (_input) =>
|
||||
@@ -1761,8 +1788,13 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
const initialSnapshot = yield* loadAuthAccessSnapshot();
|
||||
const revisionRef = yield* Ref.make(1);
|
||||
const accessChanges: Stream.Stream<
|
||||
PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange
|
||||
> = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
|
||||
| PairingGrantStore.BootstrapCredentialChange
|
||||
| SessionStore.SessionCredentialChange
|
||||
| ConnectClientStore.ConnectClientChange
|
||||
> = Stream.merge(
|
||||
Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges),
|
||||
serverAuth.streamConnectClientChanges,
|
||||
);
|
||||
|
||||
const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
|
||||
Stream.mapEffect((change) =>
|
||||
@@ -1791,8 +1823,9 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
);
|
||||
|
||||
export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
Effect.succeed(
|
||||
HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
return HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
Effect.gen(function* () {
|
||||
@@ -1811,9 +1844,8 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
disableTracing: true,
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeWsRpcLayer(session).pipe(
|
||||
makeWsRpcLayer(session, previewAutomationBroker).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(
|
||||
SourceControlDiscovery.layer.pipe(
|
||||
@@ -1850,6 +1882,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -22,7 +22,7 @@
|
||||
"@fontsource-variable/dm-sans": "^5.2.8",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.0.0-beta.44",
|
||||
"@legendapp/list": "3.2.0",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
|
||||
@@ -3,20 +3,22 @@ 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 the Electron browser host", () => {
|
||||
it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => {
|
||||
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(2);
|
||||
expect(children).toHaveLength(3);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(ElectronBrowserHost);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
|
||||
@@ -13,6 +14,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
return (
|
||||
<AppAtomRegistryProvider>
|
||||
<RouterProvider router={router} />
|
||||
<PreviewAutomationHosts />
|
||||
<ElectronBrowserHost />
|
||||
</AppAtomRegistryProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,340 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
"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}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"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";
|
||||
@@ -22,7 +23,7 @@ export function ElectronBrowserHost() {
|
||||
? Object.values(previewState.sessions).map((snapshot) => ({
|
||||
threadRef,
|
||||
snapshot,
|
||||
active: previewState.activeTabId === snapshot.tabId,
|
||||
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
|
||||
}))
|
||||
: [];
|
||||
}),
|
||||
@@ -73,7 +74,7 @@ export function ElectronBrowserHost() {
|
||||
if (!isElectron) return null;
|
||||
return (
|
||||
<div className="contents" data-electron-browser-host>
|
||||
{sessions.map(({ threadRef, snapshot }) => {
|
||||
{sessions.map(({ threadRef, snapshot, zoomFactor }) => {
|
||||
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return (
|
||||
<HostedBrowserWebview
|
||||
@@ -81,6 +82,8 @@ export function ElectronBrowserHost() {
|
||||
threadRef={threadRef}
|
||||
tabId={snapshot.tabId}
|
||||
initialUrl={url}
|
||||
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
|
||||
zoomFactor={zoomFactor}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { useActiveBrowserRecordingTabId } from "./browserRecording";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { browserViewportSettingKey } from "./browserViewportLayout";
|
||||
import { reconcileLockedAspectRatio } from "./browserDeviceToolbarState";
|
||||
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
|
||||
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
|
||||
import { useBrowserViewportResize } from "./useBrowserViewportResize";
|
||||
|
||||
interface ElectronWebview extends HTMLElement {
|
||||
src: string;
|
||||
@@ -18,6 +24,7 @@ interface ElectronWebview extends HTMLElement {
|
||||
preload?: string;
|
||||
webpreferences?: string;
|
||||
getWebContentsId: () => number;
|
||||
executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -30,13 +37,25 @@ export function HostedBrowserWebview(props: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly tabId: string;
|
||||
readonly initialUrl: string | null;
|
||||
readonly viewport: PreviewViewportSetting;
|
||||
readonly zoomFactor: number;
|
||||
}) {
|
||||
const { threadRef, tabId, initialUrl } = props;
|
||||
const { threadRef, tabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const initialSrcRef = useRef(initialUrl ?? "about:blank");
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
const webviewRef = useRef<ElectronWebview | null>(null);
|
||||
const presentation = useBrowserSurfaceStore(useShallow((state) => state.byTabId[tabId] ?? 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 recording = useActiveBrowserRecordingTabId() === tabId;
|
||||
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
@@ -89,10 +108,69 @@ 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 active = presentation?.visible === true && presentation.rect !== null;
|
||||
const lastRect = presentation?.rect;
|
||||
const style =
|
||||
|
||||
const wrapperStyle =
|
||||
active && lastRect
|
||||
? {
|
||||
left: lastRect.x,
|
||||
@@ -105,23 +183,86 @@ export function HostedBrowserWebview(props: {
|
||||
: {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: lastRect?.width ?? 1280,
|
||||
height: lastRect?.height ?? 800,
|
||||
width: hiddenSize.width,
|
||||
height: hiddenSize.height,
|
||||
zIndex: recording ? 0 : -1,
|
||||
pointerEvents: "none" as const,
|
||||
};
|
||||
|
||||
return (
|
||||
<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}
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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);
|
||||
}
|
||||
@@ -90,6 +90,10 @@ 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";
|
||||
@@ -137,10 +141,11 @@ export async function startBrowserRecording(tabId: string): Promise<string> {
|
||||
activeTabId: active.tabId,
|
||||
});
|
||||
}
|
||||
const rect = useBrowserSurfaceStore.getState().byTabId[tabId]?.rect;
|
||||
const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
|
||||
const recordingSize = surface?.content ?? surface?.rect;
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, rect?.width ?? 1280);
|
||||
canvas.height = Math.max(1, rect?.height ?? 800);
|
||||
canvas.width = Math.max(1, recordingSize?.width ?? 1280);
|
||||
canvas.height = Math.max(1, recordingSize?.height ?? 800);
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) {
|
||||
throw new BrowserRecordingCanvasUnavailableError({
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export function resolveBrowserRecordingStopTarget(activeTabId: string | null): string | null {
|
||||
return activeTabId;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -10,15 +10,47 @@ 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 &&
|
||||
@@ -35,7 +67,43 @@ export const useBrowserSurfaceStore = create<BrowserSurfaceStoreState>()((set) =
|
||||
return {
|
||||
byTabId: {
|
||||
...state.byTabId,
|
||||
[tabId]: { rect, visible, updatedAt: Date.now() },
|
||||
[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() },
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
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 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
"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,
|
||||
};
|
||||
}
|
||||
@@ -205,6 +205,7 @@ describe("web cloud link environment client", () => {
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: false,
|
||||
connectSecurityMode: "account",
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
@@ -218,6 +219,7 @@ describe("web cloud link environment client", () => {
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: false,
|
||||
connectSecurityMode: "account",
|
||||
}),
|
||||
);
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
|
||||
@@ -235,6 +237,7 @@ describe("web cloud link environment client", () => {
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: false,
|
||||
connectSecurityMode: "account",
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
@@ -262,6 +265,7 @@ describe("web cloud link environment client", () => {
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: true,
|
||||
connectSecurityMode: "account",
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
@@ -518,7 +518,7 @@ export function BranchToolbarBranchSelector({
|
||||
return;
|
||||
}
|
||||
|
||||
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
|
||||
}, [deferredTrimmedBranchQuery, isBranchMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -628,7 +628,7 @@ export function BranchToolbarBranchSelector({
|
||||
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
|
||||
return;
|
||||
}
|
||||
branchListRef.current?.scrollIndexIntoView?.({
|
||||
void branchListRef.current?.scrollIndexIntoView?.({
|
||||
index: eventDetails.index,
|
||||
animated: false,
|
||||
});
|
||||
@@ -696,6 +696,13 @@ export function BranchToolbarBranchSelector({
|
||||
ref={branchListRef}
|
||||
data={filteredBranchPickerItems}
|
||||
keyExtractor={(item) => item}
|
||||
getItemType={(item) =>
|
||||
item === checkoutPullRequestItemValue
|
||||
? "checkout-pull-request"
|
||||
: item === createBranchItemValue
|
||||
? "create-branch"
|
||||
: "branch"
|
||||
}
|
||||
renderItem={({ item, index }) => renderPickerItem(item, index)}
|
||||
estimatedItemSize={28}
|
||||
drawDistance={336}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildThreadTurnInterruptInput,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
getStartedThreadModelChangeBlockReason,
|
||||
@@ -69,6 +70,30 @@ 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({
|
||||
|
||||
@@ -74,6 +74,17 @@ 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>;
|
||||
|
||||
@@ -36,12 +36,23 @@ import {
|
||||
createModelSelection,
|
||||
resolvePromptInjectedEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { truncate } from "@t3tools/shared/String";
|
||||
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
lazy,
|
||||
memo,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import {
|
||||
@@ -119,7 +130,6 @@ 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";
|
||||
@@ -205,6 +215,7 @@ import {
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
buildLocalDraftThread,
|
||||
buildThreadTurnInterruptInput,
|
||||
collectUserMessageBlobPreviewUrls,
|
||||
createLocalDispatchSnapshot,
|
||||
deriveComposerSendState,
|
||||
@@ -1137,12 +1148,32 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
LastInvokedScriptByProjectSchema,
|
||||
);
|
||||
const legendListRef = useRef<LegendListRef | null>(null);
|
||||
const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);
|
||||
const [composerOverlayHeight, setComposerOverlayHeight] = useState(0);
|
||||
const isAtEndRef = useRef(true);
|
||||
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
|
||||
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
|
||||
const sendInFlightRef = useRef(false);
|
||||
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!composerOverlayElement) return;
|
||||
|
||||
const updateHeight = () => {
|
||||
const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height);
|
||||
setComposerOverlayHeight((currentHeight) =>
|
||||
currentHeight === nextHeight ? currentHeight : nextHeight,
|
||||
);
|
||||
};
|
||||
|
||||
updateHeight();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver(updateHeight);
|
||||
observer.observe(composerOverlayElement);
|
||||
return () => observer.disconnect();
|
||||
}, [composerOverlayElement]);
|
||||
|
||||
const terminalUiState = useTerminalUiStateStore((state) =>
|
||||
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
|
||||
);
|
||||
@@ -1254,6 +1285,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
[activeThread],
|
||||
);
|
||||
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
|
||||
const [timelineAnchor, setTimelineAnchor] = useState<{
|
||||
readonly threadKey: string | null;
|
||||
readonly messageId: MessageId | null;
|
||||
}>({ threadKey: activeThreadKey, messageId: null });
|
||||
if (timelineAnchor.threadKey !== activeThreadKey) {
|
||||
setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
|
||||
}
|
||||
const timelineAnchorMessageId = timelineAnchor.messageId;
|
||||
const activeRightPanelKind = useRightPanelStore((state) =>
|
||||
selectActiveRightPanel(state.byThreadKey, activeThreadRef),
|
||||
);
|
||||
@@ -3109,9 +3148,82 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
],
|
||||
);
|
||||
|
||||
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
|
||||
// Scrolling is explicit so streamed timeline updates never take control away
|
||||
// from the user after the newly sent row has been positioned once.
|
||||
const scrollToEnd = useCallback((animated = false) => {
|
||||
legendListRef.current?.scrollToEnd?.({ animated });
|
||||
void legendListRef.current?.scrollToEnd?.({ animated });
|
||||
}, []);
|
||||
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
|
||||
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
|
||||
const pendingAnchorScrollRestoreRef = useRef<{
|
||||
readonly messageId: MessageId;
|
||||
readonly offset: number;
|
||||
} | null>(null);
|
||||
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
|
||||
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
|
||||
if (positionedTimelineAnchorRef.current === messageId) {
|
||||
return;
|
||||
}
|
||||
positionedTimelineAnchorRef.current = messageId;
|
||||
settledTimelineAnchorRef.current = null;
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (positionedTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
const list = legendListRef.current;
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
const scrollNode = list.getScrollableNode();
|
||||
let finished = false;
|
||||
const finishAnimatedPositioning = () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
window.clearTimeout(fallbackTimer);
|
||||
scrollNode.removeEventListener("scrollend", finishAnimatedPositioning);
|
||||
if (positionedTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
const scrollOffset = list.getState().scroll;
|
||||
void list.scrollToOffset({ offset: scrollOffset, animated: false });
|
||||
settledTimelineAnchorRef.current = messageId;
|
||||
};
|
||||
const fallbackTimer = window.setTimeout(finishAnimatedPositioning, 750);
|
||||
scrollNode.addEventListener("scrollend", finishAnimatedPositioning, { once: true });
|
||||
void list.scrollToIndex({
|
||||
index: anchorIndex,
|
||||
animated: true,
|
||||
viewPosition: 0,
|
||||
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
|
||||
});
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
|
||||
if (settledTimelineAnchorRef.current !== messageId) {
|
||||
return;
|
||||
}
|
||||
const scrollOffset = legendListRef.current?.getState().scroll;
|
||||
if (scrollOffset === undefined) {
|
||||
return;
|
||||
}
|
||||
if (pendingAnchorScrollRestoreRef.current === null) {
|
||||
pendingAnchorScrollRestoreRef.current = { messageId, offset: scrollOffset };
|
||||
}
|
||||
if (anchorScrollRestoreFrameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
|
||||
anchorScrollRestoreFrameRef.current = null;
|
||||
const pending = pendingAnchorScrollRestoreRef.current;
|
||||
pendingAnchorScrollRestoreRef.current = null;
|
||||
if (pending && settledTimelineAnchorRef.current === pending.messageId) {
|
||||
void legendListRef.current?.scrollToOffset({ offset: pending.offset, animated: false });
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
|
||||
@@ -3690,14 +3802,16 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
// Scroll to the current end *before* adding the optimistic message.
|
||||
// This sets LegendList's internal isAtEnd=true so maintainScrollAtEnd
|
||||
// automatically pins to the new item when the data changes.
|
||||
// Sending always returns to the live edge. The new row becomes the
|
||||
// anchored end-space target so it lands near the top while the response
|
||||
// streams into the reserved space below it.
|
||||
isAtEndRef.current = true;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
await legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
|
||||
setTimelineAnchor({
|
||||
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
|
||||
messageId: messageIdForSend,
|
||||
});
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
{
|
||||
@@ -3711,7 +3825,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
streaming: false,
|
||||
},
|
||||
]);
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
@@ -3901,9 +4014,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!activeThread) return;
|
||||
const result = await interruptThreadTurn({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: activeThread.id,
|
||||
},
|
||||
input: buildThreadTurnInterruptInput(activeThread),
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
@@ -4126,11 +4237,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
beginLocalDispatch({ preparingWorktree: false });
|
||||
setThreadError(threadIdForSend, null);
|
||||
|
||||
// Scroll to the current end *before* adding the optimistic message.
|
||||
// Position this sent row once LegendList has measured the anchored tail.
|
||||
isAtEndRef.current = true;
|
||||
showScrollDebouncer.current.cancel();
|
||||
setShowScrollToBottom(false);
|
||||
await legendListRef.current?.scrollToEnd?.({ animated: false });
|
||||
setTimelineAnchor({
|
||||
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
|
||||
messageId: messageIdForSend,
|
||||
});
|
||||
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -4663,9 +4777,6 @@ 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(
|
||||
@@ -4722,7 +4833,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
{/* Main content area with optional plan sidebar */}
|
||||
<div className="flex min-h-0 min-w-0 flex-1">
|
||||
{/* Chat column */}
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
{/* Messages Wrapper */}
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
{/* Messages — LegendList handles virtualization and scrolling internally */}
|
||||
@@ -4734,6 +4845,11 @@ 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}
|
||||
@@ -4747,12 +4863,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
timestampFormat={timestampFormat}
|
||||
workspaceRoot={activeWorkspaceRoot}
|
||||
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
|
||||
anchorMessageId={timelineAnchorMessageId}
|
||||
onAnchorReady={onTimelineAnchorReady}
|
||||
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
|
||||
contentInsetEndAdjustment={composerOverlayHeight}
|
||||
onIsAtEndChange={onIsAtEndChange}
|
||||
/>
|
||||
|
||||
{/* scroll to bottom pill — shown when user has scrolled away from the bottom */}
|
||||
{showScrollToBottom && (
|
||||
<div className="pointer-events-none absolute bottom-1 left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5">
|
||||
<div
|
||||
className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5"
|
||||
style={{ bottom: composerOverlayHeight + 4 }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => scrollToEnd(true)}
|
||||
@@ -4767,115 +4890,133 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
|
||||
{/* Input bar */}
|
||||
<div
|
||||
className={cn(
|
||||
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
ref={setComposerOverlayElement}
|
||||
data-chat-composer-overlay="true"
|
||||
className="pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
|
||||
>
|
||||
<div className="relative isolate">
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<div className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
shouldAutoScrollRef={isAtEndRef}
|
||||
scheduleStickToBottom={scrollToEnd}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
|
||||
>
|
||||
<div className="relative mx-auto h-full w-full max-w-208 overflow-clip rounded-t-[20px]">
|
||||
<div className="chat-composer-shared-blur absolute -inset-8" />
|
||||
</div>
|
||||
</div>
|
||||
{isGitRepo && (
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
<div className="chat-composer-horizontal-inset">
|
||||
<div className="pointer-events-auto relative z-10 isolate">
|
||||
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
|
||||
<div className="relative z-10">
|
||||
<ChatComposer
|
||||
composerRef={composerRef}
|
||||
composerDraftTarget={composerDraftTarget}
|
||||
environmentId={environmentId}
|
||||
routeKind={routeKind}
|
||||
routeThreadRef={routeThreadRef}
|
||||
draftId={draftId}
|
||||
activeThreadId={activeThreadId}
|
||||
activeThreadEnvironmentId={activeThread?.environmentId}
|
||||
activeThread={activeThread}
|
||||
isServerThread={isServerThread}
|
||||
isLocalDraftThread={isLocalDraftThread}
|
||||
phase={phase}
|
||||
isConnecting={isConnecting}
|
||||
isSendBusy={isSendBusy}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
environmentUnavailable={activeEnvironmentUnavailableState}
|
||||
activePendingApproval={activePendingApproval}
|
||||
pendingApprovals={pendingApprovals}
|
||||
pendingUserInputs={pendingUserInputs}
|
||||
activePendingProgress={activePendingProgress}
|
||||
activePendingResolvedAnswers={activePendingResolvedAnswers}
|
||||
activePendingIsResponding={activePendingIsResponding}
|
||||
activePendingDraftAnswers={activePendingDraftAnswers}
|
||||
activePendingQuestionIndex={activePendingQuestionIndex}
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
interactionMode={interactionMode}
|
||||
lockedProvider={lockedProvider}
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
terminalOpen={Boolean(terminalUiState.terminalOpen)}
|
||||
gitCwd={gitCwd}
|
||||
promptRef={promptRef}
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
|
||||
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
|
||||
onPreviousActivePendingUserInputQuestion={
|
||||
onPreviousActivePendingUserInputQuestion
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
)}
|
||||
onChangeActivePendingUserInputCustomAnswer={
|
||||
onChangeActivePendingUserInputCustomAnswer
|
||||
}
|
||||
onProviderModelSelect={onProviderModelSelect}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
toggleInteractionMode={toggleInteractionMode}
|
||||
handleRuntimeModeChange={handleRuntimeModeChange}
|
||||
handleInteractionModeChange={handleInteractionModeChange}
|
||||
togglePlanSidebar={togglePlanSidebar}
|
||||
focusComposer={focusComposer}
|
||||
scheduleComposerFocus={scheduleComposerFocus}
|
||||
setThreadError={setThreadError}
|
||||
onExpandImage={onExpandTimelineImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",
|
||||
isGitRepo
|
||||
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
|
||||
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
|
||||
)}
|
||||
>
|
||||
{isGitRepo && (
|
||||
<div className="pointer-events-auto">
|
||||
<BranchToolbar
|
||||
environmentId={activeThread.environmentId}
|
||||
threadId={activeThread.id}
|
||||
{...(routeKind === "draft" && draftId ? { draftId } : {})}
|
||||
onEnvModeChange={onEnvModeChange}
|
||||
startFromOrigin={startFromOrigin}
|
||||
onStartFromOriginChange={onStartFromOriginChange}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? { effectiveEnvModeOverride: envMode }
|
||||
: {})}
|
||||
{...(canOverrideServerThreadEnvMode
|
||||
? {
|
||||
activeThreadBranchOverride: activeThreadBranch,
|
||||
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
|
||||
}
|
||||
: {})}
|
||||
envLocked={envLocked}
|
||||
onComposerFocusRequest={scheduleComposerFocus}
|
||||
{...(canCheckoutPullRequestIntoThread
|
||||
? { onCheckoutPullRequestRequest: openPullRequestDialog }
|
||||
: {})}
|
||||
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
|
||||
availableEnvironments={logicalProjectEnvironments}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pullRequestDialogState ? (
|
||||
|
||||
@@ -20,6 +20,7 @@ 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";
|
||||
@@ -346,6 +347,7 @@ 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
|
||||
>
|
||||
|
||||
@@ -504,10 +504,6 @@ export interface ChatComposerProps {
|
||||
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
|
||||
composerRef: React.RefObject<ChatComposerHandle | null>;
|
||||
|
||||
// Scroll
|
||||
shouldAutoScrollRef: React.RefObject<boolean>;
|
||||
scheduleStickToBottom: () => void;
|
||||
|
||||
// Callbacks
|
||||
onSend: (e?: { preventDefault: () => void }) => void;
|
||||
onInterrupt: () => void;
|
||||
@@ -593,8 +589,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
composerElementContextsRef,
|
||||
shouldAutoScrollRef,
|
||||
scheduleStickToBottom,
|
||||
onSend,
|
||||
onInterrupt,
|
||||
onImplementPlanInNewThread,
|
||||
@@ -896,7 +890,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -1329,15 +1322,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
};
|
||||
};
|
||||
|
||||
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
|
||||
const initialCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact);
|
||||
setIsComposerFooterCompact(initialCompactness.footerCompact);
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const [entry] = entries;
|
||||
if (!entry) return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
const nextCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact((previous) =>
|
||||
previous === nextCompactness.primaryActionsCompact
|
||||
@@ -1347,25 +1337,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setIsComposerFooterCompact((previous) =>
|
||||
previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact,
|
||||
);
|
||||
const nextHeight = entry.contentRect.height;
|
||||
const previousHeight = composerFormHeightRef.current;
|
||||
composerFormHeightRef.current = nextHeight;
|
||||
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
});
|
||||
|
||||
observer.observe(composerForm);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [
|
||||
activeThreadId,
|
||||
composerFooterActionLayoutKey,
|
||||
composerFooterHasWideActions,
|
||||
scheduleStickToBottom,
|
||||
shouldAutoScrollRef,
|
||||
]);
|
||||
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Image persist effect
|
||||
@@ -2083,8 +2061,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
ref={composerSurfaceRef}
|
||||
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
|
||||
className={cn(
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
|
||||
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
|
||||
environmentUnavailable ? "opacity-75" : null,
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
|
||||
@@ -794,6 +794,67 @@ 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: [
|
||||
@@ -879,6 +940,77 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRow?.showAssistantMeta).toBe(false);
|
||||
expect(assistantRow?.showAssistantCopyButton).toBe(false);
|
||||
});
|
||||
|
||||
it("models work log overflow expansion as inserted list rows", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
label: "read",
|
||||
detail: "Reading package.json",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-2",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
entry: {
|
||||
id: "work-2",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
label: "edit",
|
||||
detail: "Editing MessagesTimeline.tsx",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-3",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
entry: {
|
||||
id: "work-3",
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
label: "test",
|
||||
detail: "Running tests",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const baseInput = {
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
};
|
||||
const collapsedRows = deriveMessagesTimelineRows(baseInput);
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
...baseInput,
|
||||
expandedWorkGroupIds: new Set(["work-group:work-entry-1"]),
|
||||
});
|
||||
|
||||
expect(collapsedRows.map((row) => row.id)).toEqual(["work-3", "work-toggle:work-entry-1"]);
|
||||
expect(collapsedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
|
||||
groupId: "work-group:work-entry-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
onlyToolEntries: true,
|
||||
});
|
||||
expect(expandedRows.map((row) => row.id)).toEqual([
|
||||
"work-1",
|
||||
"work-2",
|
||||
"work-3",
|
||||
"work-toggle:work-entry-1",
|
||||
]);
|
||||
expect(expandedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import {
|
||||
formatDuration,
|
||||
workEntryIndicatesToolNeutralStatus,
|
||||
workLogEntryIsToolLike,
|
||||
type TimelineEntry,
|
||||
type WorkLogEntry,
|
||||
} from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
|
||||
|
||||
@@ -42,6 +48,15 @@ export type MessagesTimelineRow =
|
||||
createdAt: string;
|
||||
groupedEntries: WorkLogEntry[];
|
||||
}
|
||||
| {
|
||||
kind: "work-toggle";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
groupId: string;
|
||||
hiddenCount: number;
|
||||
expanded: boolean;
|
||||
onlyToolEntries: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
@@ -149,13 +164,20 @@ interface TurnFold {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null {
|
||||
function deriveUnsettledTurnId(
|
||||
latestTurn: TimelineLatestTurn | null,
|
||||
runningTurnId: TurnId | null,
|
||||
): TurnId | null {
|
||||
if (runningTurnId !== null) {
|
||||
return runningTurnId;
|
||||
}
|
||||
if (!latestTurn) {
|
||||
return null;
|
||||
}
|
||||
@@ -291,7 +313,9 @@ function deriveTurnFolds(input: {
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
latestTurn?: TimelineLatestTurn | null;
|
||||
runningTurnId?: TurnId | null;
|
||||
expandedTurnIds?: ReadonlySet<TurnId>;
|
||||
expandedWorkGroupIds?: ReadonlySet<string>;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
@@ -302,7 +326,10 @@ export function deriveMessagesTimelineRows(input: {
|
||||
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
|
||||
const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null);
|
||||
const unsettledTurnId = deriveUnsettledTurnId(
|
||||
input.latestTurn ?? null,
|
||||
input.runningTurnId ?? null,
|
||||
);
|
||||
const foldsByAnchorEntryId = deriveTurnFolds({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds,
|
||||
@@ -356,12 +383,44 @@ export function deriveMessagesTimelineRows(input: {
|
||||
groupedEntries.push(nextEntry.entry);
|
||||
cursor += 1;
|
||||
}
|
||||
nextRows.push({
|
||||
kind: "work",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
groupedEntries,
|
||||
});
|
||||
const visibleGroupedEntries = groupedEntries.filter(
|
||||
(entry) => !workEntryIndicatesToolNeutralStatus(entry),
|
||||
);
|
||||
if (visibleGroupedEntries.length > 0) {
|
||||
if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
|
||||
nextRows.push({
|
||||
kind: "work",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
groupedEntries: visibleGroupedEntries,
|
||||
});
|
||||
} else {
|
||||
const groupId = `work-group:${timelineEntry.id}`;
|
||||
const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
|
||||
const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
|
||||
const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
|
||||
const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;
|
||||
|
||||
for (const workEntry of renderedEntries) {
|
||||
nextRows.push({
|
||||
kind: "work",
|
||||
id: workEntry.id,
|
||||
createdAt: workEntry.createdAt,
|
||||
groupedEntries: [workEntry],
|
||||
});
|
||||
}
|
||||
|
||||
nextRows.push({
|
||||
kind: "work-toggle",
|
||||
id: `work-toggle:${timelineEntry.id}`,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
groupId,
|
||||
hiddenCount: hiddenEntries.length,
|
||||
expanded,
|
||||
onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
|
||||
});
|
||||
}
|
||||
}
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
}
|
||||
@@ -462,6 +521,17 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
case "work-toggle": {
|
||||
const bw = b as typeof a;
|
||||
return (
|
||||
a.createdAt === bw.createdAt &&
|
||||
a.groupId === bw.groupId &&
|
||||
a.hiddenCount === bw.hiddenCount &&
|
||||
a.expanded === bw.expanded &&
|
||||
a.onlyToolEntries === bw.onlyToolEntries
|
||||
);
|
||||
}
|
||||
|
||||
case "message": {
|
||||
const bm = b as typeof a;
|
||||
return (
|
||||
|
||||
@@ -13,16 +13,63 @@ vi.mock("@legendapp/list/react", async () => {
|
||||
renderItem: (args: { item: { id: string } }) => ReactNode;
|
||||
ListHeaderComponent?: ReactNode;
|
||||
ListFooterComponent?: ReactNode;
|
||||
anchoredEndSpace?: {
|
||||
anchorIndex: number;
|
||||
anchorMaxSize?: number;
|
||||
anchorOffset?: number;
|
||||
onReady?: (info: { anchorIndex: number }) => void;
|
||||
onSizeChanged?: (size: number) => void;
|
||||
};
|
||||
contentInsetEndAdjustment?: number;
|
||||
className?: string;
|
||||
maintainScrollAtEnd?: boolean;
|
||||
maintainVisibleContentPosition?:
|
||||
| boolean
|
||||
| {
|
||||
data?: boolean;
|
||||
size?: boolean;
|
||||
shouldRestorePosition?: (item: { id: string }) => boolean;
|
||||
};
|
||||
ref?: Ref<LegendListRef>;
|
||||
}) => (
|
||||
<div data-testid={legendListTestId}>
|
||||
{props.ListHeaderComponent}
|
||||
{props.data.map((item) => (
|
||||
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
|
||||
))}
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
}) => {
|
||||
if (props.anchoredEndSpace) {
|
||||
props.anchoredEndSpace.onSizeChanged?.(240);
|
||||
props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
|
||||
}
|
||||
return (
|
||||
<div
|
||||
data-testid={legendListTestId}
|
||||
data-anchor-index={props.anchoredEndSpace?.anchorIndex}
|
||||
data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
|
||||
data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
|
||||
data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
|
||||
data-content-inset-end={props.contentInsetEndAdjustment}
|
||||
data-class-name={props.className}
|
||||
data-maintain-scroll-at-end={props.maintainScrollAtEnd}
|
||||
data-maintain-visible-content-position={
|
||||
typeof props.maintainVisibleContentPosition === "object"
|
||||
? "object"
|
||||
: props.maintainVisibleContentPosition
|
||||
}
|
||||
data-maintain-visible-content-position-data={
|
||||
typeof props.maintainVisibleContentPosition === "object"
|
||||
? props.maintainVisibleContentPosition.data
|
||||
: undefined
|
||||
}
|
||||
data-maintain-visible-content-position-size={
|
||||
typeof props.maintainVisibleContentPosition === "object"
|
||||
? props.maintainVisibleContentPosition.size
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{props.ListHeaderComponent}
|
||||
{props.data.map((item) => (
|
||||
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
|
||||
))}
|
||||
{props.ListFooterComponent}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return { LegendList };
|
||||
});
|
||||
@@ -97,6 +144,7 @@ function buildProps() {
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
latestTurn: null,
|
||||
runningTurnId: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: () => {},
|
||||
@@ -109,6 +157,10 @@ function buildProps() {
|
||||
resolvedTheme: "light" as const,
|
||||
timestampFormat: "locale" as const,
|
||||
workspaceRoot: undefined,
|
||||
anchorMessageId: null,
|
||||
onAnchorReady: () => {},
|
||||
onAnchorSizeChanged: () => {},
|
||||
contentInsetEndAdjustment: 0,
|
||||
onIsAtEndChange: () => {},
|
||||
};
|
||||
}
|
||||
@@ -137,6 +189,55 @@ function buildUserTimelineEntry(text: string) {
|
||||
}
|
||||
|
||||
describe("MessagesTimeline", () => {
|
||||
it("anchors a sent attachment message using its measured height", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const onAnchorReady = vi.fn();
|
||||
const onAnchorSizeChanged = vi.fn();
|
||||
const firstEntry = buildUserTimelineEntry("First prompt.");
|
||||
const secondEntry = {
|
||||
...buildUserTimelineEntry("Newest prompt."),
|
||||
id: "entry-2",
|
||||
message: {
|
||||
...buildUserTimelineEntry("Newest prompt.").message,
|
||||
id: MessageId.make("message-2"),
|
||||
attachments: [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: "attachment-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1,
|
||||
previewUrl: "data:image/png;base64,iVBORw0KGgo=",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
anchorMessageId={secondEntry.message.id}
|
||||
onAnchorReady={onAnchorReady}
|
||||
onAnchorSizeChanged={onAnchorSizeChanged}
|
||||
contentInsetEndAdjustment={144}
|
||||
timelineEntries={[firstEntry, secondEntry]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain('data-anchor-index="1"');
|
||||
expect(markup).toContain('data-anchor-offset="16"');
|
||||
expect(markup).toContain('data-anchor-on-ready="true"');
|
||||
expect(markup).not.toContain("data-anchor-max-size=");
|
||||
expect(markup).toContain('data-content-inset-end="144"');
|
||||
expect(markup).toContain("[overflow-anchor:none]");
|
||||
expect(markup).not.toContain("data-maintain-scroll-at-end=");
|
||||
expect(markup).toContain('data-maintain-visible-content-position="object"');
|
||||
expect(markup).toContain('data-maintain-visible-content-position-data="true"');
|
||||
expect(markup).toContain('data-maintain-visible-content-position-size="false"');
|
||||
expect(onAnchorReady).toHaveBeenCalledOnce();
|
||||
expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
|
||||
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
|
||||
});
|
||||
|
||||
it("renders collapse controls for long user messages", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import {
|
||||
createContext,
|
||||
Fragment,
|
||||
@@ -13,13 +14,13 @@ import {
|
||||
use,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
import {
|
||||
@@ -42,7 +43,6 @@ import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
ChevronUpIcon,
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
GlobeIcon,
|
||||
@@ -66,7 +66,6 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
MAX_VISIBLE_WORK_LOG_ENTRIES,
|
||||
deriveMessagesTimelineRows,
|
||||
normalizeCompactToolLabel,
|
||||
resolveAssistantMessageCopyState,
|
||||
@@ -127,6 +126,7 @@ interface TimelineRowSharedState {
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onToggleTurnFold: (turnId: TurnId) => void;
|
||||
onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
@@ -152,6 +152,7 @@ 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;
|
||||
@@ -165,6 +166,10 @@ interface MessagesTimelineProps {
|
||||
timestampFormat: TimestampFormat;
|
||||
workspaceRoot: string | undefined;
|
||||
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
|
||||
anchorMessageId: MessageId | null;
|
||||
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
|
||||
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
|
||||
contentInsetEndAdjustment: number;
|
||||
onIsAtEndChange: (isAtEnd: boolean) => void;
|
||||
}
|
||||
|
||||
@@ -179,6 +184,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
listRef,
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
routeThreadKey,
|
||||
onOpenTurnDiff,
|
||||
@@ -192,19 +198,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
timestampFormat,
|
||||
workspaceRoot,
|
||||
skills = EMPTY_TIMELINE_SKILLS,
|
||||
anchorMessageId,
|
||||
onAnchorReady,
|
||||
onAnchorSizeChanged,
|
||||
contentInsetEndAdjustment,
|
||||
onIsAtEndChange,
|
||||
}: MessagesTimelineProps) {
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
|
||||
|
||||
// Toggling a fold inserts/removes rows between the fold row and the final
|
||||
// message — everything above the trigger is unchanged, so the trigger stays
|
||||
// put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
|
||||
// exactly that (pin the bottom content when row data changes while scrolled
|
||||
// to the end), yanking the trigger out of view. Suppress it for the frames
|
||||
// in which the toggle's data change and item measurements settle.
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
setFoldToggleSettling(true);
|
||||
setExpandedTurnIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
if (next.has(turnId)) {
|
||||
@@ -215,23 +218,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!foldToggleSettling) {
|
||||
return;
|
||||
}
|
||||
let secondFrameId: number | null = null;
|
||||
const firstFrameId = window.requestAnimationFrame(() => {
|
||||
secondFrameId = window.requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
const onToggleWorkGroup = useCallback(
|
||||
(groupId: string, anchorElement?: HTMLElement) => {
|
||||
const anchorBottomBeforeToggle = anchorElement?.getBoundingClientRect().bottom ?? null;
|
||||
|
||||
flushSync(() => {
|
||||
setExpandedWorkGroupIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
if (next.has(groupId)) {
|
||||
next.delete(groupId);
|
||||
} else {
|
||||
next.add(groupId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(firstFrameId);
|
||||
if (secondFrameId !== null) {
|
||||
window.cancelAnimationFrame(secondFrameId);
|
||||
|
||||
if (anchorBottomBeforeToggle === null || !anchorElement) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
}, [foldToggleSettling]);
|
||||
|
||||
const delta = anchorElement.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = listRef.current;
|
||||
const currentScroll = list?.getState?.().scroll;
|
||||
if (list && typeof currentScroll === "number") {
|
||||
list.scrollToOffset({ offset: currentScroll + delta, animated: false });
|
||||
}
|
||||
},
|
||||
[listRef],
|
||||
);
|
||||
|
||||
// An in-session interrupt leaves its turn expanded so the user keeps their
|
||||
// place; the next turn (or a reload, since this is local state) folds it.
|
||||
@@ -267,7 +286,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -276,7 +297,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
[
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -284,6 +307,30 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
],
|
||||
);
|
||||
const rows = useStableRows(rawRows);
|
||||
const handleAnchorReady = useCallback(
|
||||
(info: { anchorIndex: number | undefined }) => {
|
||||
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
|
||||
onAnchorReady(anchorMessageId, info.anchorIndex);
|
||||
}
|
||||
},
|
||||
[anchorMessageId, onAnchorReady],
|
||||
);
|
||||
const handleAnchorSizeChanged = useCallback(
|
||||
(size: number) => {
|
||||
if (anchorMessageId !== null) {
|
||||
onAnchorSizeChanged(anchorMessageId, size);
|
||||
}
|
||||
},
|
||||
[anchorMessageId, onAnchorSizeChanged],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(() => {
|
||||
const config = resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
|
||||
row.kind === "message" ? row.message.id : null,
|
||||
);
|
||||
return config
|
||||
? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
|
||||
: undefined;
|
||||
}, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const state = listRef.current?.getState?.();
|
||||
@@ -292,24 +339,6 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
}, [listRef, onIsAtEndChange]);
|
||||
|
||||
const previousRowCountRef = useRef(rows.length);
|
||||
useEffect(() => {
|
||||
const previousRowCount = previousRowCountRef.current;
|
||||
previousRowCountRef.current = rows.length;
|
||||
|
||||
if (previousRowCount > 0 || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
onIsAtEndChange(true);
|
||||
const frameId = window.requestAnimationFrame(() => {
|
||||
void listRef.current?.scrollToEnd?.({ animated: false });
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
}, [listRef, onIsAtEndChange, rows.length]);
|
||||
|
||||
const sharedState = useMemo<TimelineRowSharedState>(
|
||||
() => ({
|
||||
timestampFormat,
|
||||
@@ -324,6 +353,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onImageExpand,
|
||||
onOpenTurnDiff,
|
||||
onToggleTurnFold,
|
||||
onToggleWorkGroup,
|
||||
}),
|
||||
[
|
||||
timestampFormat,
|
||||
@@ -337,6 +367,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onImageExpand,
|
||||
onOpenTurnDiff,
|
||||
onToggleTurnFold,
|
||||
onToggleWorkGroup,
|
||||
],
|
||||
);
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
@@ -376,14 +407,18 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
keyExtractor={keyExtractor}
|
||||
getItemType={getItemType}
|
||||
renderItem={renderItem}
|
||||
estimatedItemSize={90}
|
||||
initialScrollAtEnd
|
||||
maintainScrollAtEnd={!foldToggleSettling}
|
||||
maintainScrollAtEndThreshold={0.1}
|
||||
maintainVisibleContentPosition
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
maintainVisibleContentPosition={{
|
||||
data: true,
|
||||
size: false,
|
||||
}}
|
||||
onScroll={handleScroll}
|
||||
className="scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
|
||||
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
@@ -396,6 +431,10 @@ function keyExtractor(item: MessagesTimelineRow) {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
function getItemType(item: MessagesTimelineRow) {
|
||||
return item.kind === "message" ? `message:${item.message.role}` : item.kind;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TimelineRowContent — the actual row component
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -412,7 +451,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
// Commentary (non-terminal assistant) rows carry no metadata row, so
|
||||
// they sit closer to the work that follows them.
|
||||
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
|
||||
row.kind === "work"
|
||||
row.kind === "work" ||
|
||||
row.kind === "work-toggle"
|
||||
? "pb-2"
|
||||
: "pb-4",
|
||||
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
|
||||
@@ -423,6 +463,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
|
||||
{row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
|
||||
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "assistant" ? (
|
||||
@@ -715,26 +756,17 @@ function WorkingTimer({ createdAt }: { createdAt: string }) {
|
||||
// re-render only the affected row, not the entire list.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
|
||||
/** Renders one or more already-derived work log rows. Overflow expansion is modeled as LegendList data. */
|
||||
const WorkGroupSection = memo(function WorkGroupSection({
|
||||
groupedEntries,
|
||||
}: {
|
||||
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
|
||||
}) {
|
||||
const { workspaceRoot } = use(TimelineRowCtx);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
const anchorBottomBeforeToggleRef = useRef<number | null>(null);
|
||||
const nonEmptyEntries = useMemo(
|
||||
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
|
||||
[groupedEntries],
|
||||
);
|
||||
const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleEntries =
|
||||
hasOverflow && !isExpanded
|
||||
? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
||||
: nonEmptyEntries;
|
||||
const hiddenCount = nonEmptyEntries.length - visibleEntries.length;
|
||||
const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry));
|
||||
const groupLabel = onlyToolEntries
|
||||
? nonEmptyEntries.length === 1
|
||||
@@ -742,49 +774,17 @@ const WorkGroupSection = memo(function WorkGroupSection({
|
||||
: `${nonEmptyEntries.length} tool calls`
|
||||
: "Work Log";
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
|
||||
anchorBottomBeforeToggleRef.current = null;
|
||||
|
||||
if (anchorBottomBeforeToggle === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const section = sectionRef.current;
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scroller = findNearestVerticalScroller(section);
|
||||
if (scroller) {
|
||||
scroller.scrollTop += delta;
|
||||
} else {
|
||||
window.scrollBy(0, delta);
|
||||
}
|
||||
}, [isExpanded]);
|
||||
|
||||
const toggleExpanded = () => {
|
||||
anchorBottomBeforeToggleRef.current =
|
||||
sectionRef.current?.getBoundingClientRect().bottom ?? null;
|
||||
setIsExpanded((v) => !v);
|
||||
};
|
||||
|
||||
if (nonEmptyEntries.length === 0) return null;
|
||||
|
||||
return (
|
||||
<section ref={sectionRef} className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
|
||||
<section className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
|
||||
{!onlyToolEntries && (
|
||||
<p className="px-0.5 pb-0.5 font-medium text-[11px] text-muted-foreground/65">
|
||||
{groupLabel}
|
||||
</p>
|
||||
)}
|
||||
<div className="space-y-px">
|
||||
{visibleEntries.map((workEntry) => (
|
||||
{nonEmptyEntries.map((workEntry) => (
|
||||
<SimpleWorkEntryRow
|
||||
key={workEntry.id}
|
||||
workEntry={workEntry}
|
||||
@@ -792,45 +792,49 @@ const WorkGroupSection = memo(function WorkGroupSection({
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{hasOverflow && (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
|
||||
onClick={toggleExpanded}
|
||||
>
|
||||
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
|
||||
{isExpanded ? (
|
||||
<ChevronUpIcon className="size-3.5 shrink-0 opacity-70" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
|
||||
)}
|
||||
</span>
|
||||
{isExpanded ? (
|
||||
<span className="font-medium text-foreground/82">Show fewer tool calls</span>
|
||||
) : (
|
||||
<span className="font-medium text-foreground/82">
|
||||
+{hiddenCount} previous tool {hiddenCount === 1 ? "call" : "calls"}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
});
|
||||
|
||||
function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null {
|
||||
let parent = element.parentElement;
|
||||
while (parent) {
|
||||
const { overflowY } = window.getComputedStyle(parent);
|
||||
if (
|
||||
(overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") &&
|
||||
parent.scrollHeight > parent.clientHeight
|
||||
) {
|
||||
return parent;
|
||||
}
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
return null;
|
||||
function WorkGroupToggleTimelineRow({
|
||||
row,
|
||||
}: {
|
||||
row: Extract<TimelineRow, { kind: "work-toggle" }>;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const labelNoun = row.onlyToolEntries ? "tool call" : "log entry";
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
|
||||
aria-expanded={row.expanded}
|
||||
onClick={(event) => {
|
||||
const anchorElement =
|
||||
event.currentTarget.closest<HTMLElement>("[data-timeline-row-id]") ?? event.currentTarget;
|
||||
ctx.onToggleWorkGroup(row.groupId, anchorElement);
|
||||
}}
|
||||
>
|
||||
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 opacity-70 transition-transform duration-200",
|
||||
row.expanded && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
{row.expanded ? (
|
||||
<span className="font-medium text-foreground/82">
|
||||
Show fewer {row.onlyToolEntries ? "tool calls" : "log entries"}
|
||||
</span>
|
||||
) : (
|
||||
<span className="font-medium text-foreground/82">
|
||||
+{row.hiddenCount} previous {labelNoun}
|
||||
{row.hiddenCount === 1 ? "" : "s"}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Subscribes directly to the UI state store for expand/collapse state,
|
||||
|
||||
@@ -554,7 +554,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
onItemHighlighted={(modelKey, eventDetails) => {
|
||||
highlightedModelKeyRef.current = typeof modelKey === "string" ? modelKey : null;
|
||||
if (eventDetails.reason === "keyboard" && eventDetails.index >= 0) {
|
||||
modelListRef.current?.scrollIndexIntoView?.({
|
||||
void modelListRef.current?.scrollIndexIntoView?.({
|
||||
index: eventDetails.index,
|
||||
animated: false,
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ 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";
|
||||
|
||||
@@ -17,6 +18,7 @@ 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;
|
||||
|
||||
@@ -24,6 +26,7 @@ export function AgentBrowserCursor(props: {
|
||||
<AgentBrowserCursorEvent
|
||||
key={event.sequence}
|
||||
event={event}
|
||||
content={content}
|
||||
zoomFactor={zoomFactor}
|
||||
controller={controller}
|
||||
/>
|
||||
@@ -32,10 +35,17 @@ 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, zoomFactor, controller } = props;
|
||||
const { event, content, zoomFactor, controller } = props;
|
||||
const [active, setActive] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -48,7 +58,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}px, ${event.y * zoomFactor}px, 0)`,
|
||||
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)`,
|
||||
}}
|
||||
aria-hidden="true"
|
||||
data-agent-browser-cursor
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
"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;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,426 +0,0 @@
|
||||
"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,6 +19,10 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -26,7 +30,13 @@ 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 }: Props) {
|
||||
export function PreviewMoreMenu({
|
||||
tabId,
|
||||
hasWebContents,
|
||||
zoomFactor,
|
||||
deviceToolbarVisible,
|
||||
onToggleDeviceToolbar,
|
||||
}: Props) {
|
||||
if (!previewBridge) return null;
|
||||
const bridge = previewBridge;
|
||||
const tabDisabled = !tabId || !hasWebContents;
|
||||
@@ -59,6 +69,10 @@ export function PreviewMoreMenu({ tabId, hasWebContents, zoomFactor }: Props) {
|
||||
<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,13 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { type ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
type PreviewViewportSetting,
|
||||
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, useThreadPreviewState } from "~/previewStateStore";
|
||||
import {
|
||||
rememberPreviewUrl,
|
||||
updatePreviewServerSnapshot,
|
||||
useThreadPreviewState,
|
||||
} from "~/previewStateStore";
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import { useEnvironment, useEnvironmentHttpBaseUrl } from "~/state/environments";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
@@ -20,10 +29,16 @@ 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";
|
||||
@@ -60,6 +75,7 @@ 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);
|
||||
|
||||
@@ -91,6 +107,10 @@ 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) => {
|
||||
@@ -131,6 +151,51 @@ 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]);
|
||||
@@ -527,6 +592,8 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
tabId={tabId}
|
||||
hasWebContents={desktopOverlay !== null}
|
||||
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
|
||||
deviceToolbarVisible={viewport._tag !== "fill"}
|
||||
onToggleDeviceToolbar={handleToggleDeviceToolbar}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
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 PreviewAutomationOwner,
|
||||
type PreviewAutomationHost,
|
||||
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: PreviewAutomationOwner["environmentId"];
|
||||
readonly environmentId: PreviewAutomationHost["environmentId"];
|
||||
readonly threadId: PreviewAutomationRequest["threadId"];
|
||||
readonly tabId: Exclude<PreviewAutomationRequest["tabId"], undefined> | null;
|
||||
}
|
||||
@@ -56,21 +56,22 @@ export class PreviewAutomationNavigationTimeoutError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
export class PreviewAutomationStaleOwnerError extends Schema.TaggedErrorClass<PreviewAutomationStaleOwnerError>()(
|
||||
"PreviewAutomationStaleOwnerError",
|
||||
export class PreviewAutomationViewportTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationViewportTimeoutError>()(
|
||||
"PreviewAutomationViewportTimeoutError",
|
||||
{
|
||||
requestId: TrimmedNonEmptyString,
|
||||
environmentId: EnvironmentId,
|
||||
expectedThreadId: ThreadId,
|
||||
requestedThreadId: ThreadId,
|
||||
threadId: ThreadId,
|
||||
tabId: PreviewTabId,
|
||||
timeoutMs: Schema.Int,
|
||||
},
|
||||
) {
|
||||
get responseTag() {
|
||||
return "PreviewAutomationUnavailableError" as const;
|
||||
return "PreviewAutomationTimeoutError" as const;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Preview automation request ${this.requestId} targeted thread ${this.requestedThreadId}, but the owner for environment ${this.environmentId} is attached to thread ${this.expectedThreadId}.`;
|
||||
return `Preview viewport for request ${this.requestId} on environment ${this.environmentId} thread ${this.threadId} tab ${this.tabId} was not rendered within ${this.timeoutMs}ms.`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +101,7 @@ export class PreviewAutomationRecordingNotActiveError extends Schema.TaggedError
|
||||
requestId: TrimmedNonEmptyString,
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
tabId: PreviewTabId,
|
||||
tabId: Schema.NullOr(PreviewTabId),
|
||||
},
|
||||
) {
|
||||
get responseTag() {
|
||||
@@ -108,10 +109,65 @@ export class PreviewAutomationRecordingNotActiveError extends Schema.TaggedError
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Preview automation request ${this.requestId} found no active recording for tab ${this.tabId} on environment ${this.environmentId} thread ${this.threadId}.`;
|
||||
return `Preview automation request ${this.requestId} found no active recording for tab ${this.tabId ?? "unassigned"} 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",
|
||||
{
|
||||
@@ -125,9 +181,18 @@ export class PreviewAutomationOperationError extends Schema.TaggedErrorClass<Pre
|
||||
) {
|
||||
static fromCause(
|
||||
input: PreviewAutomationOperationContext & { readonly cause: unknown },
|
||||
): PreviewAutomationOwnerError {
|
||||
return isPreviewAutomationOwnerError(input.cause)
|
||||
? input.cause
|
||||
): 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,
|
||||
})
|
||||
: new PreviewAutomationOperationError(input);
|
||||
}
|
||||
|
||||
@@ -140,20 +205,21 @@ export class PreviewAutomationOperationError extends Schema.TaggedErrorClass<Pre
|
||||
}
|
||||
}
|
||||
|
||||
export const PreviewAutomationOwnerError = Schema.Union([
|
||||
export const PreviewAutomationHostError = Schema.Union([
|
||||
PreviewAutomationOverlayTimeoutError,
|
||||
PreviewAutomationNavigationTimeoutError,
|
||||
PreviewAutomationStaleOwnerError,
|
||||
PreviewAutomationViewportTimeoutError,
|
||||
PreviewAutomationTargetUnavailableError,
|
||||
PreviewAutomationRecordingNotActiveError,
|
||||
PreviewAutomationTargetNotEditableHostError,
|
||||
PreviewAutomationOperationError,
|
||||
]);
|
||||
export type PreviewAutomationOwnerError = typeof PreviewAutomationOwnerError.Type;
|
||||
export type PreviewAutomationHostError = typeof PreviewAutomationHostError.Type;
|
||||
|
||||
export const isPreviewAutomationOwnerError = Schema.is(PreviewAutomationOwnerError);
|
||||
export const isPreviewAutomationHostError = Schema.is(PreviewAutomationHostError);
|
||||
|
||||
export function serializePreviewAutomationOwnerError(
|
||||
error: PreviewAutomationOwnerError,
|
||||
export function serializePreviewAutomationHostError(
|
||||
error: PreviewAutomationHostError,
|
||||
): NonNullable<PreviewAutomationResponse["error"]> {
|
||||
const detail = Object.fromEntries(
|
||||
Object.entries(error).filter(
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
|
||||
|
||||
export function previewAutomationOpenNeedsOverlay(
|
||||
input: PreviewAutomationOpenInput,
|
||||
snapshot: PreviewSessionSnapshot,
|
||||
): boolean {
|
||||
return input.url !== undefined || snapshot.navStatus._tag !== "Idle";
|
||||
}
|
||||
@@ -2,13 +2,18 @@ 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 { PreviewAutomationTargetUnavailableError } from "./previewAutomationErrors";
|
||||
import {
|
||||
PreviewAutomationRecordingNotActiveError,
|
||||
PreviewAutomationTargetUnavailableError,
|
||||
PreviewAutomationViewportTimeoutError,
|
||||
} from "./previewAutomationErrors";
|
||||
import {
|
||||
createPreviewAutomationRequestConsumerAtom,
|
||||
serializePreviewAutomationError,
|
||||
@@ -17,6 +22,8 @@ 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,
|
||||
@@ -30,10 +37,88 @@ 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<PreviewAutomationRequest, Error>>(
|
||||
AsyncResult.initial<PreviewAutomationRequest, Error>(false),
|
||||
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
|
||||
AsyncResult.initial<PreviewAutomationStreamEvent, Error>(false),
|
||||
);
|
||||
const handleRequest = vi.fn(async (value: PreviewAutomationRequest) => ({
|
||||
requestId: value.requestId,
|
||||
@@ -42,18 +127,21 @@ 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,
|
||||
handleRequest,
|
||||
requestHandlerAtom: state.requestHandlerAtom,
|
||||
respond,
|
||||
label: "test:preview-automation-consumer",
|
||||
});
|
||||
const registry = AtomRegistry.make();
|
||||
registry.mount(consumerAtom);
|
||||
|
||||
registry.set(requestsAtom, AsyncResult.success(request("request-1")));
|
||||
registry.set(requestsAtom, AsyncResult.success(request("request-2")));
|
||||
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-1")));
|
||||
registry.set(requestsAtom, AsyncResult.success(requestEvent("request-2")));
|
||||
|
||||
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(2));
|
||||
expect(handleRequest.mock.calls.map(([value]) => value.requestId)).toEqual([
|
||||
@@ -64,15 +152,50 @@ describe("previewAutomationRequestConsumer", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("consumes a request that arrived immediately before the consumer mounted", async () => {
|
||||
const requestsAtom = Atom.make(
|
||||
AsyncResult.success<PreviewAutomationRequest, Error>(request("request-ready")),
|
||||
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,
|
||||
handleRequest: async () => undefined,
|
||||
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")),
|
||||
);
|
||||
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,
|
||||
respond,
|
||||
label: "test:preview-automation-initial-request",
|
||||
});
|
||||
@@ -81,7 +204,12 @@ describe("previewAutomationRequestConsumer", () => {
|
||||
registry.mount(consumerAtom);
|
||||
|
||||
await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1));
|
||||
expect(respond).toHaveBeenCalledWith({ requestId: "request-ready", ok: true });
|
||||
expect(respond).toHaveBeenCalledWith({
|
||||
clientId,
|
||||
connectionId,
|
||||
requestId: "request-ready",
|
||||
ok: true,
|
||||
});
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
@@ -118,6 +246,84 @@ 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 = {
|
||||
@@ -145,16 +351,19 @@ describe("previewAutomationRequestConsumer", () => {
|
||||
});
|
||||
|
||||
it("sanitizes unexpected handler failures at the response boundary", async () => {
|
||||
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationRequest, Error>>(
|
||||
AsyncResult.initial<PreviewAutomationRequest, Error>(false),
|
||||
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
|
||||
AsyncResult.initial<PreviewAutomationStreamEvent, 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,
|
||||
handleRequest: async () => {
|
||||
throw new Error("desktop IPC secret: do-not-return");
|
||||
},
|
||||
requestHandlerAtom: state.requestHandlerAtom,
|
||||
respond: async (response) => {
|
||||
responses.push(response);
|
||||
},
|
||||
@@ -166,7 +375,7 @@ describe("previewAutomationRequestConsumer", () => {
|
||||
registry.set(
|
||||
requestsAtom,
|
||||
AsyncResult.success(
|
||||
request("request-failed", {
|
||||
requestEvent("request-failed", {
|
||||
operation: "click",
|
||||
tabId,
|
||||
}),
|
||||
@@ -175,6 +384,8 @@ describe("previewAutomationRequestConsumer", () => {
|
||||
|
||||
await vi.waitFor(() => expect(responses).toHaveLength(1));
|
||||
expect(responses[0]).toEqual({
|
||||
clientId,
|
||||
connectionId,
|
||||
requestId: "request-failed",
|
||||
ok: false,
|
||||
error: {
|
||||
|
||||
@@ -1,87 +1,121 @@
|
||||
import type {
|
||||
PreviewAutomationOwner,
|
||||
PreviewAutomationHost,
|
||||
PreviewAutomationRequest,
|
||||
PreviewAutomationResponse,
|
||||
PreviewAutomationStreamEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
PreviewAutomationOperationError,
|
||||
type PreviewAutomationOperationContext,
|
||||
serializePreviewAutomationOwnerError,
|
||||
serializePreviewAutomationHostError,
|
||||
} from "./previewAutomationErrors";
|
||||
|
||||
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),
|
||||
};
|
||||
}
|
||||
type AutomationStreamResult<E> = AsyncResult.AsyncResult<PreviewAutomationStreamEvent, E>;
|
||||
|
||||
export function serializePreviewAutomationError(
|
||||
error: unknown,
|
||||
context: PreviewAutomationOperationContext,
|
||||
): NonNullable<PreviewAutomationResponse["error"]> {
|
||||
return serializePreviewAutomationOwnerError(
|
||||
return serializePreviewAutomationHostError(
|
||||
PreviewAutomationOperationError.fromCause({ ...context, cause: error }),
|
||||
);
|
||||
}
|
||||
|
||||
export function createPreviewAutomationRequestConsumerAtom<E>(options: {
|
||||
readonly requestsAtom: Atom.Atom<AutomationRequestResult<E>>;
|
||||
readonly environmentId: PreviewAutomationOwner["environmentId"];
|
||||
readonly handleRequest: (request: PreviewAutomationRequest) => Promise<unknown>;
|
||||
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 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: AutomationRequestResult<E>) => {
|
||||
const consume = (result: AutomationStreamResult<E>) => {
|
||||
if (!AsyncResult.isSuccess(result)) return;
|
||||
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, {
|
||||
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,
|
||||
requestId: request.requestId,
|
||||
operation: request.operation,
|
||||
environmentId: options.environmentId,
|
||||
threadId: request.threadId,
|
||||
tabId: request.tabId ?? null,
|
||||
ok: true,
|
||||
...(value === undefined ? {} : { result: value }),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
(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(() => {
|
||||
if (!disposed && requestsVersion === 0) consume(initialRequest);
|
||||
const initialConnectionWasSkipped =
|
||||
AsyncResult.isSuccess(initialRequest) &&
|
||||
initialRequest.value.connectionId === activeConnectionId &&
|
||||
initialRequest.value.connectionId !== reportedConnectionId;
|
||||
if (!disposed && (requestsVersion === 0 || initialConnectionWasSkipped)) {
|
||||
consume(initialRequest);
|
||||
}
|
||||
});
|
||||
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(options.label));
|
||||
}
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user