Compare commits

..
Author SHA1 Message Date
Ben Davis 4a4df05191 fix(server): preserve active VCS cache entries 2026-06-26 13:50:39 -07:00
Ben Davis f891d526de test(server): stabilize provider shutdown assertions 2026-06-26 13:43:09 -07:00
Ben Davis 40c5fc2121 fix(server): address vcs and log retention review 2026-06-26 13:35:33 -07:00
Ben Davis a9a23e489a refactor(server): clarify provider log ownership 2026-06-26 13:27:36 -07:00
Ben Davis c5974d3848 fix(server): isolate interrupted Git refresh waiters 2026-06-26 11:36:10 -07:00
Ben Davis 96afe3f821 fix(server): retry interrupted Git status refreshes 2026-06-26 11:30:42 -07:00
Ben Davis b9197b7e4c fix(server): bound explicit child process kills 2026-06-26 11:23:47 -07:00
Ben Davis 45d301e835 fix(server): close managed Claude event logs 2026-06-26 11:20:51 -07:00
Ben Davis ed0591335e fix(server): bound VCS status broadcaster state 2026-06-26 11:18:24 -07:00
Ben Davis 3d0f074442 fix(server): bound child process shutdown 2026-06-26 11:14:52 -07:00
Ben Davis 16e4282201 perf(server): avoid tracing provider log hot paths 2026-06-26 11:14:37 -07:00
Ben Davis 6c0533a23b fix(server): harden background Git status refresh 2026-06-26 11:14:27 -07:00
Ben Davis 39b9fab7a5 fix(server): bound provider event log churn 2026-06-26 11:09:53 -07:00
Ben Davis 1d0fc944a2 fix(cli): force exit when graceful shutdown stalls 2026-06-26 11:06:06 -07:00
Ben Davis a49d7a7010 fix(client): release idle VCS subscriptions immediately 2026-06-26 11:02:37 -07:00
52b04b947e fix(grok): Harden ACP resume with replay-idle load readiness (#3156)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-25 23:34:08 -07:00
Julius Marmingeandcodex e9ed70c5b9 [codex] Fix preview automation edge cases (#3561)
Co-authored-by: codex <[email protected]>
2026-06-25 20:08:27 -07:00
Julius Marmingeandcodex ffae5410e8 Route preview automation through live owner streams (#3548)
Co-authored-by: codex <[email protected]>
2026-06-25 19:06:44 -07:00
Julius MarmingeandJulius Marminge 31dfe3596e Fix Electron dev and packaged renderer startup (#3557)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-25 20:58:38 +00:00
Julius Marminge c2776c2336 Restore right panel inset when maximized (#3555) 2026-06-25 17:07:33 +00:00
Julius MarmingeandJulius Marminge 22f021ed69 [codex] Upgrade Legend List chat scrolling (#3545)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 15:39:17 -07:00
Wout StiensandCodex a4964b3b36 [codex] fix: show standalone element-pick context (#3527)
Co-authored-by: Codex <[email protected]>
2026-06-23 13:04:20 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
195 changed files with 15212 additions and 3501 deletions

No files matched your search

+36 -14
View File
@@ -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");
+45 -2
View File
@@ -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);
+387 -10
View File
@@ -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* () {
+236 -74
View File
@@ -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" });
});
});
+203
View File
@@ -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 },
};
}
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -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();
+95 -3
View File
@@ -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)));
});
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^7.0.3"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
+3 -3
View File
@@ -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",
+7 -10
View File
@@ -104,16 +104,13 @@ const capabilitiesLayer = Layer.succeedContext(
}),
),
);
return yield* Option.match(token, {
onNone: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
}),
),
onSome: Effect.succeed,
});
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
}),
).pipe(
@@ -1,17 +1,12 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import {
ManagedRelay,
ManagedRelaySessionTokenReadError,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { type ReactNode, useEffect, useRef } from "react";
import { environmentCatalog } from "../../connection/catalog";
@@ -44,11 +39,7 @@ export function activateCloudRelayAccount(
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: () =>
Effect.tryPromise({
try: tokenProvider,
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
}).pipe(Effect.map(Option.fromNullOr)),
readClerkToken: tokenProvider,
});
}
@@ -30,7 +30,9 @@ import {
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { buildThreadRoutePath } from "../../lib/routes";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
import { useProjects } from "../../state/entities";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
@@ -63,6 +65,7 @@ export function NewTaskDraftScreen(props: {
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const borderColor = useThemeColor("--color-border");
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
) {
return;
}
setProject(directProject);
return;
}
@@ -105,10 +114,16 @@ export function NewTaskDraftScreen(props: {
useEffect(() => {
if (!selectedProject) {
loadedBranchesProjectKeyRef.current = null;
return;
}
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
if (loadedBranchesProjectKeyRef.current === projectKey) {
return;
}
loadedBranchesProjectKeyRef.current = projectKey;
void flow.loadBranches();
}, [flow, selectedProject]);
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
if (!selectedProject) {
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("model:")) {
return;
}
// Defer state update so the native menu dismiss animation completes
// before re-rendering the menu actions (prevents submenu jump).
setTimeout(() => {
flow.setSelectedModelKey(event.slice("model:".length));
}, 150);
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
@@ -366,27 +377,42 @@ export function NewTaskDraftScreen(props: {
);
async function handleStart(): Promise<void> {
const selectedProject = flow.selectedProject;
if (!selectedProject) {
return;
}
const draft = getComposerDraftSnapshot(
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
);
const modelSelection = draft.modelSelection ?? flow.selectedModel;
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
const selectedWorktreePath =
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
const interactionMode = draft.interactionMode ?? flow.interactionMode;
const initialMessageText = draft.text.trim();
if (
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
!modelSelection ||
initialMessageText.length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
(workspaceMode === "worktree" && !selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
const result = await createProjectThread({
project: flow.selectedProject,
modelSelection: flow.selectedModel,
envMode: flow.workspaceMode,
branch: flow.selectedBranchName,
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
initialMessageText: flow.prompt.trim(),
initialAttachments: flow.attachments,
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
});
flow.setSubmitting(false);
@@ -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}
+62 -122
View File
@@ -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 { 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>;
}
@@ -812,30 +821,6 @@ 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}
@@ -1122,17 +1107,12 @@ 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 previousLatestTurnRef = useRef(props.latestTurn);
const isNearEndRef = useRef(true);
const initialScrollReadyRef = useRef(false);
const lastContentHeightRef = useRef(0);
const { width: viewportWidth } = useWindowDimensions();
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1214,6 +1194,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
[expandedTurnIds, 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>();
for (const entry of props.feed) {
@@ -1229,54 +1219,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 +1250,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);
}
@@ -1358,7 +1297,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, []);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
suppressAutoFollowRef.current = true;
setFoldToggleSettling(true);
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
@@ -1376,7 +1315,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
});
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
suppressAutoFollowRef.current = false;
setFoldToggleSettling(false);
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
@@ -1458,59 +1397,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={
foldToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
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
@@ -1,13 +1,7 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useWorkspaceState } from "../../state/workspace";
@@ -79,18 +73,6 @@ export function ThreadRouteScreen() {
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const updateThreadMetadata = useAtomCommand(
threadEnvironment.updateMetadata,
"thread metadata update",
);
const setThreadRuntimeMode = useAtomCommand(
threadEnvironment.setRuntimeMode,
"thread runtime mode",
);
const setThreadInteractionMode = useAtomCommand(
threadEnvironment.setInteractionMode,
"thread interaction mode",
);
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const router = useRouter();
const params = useLocalSearchParams<{
@@ -105,6 +87,18 @@ export function ThreadRouteScreen() {
const routeConnectionState =
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
const selectedThreadWithDraftSettings = useMemo(
() =>
selectedThread
? {
...selectedThread,
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
}
: null,
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
);
/* ─── Native header theming ──────────────────────────────────────── */
const iconColor = String(useThemeColor("--color-icon"));
@@ -157,51 +151,6 @@ export function ThreadRouteScreen() {
const handleOpenConnectionEditor = useCallback(() => {
void router.push("/connections");
}, [router]);
const handleUpdateThreadModelSelection = useCallback(
(modelSelection: ModelSelection) => {
if (!selectedThread) {
return;
}
return updateThreadMetadata({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
modelSelection,
},
});
},
[selectedThread, updateThreadMetadata],
);
const handleUpdateThreadRuntimeMode = useCallback(
(runtimeMode: RuntimeMode) => {
if (!selectedThread) {
return;
}
return setThreadRuntimeMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
runtimeMode,
},
});
},
[selectedThread, setThreadRuntimeMode],
);
const handleUpdateThreadInteractionMode = useCallback(
(interactionMode: ProviderInteractionMode) => {
if (!selectedThread) {
return;
}
return setThreadInteractionMode({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
interactionMode,
},
});
},
[selectedThread, setThreadInteractionMode],
);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
@@ -23,6 +23,7 @@ import {
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
@@ -158,34 +159,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
? selectedEnvironmentIdOverride
: (projects[0]?.environmentId ?? null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
const branchLoadVersionRef = useRef(0);
const [submitting, setSubmitting] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
DEFAULT_PROVIDER_INTERACTION_MODE,
);
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
Record<string, ModelSelection>
>({});
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
const reset = useCallback(() => {
setSelectedEnvironmentId(null);
setSelectedProjectKey(null);
setSelectedModelKey(null);
setWorkspaceMode("local");
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setSubmitting(false);
setBranchQuery("");
setRuntimeMode(DEFAULT_RUNTIME_MODE);
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
setModelSelectionOverrides({});
setExpandedProvider(null);
}, []);
@@ -247,33 +229,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
const modelOptions = useMemo(
() =>
buildModelOptions(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
),
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
);
const defaultModelKey = selectedProject?.defaultModelSelection
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
: null;
const baseSelectedModel =
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
(defaultModelKey
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
: null) ??
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
const selectedModelKey = selectedModel
? `${selectedModel.instanceId}:${selectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
const selectedProviderSkills =
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
const selectedProviderSkills = useMemo(
() =>
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [],
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
(key: string | null) => {
if (!key || !selectedProjectDraftKey) {
return;
}
const option = modelOptions.find((candidate) => candidate.key === key);
if (!option) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
);
const setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedModelIdentity) {
if (!selectedModel || !selectedProjectDraftKey) {
return;
}
const nextSelection: ModelSelection = options
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: nextSelection,
});
},
[selectedModel, selectedModelIdentity],
[selectedModel, selectedProjectDraftKey],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
@@ -381,62 +380,85 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const setProject = useCallback((project: EnvironmentProject) => {
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(project.environmentId);
setSelectedProjectKey(nextProjectKey);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
branchLoadVersionRef.current += 1;
setSelectedEnvironmentId(environmentId);
setSelectedProjectKey(null);
setSelectedBranchName(null);
setSelectedWorktreePath(null);
setModelSelectionOverrides({});
}, []);
const setWorkspaceMode = useCallback(
(mode: WorkspaceMode) => {
if (!selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
(branch: VcsRef) => {
setSelectedBranchName(branch.name);
setSelectedWorktreePath(
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
);
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
},
});
},
[selectedProject],
[selectedProject, selectedProjectDraftKey, workspaceMode],
);
const refreshBranches = branchState.refresh;
const loadBranches = useCallback(async () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
}, [refreshBranches, selectedProject]);
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
setPendingConnectionError(null);
if (workspaceMode === "worktree" && !selectedBranchName) {
const preferredBranch =
availableBranches.find((branch) => branch.current)?.name ??
availableBranches.find((branch) => branch.isDefault)?.name ??
null;
if (preferredBranch) {
setSelectedBranchName(preferredBranch);
}
const preferredBranch =
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
}
},
[selectedProjectDraftKey],
);
const setInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (selectedProjectDraftKey) {
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
}
},
[selectedProjectDraftKey],
);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setProject,
selectBranch,
selectEnvironment,
setInteractionMode,
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setWorkspaceMode,
submitting,
workspaceMode,
appendAttachments,
@@ -0,0 +1,11 @@
import * as Schema from "effect/Schema";
export const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
+6 -6
View File
@@ -86,7 +86,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread, [], null);
const feed = buildThreadFeed(thread);
expect(feed).toMatchObject([
{
type: "activity-group",
@@ -144,7 +144,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread, [], null);
const feed = buildThreadFeed(thread);
const group = feed[0];
expect(group).toMatchObject({
@@ -209,7 +209,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 +271,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 +359,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,7 +399,7 @@ 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",
+1 -19
View File
@@ -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";
@@ -88,13 +86,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 +95,7 @@ type RawThreadFeedEntry =
};
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
| Extract<RawThreadFeedEntry, { type: "message" }>
| {
readonly type: "activity-group";
readonly id: string;
@@ -1255,8 +1246,6 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
thread: OrchestrationThread,
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
dispatchingQueuedMessageId: MessageId | null,
options?: {
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
},
@@ -1273,13 +1262,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);
});
});
-22
View File
@@ -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;
}
+65 -13
View File
@@ -1,32 +1,38 @@
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
IsoDateTime,
MessageId,
ModelSelection,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
type ModelSelection as ModelSelectionType,
type ProviderInteractionMode as ProviderInteractionModeType,
type RuntimeMode as RuntimeModeType,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
const DraftComposerImageAttachmentSchema = Schema.Struct({
id: Schema.String,
previewUri: Schema.String,
type: Schema.Literal("image"),
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
dataUrl: Schema.String,
});
export const QueuedThreadMessageSchema = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
environmentId: EnvironmentId,
threadId: ThreadId,
messageId: MessageId,
commandId: CommandId,
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelection),
runtimeMode: Schema.optional(RuntimeMode),
interactionMode: Schema.optional(ProviderInteractionMode),
createdAt: IsoDateTime,
});
@@ -40,9 +46,37 @@ export interface QueuedThreadMessage {
readonly commandId: CommandId;
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelectionType;
readonly runtimeMode?: RuntimeModeType;
readonly interactionMode?: ProviderInteractionModeType;
readonly createdAt: string;
}
export interface ThreadSettingsSnapshot {
readonly modelSelection: ModelSelectionType;
readonly runtimeMode: RuntimeModeType;
readonly interactionMode: ProviderInteractionModeType;
}
export function resolveQueuedThreadSettings(
message: QueuedThreadMessage,
thread: ThreadSettingsSnapshot,
): ThreadSettingsSnapshot {
return {
modelSelection: message.modelSelection ?? thread.modelSelection,
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
interactionMode: message.interactionMode ?? thread.interactionMode,
};
}
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
return (
left.instanceId === right.instanceId &&
left.model === right.model &&
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
);
}
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
return encodeStoredQueuedThreadMessage({
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
@@ -119,3 +153,21 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
}
return isTransportConnectionErrorMessage(errorMessage(error));
}
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
export type ThreadOutboxFailureAction = "retry" | "discard";
export function resolveThreadOutboxFailureAction(input: {
readonly stage: ThreadOutboxCommandStage;
readonly error: unknown;
readonly interrupted: boolean;
}): ThreadOutboxFailureAction {
if (
input.stage === "settings-sync" ||
input.interrupted ||
shouldRetryThreadOutboxDelivery(input.error)
) {
return "retry";
}
return "discard";
}
+78 -1
View File
@@ -1,11 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
@@ -66,6 +76,54 @@ describe("thread outbox", () => {
).toThrow();
});
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
const legacyMessage = queuedMessage({
messageId: "message-1",
createdAt: "2026-06-08T10:00:01.000Z",
});
const selectedMessage = {
...legacyMessage,
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
} satisfies QueuedThreadMessage;
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
selectedMessage,
);
expect(
resolveQueuedThreadSettings(legacyMessage, {
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
}),
).toEqual({
modelSelection: selectedMessage.modelSelection,
runtimeMode: selectedMessage.runtimeMode,
interactionMode: selectedMessage.interactionMode,
});
});
it("compares model options as part of the queued settings change", () => {
const base = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "medium" }],
} as const;
expect(modelSelectionsEqual(base, base)).toBe(true);
expect(
modelSelectionsEqual(base, {
...base,
options: [{ id: "reasoningEffort", value: "xhigh" }],
}),
).toBe(false);
});
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
@@ -271,4 +329,23 @@ describe("thread outbox", () => {
).toBe(true);
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
});
it("retains queued messages when settings synchronization fails before startTurn", () => {
const deterministicFailure = new Error("Thread no longer exists");
expect(
resolveThreadOutboxFailureAction({
stage: "settings-sync",
error: deterministicFailure,
interrupted: false,
}),
).toBe("retry");
expect(
resolveThreadOutboxFailureAction({
stage: "start-turn",
error: deterministicFailure,
interrupted: false,
}),
).toBe("discard");
});
});
@@ -1,14 +1,136 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
removeComposerDraftsForEnvironment,
} from "./use-composer-drafts";
const DRAFT: ComposerDraft = {
text: "hello",
attachments: [],
};
afterEach(() => {
appAtomRegistry.set(composerDraftsAtom, {});
});
describe("mobile composer drafts", () => {
it("hydrates selector state even when the message content is empty", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
},
}),
).toEqual({
"new-task:environment-1:project-1": {
text: "",
attachments: [],
modelSelection: {
instanceId: "codex",
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
runtimeMode: "approval-required",
interactionMode: "plan",
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
},
});
});
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
expect(
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": DRAFT,
},
}),
).toEqual({
"environment-1:thread-1": DRAFT,
});
expect(() =>
decodePersistedComposerDrafts({
schemaVersion: 1,
drafts: {
"environment-1:thread-1": {
...DRAFT,
runtimeMode: "sometimes-safe",
},
},
}),
).toThrow();
});
it("clears sent content without clearing the selected model or workspace", () => {
const draftKey = "environment-1:thread-1";
const draft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
workspaceSelection: {
mode: "worktree",
branch: "main",
worktreePath: null,
},
};
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
[draftKey]: {
...draft,
text: "",
attachments: [],
},
});
});
it("reads the latest selector state synchronously for send", () => {
const draftKey = "environment-1:thread-1";
const selectedDraft: ComposerDraft = {
text: "send this",
attachments: [],
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
options: [{ id: "reasoningEffort", value: "xhigh" }],
},
};
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
});
it("removes only drafts owned by the selected environment", () => {
const environmentId = EnvironmentId.make("environment-cloud");
const retainedEnvironmentId = EnvironmentId.make("environment-local");
@@ -17,12 +139,15 @@ describe("mobile composer drafts", () => {
removeComposerDraftsForEnvironment(
{
[`${environmentId}:thread-cloud`]: DRAFT,
[`new-task:${environmentId}:project-cloud`]: DRAFT,
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
},
environmentId,
),
).toEqual({
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
});
});
});
+124 -22
View File
@@ -1,9 +1,18 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import {
ModelSelection as ModelSelectionSchema,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom } from "effect/unstable/reactivity";
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { appAtomRegistry } from "./atom-registry";
@@ -29,13 +38,47 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
export interface ComposerDraft {
readonly text: string;
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly modelSelection?: ModelSelection;
readonly runtimeMode?: RuntimeMode;
readonly interactionMode?: ProviderInteractionMode;
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
}
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
}
export type ComposerDraftSettingsUpdate = Pick<
ComposerDraft,
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
>;
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
mode: Schema.Literals(["local", "worktree"]),
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
});
const ComposerDraftSchema = Schema.Struct({
text: Schema.String,
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
modelSelection: Schema.optional(ModelSelectionSchema),
runtimeMode: Schema.optional(RuntimeModeSchema),
interactionMode: Schema.optional(ProviderInteractionModeSchema),
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
});
const PersistedComposerDraftsSchema = Schema.Struct({
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
});
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
PersistedComposerDraftsSchema,
);
const EMPTY_DRAFT: ComposerDraft = {
text: "",
attachments: [],
@@ -54,13 +97,32 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
return EMPTY_DRAFT;
}
return {
...draft,
text: draft.text,
attachments: draft.attachments,
};
}
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
}
function isEmptyDraft(draft: ComposerDraft): boolean {
return draft.text.length === 0 && draft.attachments.length === 0;
return (
draft.text.length === 0 &&
draft.attachments.length === 0 &&
draft.modelSelection === undefined &&
draft.runtimeMode === undefined &&
draft.interactionMode === undefined &&
draft.workspaceSelection === undefined
);
}
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
const parsed = decodePersistedComposerDraftsDocument(value);
return Object.fromEntries(
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
}
async function getComposerDraftsFile() {
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "read";
const raw = await file.text();
operation = "decode";
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
return {};
}
return Object.fromEntries(
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
const draft = entry[1];
return (
typeof draft?.text === "string" &&
Array.isArray(draft.attachments) &&
!isEmptyDraft(draft)
);
}),
);
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
const document = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
} as const;
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
@@ -282,6 +331,55 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
});
}
export function updateComposerDraftSettings(
draftKey: string,
settings: Partial<ComposerDraftSettingsUpdate>,
): void {
updateComposerDrafts((current) => {
const draft = {
...normalizeDraft(current[draftKey]),
...settings,
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
});
}
export function clearComposerDraftContentState(
current: Record<string, ComposerDraft>,
draftKey: string,
): Record<string, ComposerDraft> {
const existing = current[draftKey];
if (!existing) {
return current;
}
const draft = {
...existing,
text: "",
attachments: [],
};
if (isEmptyDraft(draft)) {
const next = { ...current };
delete next[draftKey];
return next;
}
return {
...current,
[draftKey]: draft,
};
}
export function clearComposerDraftContent(draftKey: string): void {
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
}
export function clearComposerDraft(draftKey: string): void {
updateComposerDrafts((current) => {
if (!current[draftKey]) {
@@ -298,8 +396,12 @@ export function removeComposerDraftsForEnvironment(
environmentId: EnvironmentId,
): Record<string, ComposerDraft> {
const environmentPrefix = `${environmentId}:`;
const newTaskPrefix = `new-task:${environmentId}:`;
return Object.fromEntries(
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
Object.entries(drafts).filter(
([draftKey]) =>
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
),
);
}
@@ -1,7 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
clearComposerDraft,
clearComposerDraftContent,
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -30,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;
@@ -67,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(() => {
@@ -81,23 +89,19 @@ 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;
const draftMessage = selectedDraft?.text ?? "";
const draftAttachments = selectedDraft?.attachments ?? [];
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
const selectedThreadSessionActivity = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
@@ -111,7 +115,6 @@ export function useThreadComposerState() {
};
}, [selectedThreadDetail, selectedThreadShell]);
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
@@ -121,51 +124,52 @@ export function useThreadComposerState() {
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
queuedSendStartedAt,
null,
);
}, [
queuedSendStartedAt,
selectedThreadDetail,
selectedThreadSessionActivity,
selectedThreadShell,
]);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
return;
return null;
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = composerDrafts[threadKey];
const text = (draft?.text ?? "").trim();
const attachments = draft?.attachments ?? [];
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
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,
modelSelection: draft.modelSelection ?? thread.modelSelection,
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
interactionMode: draft.interactionMode ?? thread.interactionMode,
createdAt: metadata.createdAt,
});
clearComposerDraft(threadKey);
clearComposerDraftContent(threadKey);
return messageId;
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
return null;
}
}, [composerDrafts, selectedThreadShell]);
}, [selectedThreadDetail, selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -255,12 +259,45 @@ export function useThreadComposerState() {
[selectedThreadShell],
);
const onUpdateModelSelection = useCallback(
(value: ModelSelection) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
},
[selectedThreadKey],
);
const onUpdateRuntimeMode = useCallback(
(value: RuntimeMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
},
[selectedThreadKey],
);
const onUpdateInteractionMode = useCallback(
(value: ProviderInteractionMode) => {
if (!selectedThreadKey) {
return;
}
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
},
[selectedThreadKey],
);
return {
selectedThreadFeed,
selectedThreadQueueCount,
activeWorkStartedAt,
draftMessage,
draftAttachments,
modelSelection,
runtimeMode,
interactionMode,
activeThreadBusy,
onChangeDraftMessage,
onPickDraftImages,
@@ -268,5 +305,8 @@ export function useThreadComposerState() {
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,
onUpdateRuntimeMode,
onUpdateInteractionMode,
};
}
+116 -33
View File
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { type MessageId } from "@t3tools/contracts";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { CommandId, type MessageId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
import { useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
shouldRetryThreadOutboxDelivery,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
@@ -44,8 +48,21 @@ function findThread(
);
}
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
return CommandId.make(`${message.commandId}:${setting}`);
}
export function useThreadOutboxDrain(): void {
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
reportFailure: false,
});
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
reportFailure: false,
});
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
const shellStatuses = useThreadOutboxShellStatuses();
@@ -68,6 +85,98 @@ export function useThreadOutboxDrain(): void {
const sendQueuedMessage = useCallback(
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
const reportFailure = (
commandResult: AtomCommandResult<unknown, unknown>,
stage: ThreadOutboxCommandStage,
): boolean => {
if (!AsyncResult.isFailure(commandResult)) {
return false;
}
const action = resolveThreadOutboxFailureAction({
stage,
error: Cause.squash(commandResult.cause),
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
});
const retry = action === "retry";
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
stage,
cause: commandResult.cause,
retry,
});
return retry;
};
const completeDelivery = async (
deliveryResult: AtomCommandResult<unknown, unknown>,
): Promise<boolean> => {
if (reportFailure(deliveryResult, "start-turn")) {
return false;
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
};
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
const updateResult = await updateThreadMetadata({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "model-selection"),
threadId: queuedMessage.threadId,
modelSelection: settings.modelSelection,
},
});
if (AsyncResult.isFailure(updateResult)) {
reportFailure(updateResult, "settings-sync");
return false;
}
}
if (settings.runtimeMode !== thread.runtimeMode) {
const runtimeResult = await setThreadRuntimeMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
threadId: queuedMessage.threadId,
runtimeMode: settings.runtimeMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(runtimeResult)) {
reportFailure(runtimeResult, "settings-sync");
return false;
}
}
if (settings.interactionMode !== thread.interactionMode) {
const interactionResult = await setThreadInteractionMode({
environmentId: queuedMessage.environmentId,
input: {
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
threadId: queuedMessage.threadId,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(interactionResult)) {
reportFailure(interactionResult, "settings-sync");
return false;
}
}
const deliveryResult = await startTurn({
environmentId: queuedMessage.environmentId,
input: {
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
if (AsyncResult.isFailure(deliveryResult)) {
const error = Cause.squash(deliveryResult.cause);
const retry =
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
console.warn("[thread-outbox] queued message delivery failed", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
cause: deliveryResult.cause,
retry,
});
if (retry) {
return false;
}
}
try {
await removeThreadOutboxMessage(queuedMessage);
return true;
} catch (error) {
console.warn("[thread-outbox] failed to remove delivered queued message", {
environmentId: queuedMessage.environmentId,
threadId: queuedMessage.threadId,
messageId: queuedMessage.messageId,
error,
});
return false;
}
return completeDelivery(deliveryResult);
},
[startTurn],
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
);
useEffect(() => {
+260 -13
View File
@@ -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: {
+9 -18
View File
@@ -3,7 +3,8 @@ import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
@@ -13,22 +14,6 @@ import {
} from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
function firstHeaderValue(value: string | undefined): string | undefined {
const first = value?.split(",")[0]?.trim();
return first && first.length > 0 ? first : undefined;
}
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
try {
return new URL(request.originalUrl).href;
} catch {
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
return new URL(request.originalUrl, `${proto}://${host}`).href;
}
}
export const mapDpopReplayStoreError = (
error: ServerSecretStore.SecretStoreError,
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
@@ -48,11 +33,17 @@ export const verifyRequestDpopProof = (input: {
}) =>
Effect.gen(function* () {
const proof = input.request.headers.dpop;
const url = HttpServerRequest.toURL(input.request);
if (Option.isNone(url)) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: "Invalid DPoP request URL.",
});
}
const now = yield* DateTime.now;
const result = verifyDpopProof({
proof,
method: input.request.method,
url: requestAbsoluteUrl(input.request),
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
+9 -1
View File
@@ -10,11 +10,16 @@ import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import * as BoundedChildProcessSpawner from "./cli/boundedChildProcessSpawner.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { installNodeShutdownSignalEscalation } from "./cli/shutdownSignalEscalation.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const CliRuntimeLayer = Layer.mergeAll(
BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer)),
NetService.layer,
);
const connectPublicConfigMissingMessage =
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
@@ -54,9 +59,12 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
export const cli = makeCli();
if (import.meta.main) {
const removeShutdownSignalEscalation = installNodeShutdownSignalEscalation();
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
Effect.ensuring(Effect.sync(removeShutdownSignalEscalation)),
NodeRuntime.runMain,
);
}
@@ -0,0 +1,291 @@
import { NodeServices } from "@effect/platform-node";
import { expect, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Deferred from "effect/Deferred";
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 Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { layer, make, type ChildProcessShutdownSignal } from "./boundedChildProcessSpawner.ts";
const makeHandle = (input: {
readonly pid: number;
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly isRunning: Effect.Effect<boolean>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly unref?: ChildProcessSpawner.ChildProcessHandle["unref"];
}) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(input.pid),
exitCode: input.exitCode,
isRunning: input.isRunning,
kill: input.kill ?? (() => Effect.void),
unref: input.unref ?? Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const errnoCode = (cause: unknown) =>
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
const isProcessAlive = (pid: number) => {
try {
process.kill(pid, 0);
return true;
} catch (cause) {
return errnoCode(cause) !== "ESRCH";
}
};
const killProcessGroup = (pid: number) => {
try {
process.kill(-pid, "SIGKILL");
} catch {
try {
process.kill(pid, "SIGKILL");
} catch {
// The process group has already exited.
}
}
};
const readFixturePids = (line: string) => {
const value: unknown = JSON.parse(line);
if (typeof value !== "object" || value === null) {
throw new Error("Expected the child fixture to print an object");
}
const pid = Reflect.get(value, "pid");
const descendantPid = Reflect.get(value, "descendantPid");
if (typeof pid !== "number" || typeof descendantPid !== "number") {
throw new Error("Expected numeric child fixture pids");
}
return { pid, descendantPid };
};
const waitForProcessesToStop = Effect.fn("waitForProcessesToStop")(function* (
pids: ReadonlyArray<number>,
timeoutMs: number,
) {
let remainingMs = timeoutMs;
while (pids.some(isProcessAlive)) {
if (remainingMs <= 0) return false;
const delayMs = Math.min(10, remainingMs);
yield* Effect.sleep(delayMs);
remainingMs -= delayMs;
}
return true;
});
it.effect("closes the delegate scope after a natural child exit", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const delegateClosed = yield* Deferred.make<void>();
const handle = makeHandle({
pid: 1,
exitCode: Deferred.await(exited),
isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
});
const delegate = ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() => Deferred.succeed(delegateClosed, undefined));
return handle;
}),
);
const spawner = make(delegate);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
expect(spawned.pid).toBe(handle.pid);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
yield* Deferred.await(delegateClosed).pipe(Effect.timeout("1 second"));
yield* Scope.close(callerScope, Exit.void);
}),
);
it.effect("preserves unref as an opt-out from scope-owned termination", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 43,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal === "SIGTERM" || killSignal === "SIGKILL") signals.push(killSignal);
}),
});
const spawner = make(
ChildProcessSpawner.make(() => Effect.succeed(handle)),
{
termGraceMs: 0,
killGraceMs: 0,
},
);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
const reref = yield* spawned.unref;
yield* Scope.close(callerScope, Exit.void);
expect(signals).toEqual([]);
yield* reref;
running = false;
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
}),
);
it.effect("bounds explicit handle kill calls and escalates to SIGKILL", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 44,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
signals.push(killSignal);
if (killSignal === "SIGKILL") running = false;
}).pipe(Effect.andThen(Deferred.await(exited)), Effect.asVoid),
});
const spawner = make(
ChildProcessSpawner.make(() => Effect.succeed(handle)),
{
termGraceMs: 0,
killGraceMs: 0,
},
);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
yield* spawned.kill({ forceKillAfter: 0 });
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
yield* Scope.close(callerScope, Exit.void);
}),
);
it.effect("does not wait for the delegate's unbounded finalizer", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const delegateCloseStarted = yield* Deferred.make<void>();
const allowDelegateClose = yield* Deferred.make<void>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 42,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
signals.push(killSignal);
if (killSignal === "SIGKILL") running = false;
}),
});
const delegate = ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Deferred.succeed(delegateCloseStarted, undefined).pipe(
Effect.andThen(Deferred.await(allowDelegateClose)),
),
);
return handle;
}),
);
const spawner = make(delegate, {
termGraceMs: 0,
killGraceMs: 0,
});
const callerScope = yield* Scope.make();
yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
yield* Scope.close(callerScope, Exit.void);
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
yield* Deferred.await(delegateCloseStarted).pipe(Effect.timeout("1 second"));
yield* Deferred.succeed(allowDelegateClose, undefined);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
}),
);
it.effect(
"kills a TERM-ignoring Node child and its descendant without blocking scope close",
() => {
const descendantScript = `
process.on("SIGTERM", () => {});
process.stdout.write("ready\\n");
setInterval(() => {}, 1_000);
`;
const childScript = `
const { spawn } = require("node:child_process");
process.on("SIGTERM", () => {});
const descendant = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], {
stdio: ["ignore", "pipe", "inherit"],
});
descendant.stdout.once("data", () => {
console.log(JSON.stringify({ pid: process.pid, descendantPid: descendant.pid }));
});
setInterval(() => {}, 1_000);
`;
const boundedLayer = layer({
termGraceMs: 100,
killGraceMs: 1_000,
pollIntervalMs: 10,
}).pipe(Layer.provideMerge(NodeServices.layer));
return Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const callerScope = yield* Scope.make();
const handle = yield* spawner
.spawn(ChildProcess.make(process.execPath, ["-e", childScript]))
.pipe(Effect.provideService(Scope.Scope, callerScope));
const line = yield* handle.stdout.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.runHead,
Effect.timeout("2 seconds"),
Effect.map(Option.getOrThrow),
);
const pids = readFixturePids(line);
yield* Effect.addFinalizer(() => Effect.sync(() => killProcessGroup(pids.pid)));
const closeFiber = yield* Scope.close(callerScope, Exit.void).pipe(
Effect.forkDetach({ startImmediately: true }),
);
yield* Fiber.join(closeFiber).pipe(Effect.timeout("2 seconds"));
expect(yield* waitForProcessesToStop([pids.pid, pids.descendantPid], 2_000)).toBe(true);
expect(isProcessAlive(pids.pid)).toBe(false);
expect(isProcessAlive(pids.descendantPid)).toBe(false);
}).pipe(Effect.scoped, Effect.provide(boundedLayer), TestClock.withLive);
},
);
@@ -0,0 +1,185 @@
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export type ChildProcessShutdownSignal = "SIGTERM" | "SIGKILL";
export interface BoundedChildProcessSpawnerOptions {
readonly termGraceMs?: number;
readonly killGraceMs?: number;
readonly pollIntervalMs?: number;
}
const DEFAULT_TERM_GRACE_MS = 2_000;
const DEFAULT_KILL_GRACE_MS = 1_000;
const DEFAULT_POLL_INTERVAL_MS = 25;
const normalizedDelay = (value: number | undefined, fallback: number) =>
value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value);
const isStillRunning = (handle: ChildProcessSpawner.ChildProcessHandle) =>
handle.isRunning.pipe(Effect.orElseSucceed(() => true));
const waitUntilStopped = Effect.fn("BoundedChildProcessSpawner.waitUntilStopped")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
timeoutMs: number,
pollIntervalMs: number,
) {
let remainingMs = timeoutMs;
while (yield* isStillRunning(handle)) {
if (remainingMs <= 0) return false;
const delayMs = Math.min(pollIntervalMs, remainingMs);
yield* Effect.sleep(delayMs);
remainingMs -= delayMs;
}
return true;
});
const closeScopeDetached = Effect.fn("BoundedChildProcessSpawner.closeScopeDetached")(function* (
scope: Scope.Closeable,
) {
yield* Scope.close(scope, Exit.void).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
});
export const make = (
delegate: ChildProcessSpawner.ChildProcessSpawner["Service"],
options: BoundedChildProcessSpawnerOptions = {},
) => {
const termGraceMs = normalizedDelay(options.termGraceMs, DEFAULT_TERM_GRACE_MS);
const killGraceMs = normalizedDelay(options.killGraceMs, DEFAULT_KILL_GRACE_MS);
const pollIntervalMs = Math.max(
1,
normalizedDelay(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS),
);
const sendSignal = Effect.fn("BoundedChildProcessSpawner.sendSignal")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
signal: ChildProcess.Signal,
) {
yield* handle
.kill({ killSignal: signal })
.pipe(Effect.ignore, Effect.forkDetach({ startImmediately: true }));
});
const kill = Effect.fn("BoundedChildProcessSpawner.kill")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
killOptions?: ChildProcess.KillOptions,
) {
if (!(yield* isStillRunning(handle))) return;
const initialSignal = killOptions?.killSignal ?? "SIGTERM";
const initialGraceMs =
initialSignal === "SIGKILL"
? killGraceMs
: Math.min(
termGraceMs,
normalizedDelay(
killOptions?.forceKillAfter === undefined
? undefined
: Duration.toMillis(killOptions.forceKillAfter),
termGraceMs,
),
);
yield* sendSignal(handle, initialSignal);
const stoppedAfterInitialSignal = yield* waitUntilStopped(
handle,
initialGraceMs,
pollIntervalMs,
);
if (stoppedAfterInitialSignal) return;
if (initialSignal !== "SIGKILL") {
yield* sendSignal(handle, "SIGKILL");
if (yield* waitUntilStopped(handle, killGraceMs, pollIntervalMs)) return;
}
yield* Effect.logWarning("Child process did not stop after SIGKILL grace period", {
pid: Number(handle.pid),
killGraceMs,
});
});
const shutdown = Effect.fn("BoundedChildProcessSpawner.shutdown")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
childScope: Scope.Closeable,
isReferenced: () => boolean,
) {
if (isReferenced()) {
yield* kill(handle);
}
// The platform spawner's own finalizer can wait forever for an exit event.
// Run it detached so it can finish normally without blocking the caller's
// scope when the operating system does not report an exit in time.
yield* closeScopeDetached(childScope);
});
const spawn = Effect.fn("BoundedChildProcessSpawner.spawn")(function* (
command: ChildProcess.Command,
) {
const childScope = yield* Scope.make("sequential");
const spawned = yield* delegate
.spawn(command)
.pipe(Effect.provideService(Scope.Scope, childScope), Effect.exit);
if (Exit.isFailure(spawned)) {
yield* closeScopeDetached(childScope);
return yield* Effect.failCause(spawned.cause);
}
const delegateHandle = spawned.value;
let referenced = true;
const handle = ChildProcessSpawner.makeHandle({
pid: delegateHandle.pid,
exitCode: delegateHandle.exitCode,
isRunning: delegateHandle.isRunning,
kill: (killOptions) => kill(delegateHandle, killOptions),
stdin: delegateHandle.stdin,
stdout: delegateHandle.stdout,
stderr: delegateHandle.stderr,
all: delegateHandle.all,
getInputFd: delegateHandle.getInputFd,
getOutputFd: delegateHandle.getOutputFd,
unref: delegateHandle.unref.pipe(
Effect.tap(() =>
Effect.sync(() => {
referenced = false;
}),
),
Effect.map((reref) =>
reref.pipe(
Effect.tap(() =>
Effect.sync(() => {
referenced = true;
}),
),
),
),
),
});
yield* Effect.addFinalizer(() => shutdown(delegateHandle, childScope, () => referenced));
yield* handle.exitCode.pipe(
Effect.exit,
Effect.andThen(Scope.close(childScope, Exit.void)),
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
return handle;
}, Effect.uninterruptible);
return ChildProcessSpawner.make(spawn);
};
export const layer = (options?: BoundedChildProcessSpawnerOptions) =>
Layer.effect(
ChildProcessSpawner.ChildProcessSpawner,
Effect.map(ChildProcessSpawner.ChildProcessSpawner, (delegate) => make(delegate, options)),
);
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vite-plus/test";
import {
installShutdownSignalEscalation,
type ShutdownSignal,
type ShutdownSignalEscalationOptions,
} from "./shutdownSignalEscalation.ts";
const makeHarness = () => {
const listeners: Record<ShutdownSignal, Set<() => void>> = {
SIGINT: new Set(),
SIGTERM: new Set(),
};
const exitCodes: Array<number> = [];
const timers = new Map<number, { readonly callback: () => void; readonly delayMs: number }>();
const clearedTimers: Array<number> = [];
let nextTimerHandle = 1;
const options = {
process: {
addSignalListener: (signal, listener) => {
listeners[signal].add(listener);
},
removeSignalListener: (signal, listener) => {
listeners[signal].delete(listener);
},
exit: (code) => {
exitCodes.push(code);
},
},
timers: {
setTimeout: (callback, delayMs) => {
const handle = nextTimerHandle;
nextTimerHandle += 1;
timers.set(handle, { callback, delayMs });
return handle;
},
clearTimeout: (handle) => {
clearedTimers.push(handle);
timers.delete(handle);
},
},
} satisfies ShutdownSignalEscalationOptions<number>;
const emit = (signal: ShutdownSignal) => {
for (const listener of listeners[signal]) listener();
};
const runNextTimer = () => {
const next = timers.entries().next();
if (next.done) throw new Error("Expected a pending timer");
const [handle, timer] = next.value;
timers.delete(handle);
timer.callback();
};
return { clearedTimers, emit, exitCodes, listeners, options, runNextTimer, timers };
};
describe("installShutdownSignalEscalation", () => {
it.each([
["SIGINT", 130],
["SIGTERM", 143],
] as const)("gives the first %s a bounded graceful-shutdown window", (signal, exitCode) => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation({
...harness.options,
forceExitAfterMs: 2_500,
});
harness.emit(signal);
expect(harness.exitCodes).toEqual([]);
expect([...harness.timers.values()].map((timer) => timer.delayMs)).toEqual([2_500]);
harness.runNextTimer();
expect(harness.exitCodes).toEqual([exitCode]);
dispose();
});
it("uses the second signal's conventional exit code immediately", () => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation(harness.options);
harness.emit("SIGTERM");
harness.emit("SIGINT");
expect(harness.exitCodes).toEqual([130]);
expect(harness.clearedTimers).toEqual([1]);
expect(harness.timers.size).toBe(0);
dispose();
});
it("removes both listeners and cancels the deadline when disposed", () => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation(harness.options);
harness.emit("SIGINT");
dispose();
dispose();
expect(harness.listeners.SIGINT.size).toBe(0);
expect(harness.listeners.SIGTERM.size).toBe(0);
expect(harness.clearedTimers).toEqual([1]);
expect(harness.timers.size).toBe(0);
harness.emit("SIGINT");
expect(harness.exitCodes).toEqual([]);
});
});
@@ -0,0 +1,94 @@
// @effect-diagnostics nodeBuiltinImport:off - This module is the CLI process and signal boundary.
import * as NodeProcess from "node:process";
import * as NodeTimers from "node:timers";
export type ShutdownSignal = "SIGINT" | "SIGTERM";
export interface ShutdownSignalProcessHooks {
readonly addSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
readonly removeSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
readonly exit: (code: number) => void;
}
export interface ShutdownSignalTimerHooks<TimerHandle> {
readonly setTimeout: (callback: () => void, delayMs: number) => TimerHandle;
readonly clearTimeout: (handle: TimerHandle) => void;
}
export interface ShutdownSignalEscalationOptions<TimerHandle> {
readonly process: ShutdownSignalProcessHooks;
readonly timers: ShutdownSignalTimerHooks<TimerHandle>;
readonly forceExitAfterMs?: number;
}
const defaultForceExitAfterMs = 10_000;
const conventionalExitCode = (signal: ShutdownSignal) => (signal === "SIGINT" ? 130 : 143);
export const installShutdownSignalEscalation = <TimerHandle>({
process: processHooks,
timers,
forceExitAfterMs = defaultForceExitAfterMs,
}: ShutdownSignalEscalationOptions<TimerHandle>) => {
let firstSignal: ShutdownSignal | undefined;
let forceExitTimer: { readonly handle: TimerHandle } | undefined;
let disposed = false;
const clearForceExitTimer = () => {
if (forceExitTimer === undefined) return;
timers.clearTimeout(forceExitTimer.handle);
forceExitTimer = undefined;
};
const forceExit = (signal: ShutdownSignal) => {
clearForceExitTimer();
processHooks.exit(conventionalExitCode(signal));
};
const handleSignal = (signal: ShutdownSignal) => {
if (firstSignal !== undefined) {
forceExit(signal);
return;
}
firstSignal = signal;
forceExitTimer = {
handle: timers.setTimeout(() => {
forceExitTimer = undefined;
processHooks.exit(conventionalExitCode(signal));
}, forceExitAfterMs),
};
};
const handleSigint = () => handleSignal("SIGINT");
const handleSigterm = () => handleSignal("SIGTERM");
processHooks.addSignalListener("SIGINT", handleSigint);
processHooks.addSignalListener("SIGTERM", handleSigterm);
return () => {
if (disposed) return;
disposed = true;
processHooks.removeSignalListener("SIGINT", handleSigint);
processHooks.removeSignalListener("SIGTERM", handleSigterm);
clearForceExitTimer();
};
};
export const installNodeShutdownSignalEscalation = () =>
installShutdownSignalEscalation({
process: {
addSignalListener: (signal, listener) => {
NodeProcess.on(signal, listener);
},
removeSignalListener: (signal, listener) => {
NodeProcess.removeListener(signal, listener);
},
exit: (code) => NodeProcess.exit(code),
},
timers: {
// @effect-diagnostics-next-line globalTimers:off - The forced exit deadline must outlive a stuck Effect shutdown.
setTimeout: (callback, delayMs) => NodeTimers.setTimeout(callback, delayMs),
clearTimeout: (handle) => NodeTimers.clearTimeout(handle),
},
});
@@ -45,6 +45,7 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -270,6 +271,12 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
refreshStatusUpstream: (cwd) =>
detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void,
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
+6 -1
View File
@@ -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
View File
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
+56 -75
View File
@@ -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);
+1 -4
View File
@@ -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");
}),
),
);
+257 -132
View File
@@ -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)),
+18 -1
View File
@@ -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,
+55
View File
@@ -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();
+38
View File
@@ -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,
@@ -3703,7 +3703,6 @@ describe("ClaudeAdapterLive", () => {
nativeThreadIds.push(threadId ?? null);
return Effect.void;
},
close: () => Effect.void,
},
});
return Effect.gen(function* () {
@@ -1347,13 +1347,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
Effect.provideService(Path.Path, path),
);
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
const createQuery =
options?.createQuery ??
@@ -1387,7 +1387,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
const logNativeSdkMessage = Effect.fnUntraced(function* (
context: ClaudeSessionContext,
message: SDKMessage,
) {
@@ -3843,6 +3843,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
@@ -1227,7 +1227,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const threadLogPath = NodePath.join(tempDir, "thread-logger.log");
const threadLogPath = NodePath.join(tempDir, "provider-native-thread-logger.log");
NodeAssert.equal(NodeFS.existsSync(threadLogPath), true);
const contents = NodeFS.readFileSync(threadLogPath, "utf8");
NodeAssert.match(contents, /NTIVE: .*"message":"native flush test"/);
@@ -1354,15 +1354,13 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* Effect.service(ServerConfig);
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
@@ -1637,7 +1635,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
),
);
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
@@ -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.sleep("10 millis").pipe(TestClock.withLive);
}
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(
@@ -321,15 +321,13 @@ export function makeCursorAdapter(
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, CursorSessionContext>();
@@ -785,6 +783,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":
@@ -4,6 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect, it } from "vite-plus/test";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
@@ -24,7 +25,11 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -293,6 +298,18 @@ const baseCursorSettings: CursorSettings = {
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const cursorCliCommandMissingMessage = [
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
@@ -411,10 +427,28 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
});
describe("checkCursorProviderStatus", () => {
it("reports the install docs when the Cursor CLI command is missing", async () => {
const provider = await runNode(
checkCursorProviderStatus({
enabled: true,
binaryPath: missingCursorBinaryPath,
apiEndpoint: "",
customModels: [],
}),
);
expect(provider).toMatchObject({
installed: false,
status: "error",
auth: { status: "unknown" },
message: cursorCliCommandMissingMessage,
});
});
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
const provider = await Effect.runPromise(
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,6 +62,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
"Check server logs for ACP details.",
].join(" ");
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
_meta: {
parameterizedModelPicker: true,
@@ -608,6 +615,14 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
return parts.length > 0 ? parts.join(" ") : undefined;
}
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
return [
`Cursor CLI command \`${binaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
].join(" ");
}
export function buildCursorProviderSnapshot(input: {
readonly checkedAt: string;
readonly cursorSettings: CursorSettings;
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1079,7 +1094,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
yield* Effect.logWarning("Cursor ACP model discovery failed", {
errorTag: causeErrorTag(discoveryExit.cause),
});
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} else if (Option.isNone(discoveryExit.value)) {
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
} else if (discoveryExit.value.value.length === 0) {
@@ -5,13 +5,25 @@ import * as NodePath from "node:path";
import { ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const decodeOmittedRecord = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({
_tag: Schema.String,
reason: Schema.String,
originalBytes: Schema.Number,
eventType: Schema.NullOr(Schema.String),
}),
),
);
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
@@ -32,6 +44,13 @@ function parseLogLine(line: string) {
};
}
function threadLogPath(basePath: string, threadSegment: string) {
return NodePath.join(
NodePath.dirname(basePath),
`${NodePath.parse(basePath).name}-${threadSegment}.log`,
);
}
describe("EventNdjsonLogger", () => {
it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
const messages: Array<unknown> = [];
@@ -55,6 +74,7 @@ describe("EventNdjsonLogger", () => {
assert.exists(logger);
if (!logger) return;
yield* logger.write(circular, ThreadId.make("thread-1"));
yield* logger.close();
const serialized = encodeUnknownJson(messages);
assert.notInclude(serialized, secret);
@@ -87,8 +107,8 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const threadOnePath = NodePath.join(tempDir, "thread-1.log");
const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
const threadOnePath = threadLogPath(basePath, "thread-1");
const threadTwoPath = threadLogPath(basePath, "thread-2");
assert.equal(NodeFS.existsSync(threadOnePath), true);
assert.equal(NodeFS.existsSync(threadTwoPath), true);
@@ -129,7 +149,7 @@ describe("EventNdjsonLogger", () => {
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
yield* logger.close();
const globalPath = NodePath.join(tempDir, "_global.log");
const globalPath = threadLogPath(basePath, "_global");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -172,7 +192,7 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const globalPath = NodePath.join(tempDir, "_global.log");
const globalPath = threadLogPath(basePath, "_global");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -190,25 +210,102 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("shares one thread writer across native and canonical streams", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
const native = store.logger("native");
const canonical = store.logger("canonical");
const threadId = ThreadId.make("thread-shared");
assert.notProperty(native, "close");
assert.notProperty(canonical, "close");
yield* native.write({ id: "native-event" }, threadId);
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-shared"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
assert.deepEqual(
lines.map(({ stream, payload }) => ({ stream, payload })),
[
{ stream: "NTIVE", payload: '{"id":"native-event"}' },
{
stream: "CANON",
payload: '{"type":"item.completed","id":"canonical-event"}',
},
],
);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("drops transient canonical events before serialization", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
const canonical = store.logger("canonical");
const native = store.logger("native");
const threadId = ThreadId.make("thread-filtered");
const circularDelta: Record<string, unknown> = { type: "content.delta" };
circularDelta["self"] = circularDelta;
yield* canonical.write(circularDelta, threadId);
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-filtered"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
assert.deepEqual(
lines.map(({ stream, payload }) => ({ stream, payload })),
[
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
],
);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("rotates per-thread files when max size is exceeded", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
try {
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "native",
maxBytes: 120,
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
maxFiles: 2,
batchWindowMs: 0,
maxBufferedBytes: 256,
maxRecordBytes: 256,
});
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
const native = store.logger("native");
const canonical = store.logger("canonical");
for (let index = 0; index < 10; index += 1) {
const logger = index % 2 === 0 ? native : canonical;
yield* logger.write(
{
type: "session.started",
threadId: "provider-thread-rotate",
id: `evt-${index}`,
payload: "x".repeat(40),
@@ -216,9 +313,9 @@ describe("EventNdjsonLogger", () => {
ThreadId.make("thread-rotate"),
);
}
yield* logger.close();
yield* store.close();
const fileStem = "thread-rotate.log";
const fileStem = NodePath.basename(threadLogPath(basePath, "thread-rotate"));
const matchingFiles = NodeFS.readdirSync(tempDir)
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
.toSorted();
@@ -235,6 +332,132 @@ describe("EventNdjsonLogger", () => {
matchingFiles.some((entry) => entry === `${fileStem}.3`),
false,
);
for (const entry of matchingFiles) {
assert.isAtMost(NodeFS.statSync(NodePath.join(tempDir, entry)).size, 512);
}
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("replaces oversized records with a bounded omission marker", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
maxRecordBytes: 256,
maxBufferedBytes: 256,
batchWindowMs: 0,
});
yield* store
.logger("canonical")
.write(
{ type: "item.completed", payload: "x".repeat(2_000) },
ThreadId.make("thread-oversized"),
);
yield* store
.logger("canonical")
.write(
{ type: "x".repeat(1_000), payload: "x".repeat(2_000) },
ThreadId.make("thread-oversized-type"),
);
yield* store.close();
const filePath = threadLogPath(basePath, "thread-oversized");
assert.isAtMost(NodeFS.statSync(filePath).size, 256);
const line = parseLogLine(NodeFS.readFileSync(filePath, "utf8").trim());
const payload = decodeOmittedRecord(line.payload);
assert.equal(payload._tag, "ProviderEventLogRecordOmitted");
assert.equal(payload.eventType, "item.completed");
assert.isAbove(payload.originalBytes, 2_000);
const longTypeFilePath = threadLogPath(basePath, "thread-oversized-type");
assert.isAtMost(NodeFS.statSync(longTypeFilePath).size, 256);
const longTypeLine = parseLogLine(NodeFS.readFileSync(longTypeFilePath, "utf8").trim());
const longTypePayload = decodeOmittedRecord(longTypeLine.payload);
assert.equal(longTypePayload.eventType, null);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("enforces aggregate age and byte retention on startup", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
const expiredPath = threadLogPath(basePath, "expired");
const oldPath = threadLogPath(basePath, "old");
const newPath = threadLogPath(basePath, "new");
const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
try {
yield* TestClock.setTime(1_800_000_000_000);
const now = yield* Clock.currentTimeMillis;
for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
NodeFS.writeFileSync(filePath, "x".repeat(400));
}
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
NodeFS.utimesSync(unrelatedLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
const store = yield* makeEventNdjsonLogStore(basePath, {
maxAgeMs: 10_000,
maxTotalBytes: 600,
});
yield* store.close();
assert.equal(NodeFS.existsSync(expiredPath), false);
assert.equal(NodeFS.existsSync(oldPath), false);
assert.equal(NodeFS.existsSync(newPath), true);
assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
assert.equal(NodeFS.existsSync(ignoredPath), true);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("keeps aggregate provider logs within the byte budget while writing", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
maxFiles: 2,
maxTotalBytes: 1_200,
maxBufferedBytes: 256,
maxRecordBytes: 256,
batchWindowMs: 0,
});
for (let index = 0; index < 30; index += 1) {
yield* store.logger(index % 2 === 0 ? "native" : "canonical").write(
{
type: "item.completed",
id: `evt-${index}`,
payload: "x".repeat(80),
},
ThreadId.make(`thread-${index % 4}`),
);
}
yield* store.close();
const totalBytes = NodeFS.readdirSync(tempDir, { withFileTypes: true })
.filter((entry) => entry.isFile() && /^events-.+\.log(?:\.\d+)?$/u.test(entry.name))
.reduce(
(total, entry) => total + NodeFS.statSync(NodePath.join(tempDir, entry.name)).size,
0,
);
assert.isAtMost(totalBytes, 1_200);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
@@ -1,10 +1,9 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Provider event logger helper.
* Best-effort provider event logging with one shared writer store.
*
* Best-effort writer for observability logs. Each record is formatted as a
* single effect-style text line in a thread-scoped file. Failures are
* downgraded to warnings so provider runtime behavior is unaffected.
* Native and canonical views share batching, rotation, and retention state so
* they cannot race while appending to the same thread-scoped file.
*/
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
@@ -12,84 +11,435 @@ import * as NodePath from "node:path";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { errorTag } from "@t3tools/shared/observability";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
const MEBIBYTE = 1024 * 1024;
const DAY_MS = 24 * 60 * 60 * 1_000;
const MIN_RECORD_BYTES = 256;
const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
const DEFAULT_MAX_FILES = 10;
const DEFAULT_BATCH_WINDOW_MS = 200;
const DEFAULT_BATCH_WINDOW_MS = 1_000;
const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
const DEFAULT_MAX_RECORD_BYTES = MEBIBYTE;
const DEFAULT_MAX_CACHED_SINKS = 64;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const transientCanonicalEventTypes = new Set([
"content.delta",
"hook.progress",
"item.updated",
"task.progress",
"thread.realtime.audio.delta",
"tool.progress",
"turn.proposed.delta",
]);
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
export interface EventNdjsonLogger {
readonly filePath: string;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
close: () => Effect.Effect<void, never, never>;
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
}
export interface EventNdjsonLoggerOptions {
readonly stream: EventNdjsonStream;
export interface ManagedEventNdjsonLogger extends EventNdjsonLogger {
readonly close: () => Effect.Effect<void>;
}
export interface EventNdjsonLogStore {
readonly filePath: string;
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
readonly close: () => Effect.Effect<void>;
}
export interface EventNdjsonLogStoreOptions {
readonly maxBytes?: number;
readonly maxFiles?: number;
readonly batchWindowMs?: number;
readonly maxTotalBytes?: number;
readonly maxAgeMs?: number;
readonly retentionCheckIntervalMs?: number;
readonly maxBufferedBytes?: number;
readonly maxBufferedRecords?: number;
readonly maxRecordBytes?: number;
readonly maxCachedSinks?: number;
}
interface ThreadWriter {
writeMessage: (message: string) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
readonly stream: EventNdjsonStream;
}
interface LoggerState {
readonly threadWriters: Map<string, ThreadWriter>;
readonly failedSegments: Set<string>;
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
"EventNdjsonLogConfigurationError",
{
filePath: Schema.String,
option: Schema.String,
value: Schema.Number,
minimum: Schema.Number,
},
) {
override get message(): string {
return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
}
}
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
"EventNdjsonLogDirectoryError",
{
directory: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to create provider event log directory '${this.directory}'`;
}
}
export type EventNdjsonLogStoreError =
| EventNdjsonLogConfigurationError
| EventNdjsonLogDirectoryError;
interface ResolvedOptions {
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly retentionCheckIntervalMs: number;
readonly maxBufferedBytes: number;
readonly maxBufferedRecords: number;
readonly maxRecordBytes: number;
readonly maxCachedSinks: number;
}
interface PendingRecord {
readonly threadSegment: string;
readonly line: string;
readonly bytes: number;
}
interface StoreState {
readonly pending: ReadonlyArray<PendingRecord>;
readonly pendingBytes: number;
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
readonly closed: boolean;
readonly lastRetentionAt: number;
readonly retainedBytesEstimate: number;
}
interface FileOperationFailure {
readonly filePath: string;
readonly cause: unknown;
}
interface RetentionResult {
readonly failures: ReadonlyArray<FileOperationFailure>;
readonly removedCount: number;
readonly totalBytes: number;
}
interface DrainResult {
readonly failures: ReadonlyArray<FileOperationFailure>;
}
function logWarning(message: string, context: Record<string, unknown>) {
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
}
function resolveThreadSegment(raw: string | null | undefined): string {
function resolveThreadSegment(raw: string | null | undefined) {
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
return normalized ?? GLOBAL_THREAD_SEGMENT;
}
function formatLoggerMessage(message: unknown): string {
if (Array.isArray(message)) {
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
function resolveStreamLabel(stream: EventNdjsonStream) {
return stream === "native" ? "NTIVE" : "CANON";
}
function shouldPersist(stream: EventNdjsonStream, event: unknown) {
if (stream !== "canonical" || typeof event !== "object" || event === null) {
return true;
}
return typeof message === "string" ? message : String(message);
const type = Reflect.get(event, "type");
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
}
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
return Logger.make(
({ date, message }) =>
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
);
function eventType(event: unknown) {
if (typeof event !== "object" || event === null) return null;
const type = Reflect.get(event, "type");
return typeof type === "string" ? type.slice(0, 128) : null;
}
function resolveStreamLabel(stream: EventNdjsonStream): string {
switch (stream) {
case "native":
return "NTIVE";
case "canonical":
case "orchestration":
default:
return "CANON";
function formatRecordLine(input: {
readonly stream: EventNdjsonStream;
readonly event: unknown;
readonly observedAt: string;
readonly payload: string;
readonly maxRecordBytes: number;
}) {
const prefix = `[${input.observedAt}] ${resolveStreamLabel(input.stream)}: `;
const line = `${prefix}${input.payload}\n`;
const bytes = Buffer.byteLength(line);
if (bytes <= input.maxRecordBytes) {
return { line, bytes };
}
const omittedPayload = (type: string | null) =>
JSON.stringify({
_tag: "ProviderEventLogRecordOmitted",
reason: "record_too_large",
originalBytes: bytes,
eventType: type,
});
let omittedLine = `${prefix}${omittedPayload(eventType(input.event))}\n`;
if (Buffer.byteLength(omittedLine) > input.maxRecordBytes) {
omittedLine = `${prefix}${omittedPayload(null)}\n`;
}
return {
line: omittedLine,
bytes: Buffer.byteLength(omittedLine),
};
}
const toLogMessage = Effect.fn("toLogMessage")(function* (
event: unknown,
): Effect.fn.Return<string | undefined> {
function writeBatchedRecords(
sink: RotatingFileSink,
records: ReadonlyArray<PendingRecord>,
maxChunkBytes: number,
) {
let pendingLines: Array<string> = [];
let pendingBytes = 0;
const flush = () => {
if (pendingLines.length === 0) return;
sink.write(pendingLines.join(""));
pendingLines = [];
pendingBytes = 0;
};
for (const record of records) {
if (pendingBytes > 0 && pendingBytes + record.bytes > maxChunkBytes) {
flush();
}
pendingLines.push(record.line);
pendingBytes += record.bytes;
if (pendingBytes >= maxChunkBytes) {
flush();
}
}
flush();
}
function enforceRetention(input: {
readonly directory: string;
readonly filePattern: RegExp;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly now: number;
}): RetentionResult {
const failures: Array<FileOperationFailure> = [];
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
let entries: ReadonlyArray<NodeFS.Dirent>;
try {
entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
} catch (cause) {
return {
failures: [{ filePath: input.directory, cause }],
removedCount: 0,
totalBytes: input.maxTotalBytes + 1,
};
}
for (const entry of entries) {
if (!entry.isFile() || !input.filePattern.test(entry.name)) continue;
const filePath = NodePath.join(input.directory, entry.name);
try {
const stat = NodeFS.statSync(filePath);
files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
} catch (cause) {
failures.push({ filePath, cause });
}
}
let totalBytes = files.reduce((total, file) => total + file.size, 0);
let removedCount = 0;
const remove = (file: (typeof files)[number]) => {
try {
NodeFS.rmSync(file.filePath, { force: true });
totalBytes -= file.size;
removedCount += 1;
return true;
} catch (cause) {
failures.push({ filePath: file.filePath, cause });
return false;
}
};
const retained = files.filter((file) => {
if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
return !remove(file);
});
for (const file of retained.toSorted(
(left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
)) {
if (totalBytes <= input.maxTotalBytes) break;
if (!remove(file)) break;
}
return { failures, removedCount, totalBytes };
}
function validateOption(input: {
readonly filePath: string;
readonly option: string;
readonly value: number;
readonly minimum: number;
}) {
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
return new EventNdjsonLogConfigurationError(input);
}
function resolveOptions(filePath: string, options: EventNdjsonLogStoreOptions) {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
const requestedMaxRecordBytes = options.maxRecordBytes ?? DEFAULT_MAX_RECORD_BYTES;
const resolved = {
maxBytes,
maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
retentionCheckIntervalMs:
options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
maxBufferedBytes,
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
maxRecordBytes: Math.min(requestedMaxRecordBytes, maxBytes, maxBufferedBytes),
maxCachedSinks: options.maxCachedSinks ?? DEFAULT_MAX_CACHED_SINKS,
} satisfies ResolvedOptions;
const validations = [
["maxBytes", maxBytes, MIN_RECORD_BYTES],
["maxFiles", resolved.maxFiles, 1],
["batchWindowMs", resolved.batchWindowMs, 0],
["maxTotalBytes", resolved.maxTotalBytes, 1],
["maxAgeMs", resolved.maxAgeMs, 1],
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
["maxBufferedBytes", maxBufferedBytes, MIN_RECORD_BYTES],
["maxBufferedRecords", resolved.maxBufferedRecords, 1],
["maxRecordBytes", requestedMaxRecordBytes, MIN_RECORD_BYTES],
["maxCachedSinks", resolved.maxCachedSinks, 1],
] as const;
for (const [option, value, minimum] of validations) {
const error = validateOption({ filePath, option, value, minimum });
if (error) return Effect.fail(error);
}
return Effect.succeed(resolved);
}
function drainPending(input: {
readonly directory: string;
readonly filePrefix: string;
readonly filePattern: RegExp;
readonly options: ResolvedOptions;
readonly state: StoreState;
readonly now: number;
readonly close: boolean;
}): readonly [DrainResult, StoreState] {
if (input.state.closed) {
return [{ failures: [] }, input.state];
}
let sinks = new Map(input.state.sinks);
const failures: Array<FileOperationFailure> = [];
const recordsBySegment = new Map<string, Array<PendingRecord>>();
for (const record of input.state.pending) {
const records = recordsBySegment.get(record.threadSegment) ?? [];
records.push(record);
recordsBySegment.set(record.threadSegment, records);
}
let writtenBytes = 0;
for (const [threadSegment, records] of recordsBySegment) {
const filePath = NodePath.join(input.directory, `${input.filePrefix}-${threadSegment}.log`);
let sink = sinks.get(threadSegment);
try {
if (!sink) {
sink = new RotatingFileSink({
filePath,
maxBytes: input.options.maxBytes,
maxFiles: input.options.maxFiles,
throwOnError: true,
});
}
sinks.delete(threadSegment);
sinks.set(threadSegment, sink);
while (sinks.size > input.options.maxCachedSinks) {
const oldest = sinks.keys().next().value;
if (oldest === undefined) break;
sinks.delete(oldest);
}
writeBatchedRecords(
sink,
records,
Math.min(input.options.maxBytes, input.options.maxBufferedBytes),
);
writtenBytes += records.reduce((total, record) => total + record.bytes, 0);
} catch (cause) {
sinks.delete(threadSegment);
failures.push({ filePath, cause });
}
}
const retainedBytesEstimate = input.state.retainedBytesEstimate + writtenBytes;
const retentionDue =
input.close ||
failures.length > 0 ||
retainedBytesEstimate > input.options.maxTotalBytes ||
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
const retention = retentionDue
? enforceRetention({
directory: input.directory,
filePattern: input.filePattern,
maxTotalBytes: input.options.maxTotalBytes,
maxAgeMs: input.options.maxAgeMs,
now: input.now,
})
: null;
if (retention && retention.removedCount > 0) {
sinks = new Map();
}
return [
{
failures: [...failures, ...(retention?.failures ?? [])],
},
{
pending: [],
pendingBytes: 0,
sinks,
closed: input.close,
lastRetentionAt: retention ? input.now : input.state.lastRetentionAt,
retainedBytesEstimate: retention?.totalBytes ?? retainedBytesEstimate,
},
];
}
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
return yield* encodeUnknownJsonString(event).pipe(
Effect.catch((error) =>
logWarning("failed to serialize provider event log record", {
@@ -99,188 +449,169 @@ const toLogMessage = Effect.fn("toLogMessage")(function* (
);
});
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.fn.Return<ThreadWriter | undefined> {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
filePath: string,
options: EventNdjsonLogStoreOptions = {},
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
const resolved = yield* resolveOptions(filePath, options);
const directory = NodePath.dirname(filePath);
const filePrefix =
toSafeThreadAttachmentSegment(NodePath.parse(filePath).name) ?? "provider-events";
const filePattern = new RegExp(`^${filePrefix}-.+\\.log(?:\\.\\d+)?$`, "u");
yield* Effect.try({
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
});
const initializedAt = yield* Clock.currentTimeMillis;
const initialRetention = yield* Effect.sync(() =>
enforceRetention({
directory,
filePattern,
maxTotalBytes: resolved.maxTotalBytes,
maxAgeMs: resolved.maxAgeMs,
now: initializedAt,
}),
);
for (const failure of initialRetention.failures) {
yield* logWarning("provider event log retention failed", {
filePath: failure.filePath,
errorTag: errorTag(failure.cause),
});
}
const stateRef = yield* SynchronizedRef.make<StoreState>({
pending: [],
pendingBytes: 0,
sinks: new Map(),
closed: false,
lastRetentionAt: initializedAt,
retainedBytesEstimate: initialRetention.totalBytes,
});
const timerScope = yield* Scope.make();
const reportDrainResult = Effect.fnUntraced(function* (result: DrainResult) {
for (const failure of result.failures) {
yield* logWarning("provider event log write or retention failed", {
filePath: failure.filePath,
errorTag: errorTag(failure.cause),
});
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
errorTag: errorTag(sinkResult.error),
});
return undefined;
const flush = Effect.fnUntraced(function* (close: boolean) {
const now = yield* Clock.currentTimeMillis;
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.sync(() =>
drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state,
now,
close,
}),
),
);
yield* reportDrainResult(result);
});
if (resolved.batchWindowMs > 0) {
yield* Effect.forkIn(
Effect.forever(Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(false)))),
timerScope,
{ startImmediately: true },
);
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
const close = Effect.fnUntraced(function* () {
yield* flush(true);
yield* Scope.close(timerScope, Exit.void);
});
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
const existing = loggerViews.get(stream);
if (existing) return existing;
const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
if (!shouldPersist(stream, event)) return;
const payload = yield* serializeEvent(event);
if (payload === undefined) return;
const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
const record = formatRecordLine({
stream,
event,
observedAt,
payload,
maxRecordBytes: resolved.maxRecordBytes,
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
errorTag: errorTag(flushResult.error),
const now = yield* Clock.currentTimeMillis;
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.closed) {
return Effect.succeed([null, state] as const);
}
const pending = [
...state.pending,
{
threadSegment: resolveThreadSegment(threadId),
line: record.line,
bytes: record.bytes,
},
];
const pendingBytes = state.pendingBytes + record.bytes;
const shouldFlush =
resolved.batchWindowMs === 0 ||
pending.length >= resolved.maxBufferedRecords ||
pendingBytes >= resolved.maxBufferedBytes;
const nextState = {
...state,
pending,
pendingBytes,
};
if (!shouldFlush) {
return Effect.succeed([null, nextState] as const);
}
return Effect.sync(() => {
const [drainResult, drainedState] = drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state: nextState,
now,
close: false,
});
return [drainResult, drainedState] as const;
});
});
if (result) {
yield* reportDrainResult(result);
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
});
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
const view = { filePath, write } satisfies EventNdjsonLogger;
loggerViews.set(stream, view);
return view;
};
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
return { filePath, logger, close } satisfies EventNdjsonLogStore;
});
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.fn.Return<EventNdjsonLogger | undefined> {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
errorTag: errorTag(directoryReady.error),
});
return undefined;
}
const stateRef = yield* SynchronizedRef.make<LoggerState>({
threadWriters: new Map(),
failedSegments: new Set(),
});
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.failedSegments.has(threadSegment)) {
return Effect.succeed([undefined, state] as const);
}
const existing = state.threadWriters.get(threadSegment);
if (existing) {
return Effect.succeed([existing, state] as const);
}
return makeThreadWriter({
filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
}).pipe(
Effect.map((writer) => {
if (!writer) {
const nextFailedSegments = new Set(state.failedSegments);
nextFailedSegments.add(threadSegment);
return [
undefined,
{
...state,
failedSegments: nextFailedSegments,
},
] as const;
}
const nextThreadWriters = new Map(state.threadWriters);
nextThreadWriters.set(threadSegment, writer);
return [
writer,
{
...state,
threadWriters: nextThreadWriters,
},
] as const;
}),
);
});
});
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
const close = Effect.fn("close")(function* () {
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.gen(function* () {
for (const writer of state.threadWriters.values()) {
yield* writer.close();
}
return [
undefined,
{
threadWriters: new Map<string, ThreadWriter>(),
failedSegments: new Set<string>(),
},
] as const;
}),
);
});
return {
filePath,
write,
close,
} satisfies EventNdjsonLogger;
): Effect.fn.Return<ManagedEventNdjsonLogger | undefined> {
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
Effect.catch((error) =>
logWarning(error.message, { error }).pipe(
Effect.as<EventNdjsonLogStore | undefined>(undefined),
),
),
);
if (!store) return undefined;
return { ...store.logger(options.stream), close: store.close };
});
@@ -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,782 @@ 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,
},
});
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 +1150,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);
@@ -355,7 +1175,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
record.event.kind === "notification"
? Effect.die(new Error("native log write failed"))
: Effect.void,
close: () => Effect.void,
},
});
const contentDelta = yield* Deferred.make<void>();
+516 -62
View File
@@ -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");
@@ -178,13 +232,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, GrokSessionContext>();
@@ -240,6 +292,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 +461,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 +474,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 +616,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 +640,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 +679,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 +706,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 +772,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
interruptedTurnIds: new Set(),
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
@@ -586,14 +781,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 +822,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 +921,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 +998,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 +1044,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 +1072,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 +1094,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 +1184,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 +1202,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,
};
}
}),
);
});
@@ -433,17 +433,15 @@ export function makeOpenCodeAdapter(
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined);
// Only close loggers we created. If the caller passed one in via
// `options.nativeEventLogger`, they own its lifecycle.
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, OpenCodeSessionContext>();
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
@@ -1,6 +1,6 @@
/**
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
* ProviderEventLoggers — single observability service that owns the shared
* provider event log store and exposes its two runtime views:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
@@ -13,17 +13,14 @@
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* should share one underlying log store — opening N writers against the
* same rotating file would race the rotation logic. Owning the loggers on
* a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
* Both fields are optional because observability must not prevent startup.
*
* @module provider/Layers/ProviderEventLoggers
*/
@@ -32,7 +29,11 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "../../config.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import {
type EventNdjsonLogger,
type EventNdjsonLogStore,
makeEventNdjsonLogStore,
} from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
@@ -63,23 +64,30 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
};
/**
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
* Live layer that builds both stream views over one shared store. Setup
* failures are logged and downgraded to the no-op service so diagnostics never
* block startup. The layer scope flushes and closes the store during shutdown.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
const store = yield* makeEventNdjsonLogStore(providerEventLogPath).pipe(
Effect.catch((error) =>
Effect.logWarning(error.message, { error }).pipe(
Effect.annotateLogs({ scope: "provider-observability" }),
Effect.as<EventNdjsonLogStore | undefined>(undefined),
),
),
);
if (!store) {
return NoOpProviderEventLoggers;
}
yield* Effect.addFinalizer(() => store.close());
return {
native,
canonical,
native: store.logger("native"),
canonical: store.logger("canonical"),
} satisfies ProviderEventLoggersShape;
}),
);
@@ -605,7 +605,6 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
canonicalThreadIds.push(threadId ?? null);
return Effect.void;
},
close: () => Effect.void,
},
}).pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
@@ -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");
@@ -21,7 +21,6 @@ nodeServicesIt("ACP native logging", (it) => {
const nativeEventLogger: EventNdjsonLogger = {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
};
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
@@ -84,7 +83,6 @@ nodeServicesIt("ACP native logging", (it) => {
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: () => Effect.die(new Error(secret)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
@@ -113,7 +111,6 @@ nodeServicesIt("ACP native logging", (it) => {
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: () => Effect.interrupt,
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
@@ -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>;
+177 -46
View File
@@ -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";
}
}
+67
View File
@@ -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;
+2 -1
View File
@@ -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* () {
+1
View File
@@ -199,6 +199,7 @@ export class GitVcsDriver extends Context.Service<
cwd: string,
options?: GitRemoteStatusOptions,
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
+321 -1
View File
@@ -2,12 +2,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import { GitCommandError } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { ServerConfig } from "../config.ts";
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
@@ -58,6 +61,20 @@ const git = (
return result.stdout.trim();
});
const findGitExecutable = Effect.fn("GitVcsDriver.test.findGitExecutable")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const pathDelimiter = (yield* HostProcessPlatform) === "win32" ? ";" : ":";
for (const entry of (process.env.PATH ?? "").split(pathDelimiter)) {
if (entry.length === 0) continue;
const candidate = pathService.join(entry, "git");
if (yield* fileSystem.exists(candidate)) {
return yield* fileSystem.realPath(candidate);
}
}
return yield* Effect.die(new Error("Could not find the Git executable in PATH."));
});
const initRepoWithCommit = (
cwd: string,
): Effect.Effect<
@@ -148,6 +165,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
const cwd = pathService.join(parent, "missing");
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.refreshStatusUpstream(cwd);
const [localStatus, remoteStatus, refs] = yield* Effect.all([
driver.statusDetails(cwd),
driver.statusDetailsRemote(cwd, { refreshUpstream: false }),
@@ -435,8 +453,16 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
const refreshError = yield* (yield* GitVcsDriver.GitVcsDriver)
.refreshStatusUpstream(cwd)
.pipe(Effect.flip);
assert.deepInclude(refreshError, {
_tag: "GitCommandError",
operation: "GitVcsDriver.fetchRemoteForStatus",
cwd,
detail: "Background Git fetch failed.",
});
assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
"GCM_INTERACTIVE=never",
"GIT_ASKPASS=",
@@ -461,6 +487,300 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("fetches status remotes from the worktree with hardened background flags", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetch-invocation.txt");
const fetchHeadPath = pathService.join(cwd, ".git", "FETCH_HEAD");
const previousPath = process.env.PATH;
const previousRealGit = process.env.T3_TEST_REAL_GIT;
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* fileSystem.writeFileString(fetchHeadPath, "sentinel-fetch-head\n");
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "cwd=%s\\n" "$PWD" > "$T3_TEST_FETCH_INVOCATION_LOG"',
' for arg in "$@"; do',
' printf "arg=%s\\n" "$arg" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
" done",
"fi",
'exec "$T3_TEST_REAL_GIT" "$@"',
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).refreshStatusUpstream(cwd);
assert.deepStrictEqual(
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
[
`cwd=${cwd}`,
"arg=fetch",
"arg=--quiet",
"arg=--no-tags",
"arg=--no-write-fetch-head",
"arg=--no-auto-maintenance",
"arg=--no-recurse-submodules",
"arg=--",
"arg=origin",
],
);
assert.equal(yield* fileSystem.readFileString(fetchHeadPath), "sentinel-fetch-head\n");
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
else process.env.T3_TEST_REAL_GIT = previousRealGit;
if (previousInvocationLog === undefined) {
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
} else {
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
}
}),
),
);
}),
);
it.effect("coalesces matching refreshes and serializes different remotes sharing objects", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const backup = yield* makeTmpDir("git-vcs-driver-backup-");
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const worktreeCwd = pathService.join(worktreeParent, "feature");
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
const activeLockPath = pathService.join(wrapperDir, "active-fetch");
const overlapLogPath = pathService.join(wrapperDir, "overlap.txt");
const previousPath = process.env.PATH;
const previousRealGit = process.env.T3_TEST_REAL_GIT;
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
const previousActiveLock = process.env.T3_TEST_FETCH_ACTIVE_LOCK;
const previousOverlapLog = process.env.T3_TEST_FETCH_OVERLAP_LOG;
yield* git(origin, ["init", "--bare"]);
yield* git(backup, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["remote", "add", "backup", backup]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["worktree", "add", "-b", "feature/serialized", worktreeCwd]);
yield* git(worktreeCwd, ["push", "-u", "backup", "feature/serialized"]);
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "start\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
' if ! mkdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null; then',
' printf "overlap\\n" >> "$T3_TEST_FETCH_OVERLAP_LOG"',
" fi",
" sleep 0.2",
' "$T3_TEST_REAL_GIT" "$@"',
" status=$?",
' rmdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null || true',
' printf "end\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
" exit $status",
"fi",
'exec "$T3_TEST_REAL_GIT" "$@"',
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
process.env.T3_TEST_FETCH_ACTIVE_LOCK = activeLockPath;
process.env.T3_TEST_FETCH_OVERLAP_LOG = overlapLogPath;
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* Effect.all(
[
driver.refreshStatusUpstream(cwd),
driver.refreshStatusUpstream(cwd),
driver.refreshStatusUpstream(worktreeCwd),
],
{ concurrency: "unbounded", discard: true },
);
const invocationLines = (yield* fileSystem.readFileString(invocationLogPath))
.trim()
.split(/\r?\n/);
assert.deepStrictEqual(invocationLines, ["start", "end", "start", "end"]);
assert.equal(yield* fileSystem.exists(overlapLogPath), false);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
else process.env.T3_TEST_REAL_GIT = previousRealGit;
if (previousInvocationLog === undefined) {
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
} else {
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
}
if (previousActiveLock === undefined) delete process.env.T3_TEST_FETCH_ACTIVE_LOCK;
else process.env.T3_TEST_FETCH_ACTIVE_LOCK = previousActiveLock;
if (previousOverlapLog === undefined) delete process.env.T3_TEST_FETCH_OVERLAP_LOG;
else process.env.T3_TEST_FETCH_OVERLAP_LOG = previousOverlapLog;
}),
),
);
}),
);
it.effect("keeps a waiting worktree refresh alive when the cache owner disconnects", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const worktreeCwd = pathService.join(worktreeParent, "feature");
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
const ownerLockPath = pathService.join(wrapperDir, "owner-fetch");
const ownerStartedPath = pathService.join(wrapperDir, "owner-started");
const waiterReadyPath = pathService.join(wrapperDir, "waiter-ready");
const envKeys = [
"PATH",
"T3_TEST_REAL_GIT",
"T3_TEST_FETCH_INVOCATION_LOG",
"T3_TEST_FETCH_OWNER_LOCK",
"T3_TEST_FETCH_OWNER_STARTED",
"T3_TEST_FETCH_WAITER_CWD",
"T3_TEST_FETCH_WAITER_READY",
] as const;
const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
yield* git(origin, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["worktree", "add", "-b", "feature/interrupted", worktreeCwd]);
yield* git(worktreeCwd, ["push", "-u", "origin", "feature/interrupted"]);
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
"is_common_dir=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
' if [ "$arg" = "--git-common-dir" ]; then is_common_dir=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "start:%s\\n" "$PWD" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
' if mkdir "$T3_TEST_FETCH_OWNER_LOCK" 2>/dev/null; then',
' : > "$T3_TEST_FETCH_OWNER_STARTED"',
" trap 'exit 130' INT TERM HUP",
" while :; do sleep 1; done",
" fi",
' exec "$T3_TEST_REAL_GIT" "$@"',
"fi",
'"$T3_TEST_REAL_GIT" "$@"',
"status=$?",
'if [ "$PWD" = "$T3_TEST_FETCH_WAITER_CWD" ] && [ "$is_common_dir" = "1" ]; then',
' : > "$T3_TEST_FETCH_WAITER_READY"',
"fi",
"exit $status",
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousEnv.get("PATH") ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
process.env.T3_TEST_FETCH_OWNER_LOCK = ownerLockPath;
process.env.T3_TEST_FETCH_OWNER_STARTED = ownerStartedPath;
process.env.T3_TEST_FETCH_WAITER_CWD = worktreeCwd;
process.env.T3_TEST_FETCH_WAITER_READY = waiterReadyPath;
const waitForFile = (filePath: string) =>
Effect.gen(function* () {
while (!(yield* fileSystem.exists(filePath))) {
yield* Effect.sleep("10 millis");
}
}).pipe(Effect.timeout("2 seconds"));
const driver = yield* GitVcsDriver.GitVcsDriver;
const owner = yield* driver.refreshStatusUpstream(cwd).pipe(Effect.forkChild);
yield* waitForFile(ownerStartedPath);
const waiter = yield* driver.refreshStatusUpstream(worktreeCwd).pipe(Effect.forkChild);
yield* waitForFile(waiterReadyPath);
yield* Effect.sleep("50 millis");
yield* Fiber.interrupt(owner);
yield* Fiber.join(waiter).pipe(Effect.timeout("5 seconds"));
assert.deepStrictEqual(
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
[`start:${cwd}`, `start:${worktreeCwd}`],
);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
for (const key of envKeys) {
const previous = previousEnv.get(key);
if (previous === undefined) delete process.env[key];
else process.env[key] = previous;
}
}),
),
TestClock.withLive,
);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+133 -43
View File
@@ -1,13 +1,15 @@
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Data from "effect/Data";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Encoding from "effect/Encoding";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Hash from "effect/Hash";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
@@ -50,7 +52,7 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
GCM_INTERACTIVE: "never",
@@ -74,6 +76,11 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
behindCount: 0,
aheadOfDefaultCount: 0,
});
export const statusUpstreamRefreshCacheTimeToLive = <A, E>(exit: Exit.Exit<A, E>) => {
if (Exit.isSuccess(exit)) return STATUS_UPSTREAM_REFRESH_INTERVAL;
return Cause.hasInterrupts(exit.cause) ? Duration.zero : STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN;
};
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
isRepo: false,
isDefaultBranch: false,
@@ -90,10 +97,35 @@ type TraceTailState = {
remainder: string;
};
class StatusRemoteRefreshCacheKey extends Data.Class<{
gitCommonDir: string;
remoteName: string;
}> {}
class StatusRemoteRefreshCacheKey {
readonly objectDir: string;
readonly remoteName: string;
readonly cwd: string;
constructor(objectDir: string, remoteName: string, cwd: string) {
this.objectDir = objectDir;
this.remoteName = remoteName;
this.cwd = cwd;
}
[Equal.symbol](that: unknown) {
return (
that instanceof StatusRemoteRefreshCacheKey &&
this.objectDir === that.objectDir &&
this.remoteName === that.remoteName &&
this.cwd === that.cwd
);
}
[Hash.symbol]() {
return Hash.string(`${this.objectDir}\0${this.remoteName}\0${this.cwd}`);
}
}
interface StatusRefreshLock {
readonly semaphore: Semaphore.Semaphore;
readonly users: number;
}
interface ExecuteGitOptions {
stdin?: string | undefined;
@@ -920,23 +952,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
});
const fetchRemoteForStatus = (
gitCommonDir: string,
remoteName: string,
): Effect.Effect<void, GitCommandError> => {
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
const fetchRemoteForStatus = (cwd: string, remoteName: string) =>
executeGit(
"GitVcsDriver.fetchRemoteForStatus",
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
cwd,
[
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-auto-maintenance",
"--no-recurse-submodules",
"--",
remoteName,
],
{
allowNonZeroExit: true,
env: STATUS_UPSTREAM_REFRESH_ENV,
fallbackErrorDetail: "Background Git fetch failed.",
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
},
).pipe(Effect.asVoid);
};
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
const gitCommonDir = yield* runGitStdout("GitVcsDriver.resolveGitCommonDir", cwd, [
@@ -946,20 +981,76 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const resolveCanonicalGitObjectDir = Effect.fn("resolveCanonicalGitObjectDir")(function* (
cwd: string,
) {
const gitCommonDir = yield* resolveGitCommonDir(cwd);
const objectDir = path.join(gitCommonDir, "objects");
return yield* fileSystem.realPath(objectDir).pipe(Effect.orElseSucceed(() => objectDir));
});
const statusRefreshLocks = yield* Ref.make<ReadonlyMap<string, StatusRefreshLock>>(new Map());
const statusRefreshLocksGuard = yield* Semaphore.make(1);
const withStatusRefreshLock = <A, E, R>(objectDir: string, effect: Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
statusRefreshLocksGuard.withPermits(1)(
Effect.gen(function* () {
const current = yield* Ref.get(statusRefreshLocks);
const existing = current.get(objectDir);
if (existing) {
yield* Ref.set(
statusRefreshLocks,
new Map(current).set(objectDir, {
semaphore: existing.semaphore,
users: existing.users + 1,
}),
);
return existing.semaphore;
}
const semaphore = yield* Semaphore.make(1);
yield* Ref.set(
statusRefreshLocks,
new Map(current).set(objectDir, { semaphore, users: 1 }),
);
return semaphore;
}),
),
(semaphore) => semaphore.withPermits(1)(effect),
(semaphore) =>
statusRefreshLocksGuard.withPermits(1)(
Ref.update(statusRefreshLocks, (current) => {
const existing = current.get(objectDir);
if (!existing || existing.semaphore !== semaphore) {
return current;
}
const next = new Map(current);
if (existing.users === 1) {
next.delete(objectDir);
} else {
next.set(objectDir, {
semaphore,
users: existing.users - 1,
});
}
return next;
}),
),
);
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
cacheKey: StatusRemoteRefreshCacheKey,
) {
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
yield* fetchRemoteForStatus(cacheKey.cwd, cacheKey.remoteName);
return true as const;
});
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
? STATUS_UPSTREAM_REFRESH_INTERVAL
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
timeToLive: statusUpstreamRefreshCacheTimeToLive,
});
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
@@ -967,16 +1058,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusRemoteRefreshCache,
new StatusRemoteRefreshCacheKey({
gitCommonDir,
remoteName: upstream.remoteName,
}),
const objectDir = yield* resolveCanonicalGitObjectDir(cwd);
yield* withStatusRefreshLock(
objectDir,
Cache.get(
statusRemoteRefreshCache,
new StatusRemoteRefreshCacheKey(objectDir, upstream.remoteName, cwd),
),
);
});
const refreshStatusUpstream: GitVcsDriver.GitVcsDriver["Service"]["refreshStatusUpstream"] =
Effect.fn("refreshStatusUpstream")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
@@ -1474,26 +1575,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn(
"statusDetails",
)(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
Effect.ignoreCause({ log: true }),
);
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
return yield* readStatusDetailsLocal(cwd);
});
const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] =
Effect.fn("statusDetailsRemote")(function* (cwd, options) {
if (options?.refreshUpstream !== false) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
Effect.ignoreCause({ log: true }),
);
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
}
return yield* readStatusDetailsRemote(cwd);
});
@@ -2535,6 +2624,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
statusDetails,
statusDetailsLocal,
statusDetailsRemote,
refreshStatusUpstream,
prepareCommitContext,
commit,
pushCurrentBranch,
@@ -1,5 +1,6 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -21,6 +22,7 @@ import type {
} from "@t3tools/contracts";
import { GitManagerError } from "@t3tools/contracts";
import { statusUpstreamRefreshCacheTimeToLive } from "./GitVcsDriverCore.ts";
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -69,6 +71,7 @@ function makeTestLayer(state: {
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
remoteRefreshCalls?: number;
remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
}) {
return VcsStatusBroadcaster.layer.pipe(
@@ -86,6 +89,10 @@ function makeTestLayer(state: {
state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
return state.currentRemoteStatus;
}),
refreshStatusUpstream: () =>
Effect.sync(() => {
state.remoteRefreshCalls = (state.remoteRefreshCalls ?? 0) + 1;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
@@ -125,6 +132,40 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("evicts the least recently used status after reaching cache capacity", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
for (let index = 0; index < VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY; index += 1) {
yield* broadcaster.getStatus({ cwd: `/repo-${index}` });
}
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
yield* broadcaster.getStatus({ cwd: "/repo-0" });
yield* broadcaster.getStatus({ cwd: "/repo-overflow" });
yield* broadcaster.getStatus({ cwd: "/repo-0" });
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
yield* broadcaster.getStatus({ cwd: "/repo-1" });
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -545,6 +586,96 @@ describe("VcsStatusBroadcaster", () => {
);
});
it.effect("publishes stale remote status and backs off when upstream refresh fails", () => {
const state = {
refreshCalls: 0,
remoteStatusCalls: 0,
remoteInvalidationCalls: 0,
remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
};
let firstRefreshDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () =>
Effect.suspend(() => {
state.refreshCalls += 1;
if (state.refreshCalls !== 1) {
return Effect.void;
}
return Effect.fail(
new GitManagerError({
operation: "GitWorkflowService.refreshStatusUpstream",
cwd: "/repo",
detail: "background fetch failed",
}),
).pipe(
Effect.ensuring(
firstRefreshDeferred
? Deferred.succeed(firstRefreshDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
);
}),
remoteStatus: (_input, options) =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
return baseRemoteStatus;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
firstRefreshDeferred = yield* Deferred.make<void>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(firstRefreshDeferred);
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
yield* Effect.yieldNow;
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies VcsStatusStreamEvent);
assert.equal(state.refreshCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 1);
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
yield* TestClock.adjust(Duration.seconds(29));
assert.equal(state.refreshCalls, 1);
yield* TestClock.adjust(Duration.seconds(1));
yield* Effect.yieldNow;
assert.equal(state.refreshCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.remoteInvalidationCalls, 2);
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
});
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -631,6 +762,168 @@ describe("VcsStatusBroadcaster", () => {
});
});
it.effect("evicts the cached status after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const remoteUpdated = yield* Deferred.make<VcsStatusStreamEvent>();
const scope = yield* Scope.make();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(remoteUpdated, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(remoteUpdated);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(scope, Exit.void);
yield* broadcaster.getStatus({ cwd: "/repo" });
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("restarts an interrupted refresh after a subscriber reconnects", () =>
Effect.gen(function* () {
const firstRefreshStarted = yield* Deferred.make<void>();
const secondRefreshStarted = yield* Deferred.make<void>();
const secondRemoteUpdated = yield* Deferred.make<void>();
let refreshLookups = 0;
const refreshCache = yield* Cache.makeWith(
() =>
Effect.gen(function* () {
refreshLookups += 1;
if (refreshLookups === 1) {
yield* Deferred.succeed(firstRefreshStarted, undefined);
return yield* Effect.never;
}
yield* Deferred.succeed(secondRefreshStarted, undefined);
}),
{
capacity: 1,
timeToLive: statusUpstreamRefreshCacheTimeToLive,
},
);
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () => Cache.get(refreshCache, "repo"),
remoteStatus: () => Effect.succeed(baseRemoteStatus),
invalidateRemoteStatus: () => Effect.void,
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
yield* Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const firstScope = yield* Scope.make();
yield* broadcaster
.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
)
.pipe(Stream.runDrain, Effect.forkIn(firstScope));
yield* Deferred.await(firstRefreshStarted).pipe(Effect.timeout("1 second"));
yield* Scope.close(firstScope, Exit.void);
const secondScope = yield* Scope.make();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(secondRemoteUpdated, undefined).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(secondScope));
yield* Deferred.await(secondRefreshStarted).pipe(Effect.timeout("1 second"));
yield* Deferred.await(secondRemoteUpdated).pipe(Effect.timeout("1 second"));
assert.equal(refreshLookups, 2);
yield* Scope.close(secondScope, Exit.void);
}).pipe(Effect.provide(testLayer), TestClock.withLive);
}),
);
it.effect("does not continue remote status work after an upstream refresh is interrupted", () => {
const state = {
remoteStatusCalls: 0,
remoteInvalidationCalls: 0,
};
let refreshStartedDeferred: Deferred.Deferred<void> | null = null;
let refreshInterruptedDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () =>
Effect.gen(function* () {
if (refreshStartedDeferred) {
yield* Deferred.succeed(refreshStartedDeferred, undefined);
}
return yield* Effect.never;
}).pipe(
Effect.onInterrupt(() =>
refreshInterruptedDeferred
? Deferred.succeed(refreshInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return baseRemoteStatus;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
return Effect.gen(function* () {
refreshStartedDeferred = yield* Deferred.make<void>();
refreshInterruptedDeferred = yield* Deferred.make<void>();
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
yield* broadcaster
.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
)
.pipe(Stream.runDrain, Effect.forkIn(scope));
yield* Deferred.await(refreshStartedDeferred);
yield* Scope.close(scope, Exit.void);
yield* Deferred.await(refreshInterruptedDeferred);
assert.equal(state.remoteInvalidationCalls, 0);
assert.equal(state.remoteStatusCalls, 0);
}).pipe(Effect.provide(testLayer));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -667,6 +960,7 @@ describe("VcsStatusBroadcaster", () => {
: Effect.void,
),
),
refreshStatusUpstream: () => Effect.void,
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
+77 -30
View File
@@ -29,6 +29,7 @@ const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
export const VCS_STATUS_CACHE_CAPACITY = 128;
function boundedDiagnosticValue(value: string): string {
return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
@@ -188,13 +189,39 @@ export const make = Effect.gen(function* () {
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const statusCache = new Map<string, CachedVcsStatus>();
const activeRemotePollerCwds = new Set<string>();
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const setCachedStatus = (cwd: string, status: CachedVcsStatus) => {
statusCache.delete(cwd);
statusCache.set(cwd, status);
while (statusCache.size > VCS_STATUS_CACHE_CAPACITY) {
let oldestCwd: string | undefined;
for (const cachedCwd of statusCache.keys()) {
if (!activeRemotePollerCwds.has(cachedCwd)) {
oldestCwd = cachedCwd;
break;
}
}
if (oldestCwd === undefined) {
break;
}
statusCache.delete(oldestCwd);
}
};
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
return yield* Effect.sync(() => {
const cached = statusCache.get(cwd) ?? null;
if (cached) {
setCachedStatus(cwd, cached);
}
return cached;
});
});
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
@@ -203,14 +230,13 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
return previous.local?.fingerprint !== nextLocal.fingerprint;
});
if (options?.publish && shouldPublish) {
@@ -233,14 +259,13 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
return previous.remote?.fingerprint !== nextRemote.fingerprint;
});
if (options?.publish && shouldPublish) {
@@ -271,18 +296,16 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
local: nextLocal,
remote: nextRemote,
});
return [
return (
previous.local?.fingerprint !== nextLocal.fingerprint ||
previous.remote?.fingerprint !== nextRemote.fingerprint,
nextCache,
] as const;
previous.remote?.fingerprint !== nextRemote.fingerprint
);
});
if (options?.publish && shouldPublish) {
@@ -355,11 +378,22 @@ export const make = Effect.gen(function* () {
cwd: string,
options?: { readonly refreshUpstream?: boolean },
) {
const refreshExit =
options?.refreshUpstream === false
? Exit.void
: yield* workflow.refreshStatusUpstream(cwd).pipe(Effect.exit);
if (Exit.isFailure(refreshExit) && Cause.hasInterrupts(refreshExit.cause)) {
return yield* Effect.failCause(refreshExit.cause);
}
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, options);
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream: false });
const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
if (Exit.isFailure(refreshExit)) {
return yield* Effect.failCause(refreshExit.cause);
}
return updated;
});
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
@@ -462,6 +496,7 @@ export const make = Effect.gen(function* () {
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
activeRemotePollerCwds.add(cwd);
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
@@ -498,6 +533,17 @@ export const make = Effect.gen(function* () {
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
if (activePollers.has(cwd)) {
return Effect.succeed([undefined, activePollers] as const);
}
return Effect.sync(() => {
activeRemotePollerCwds.delete(cwd);
statusCache.delete(cwd);
return [undefined, activePollers] as const;
});
});
}
});
@@ -509,15 +555,16 @@ export const make = Effect.gen(function* () {
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const cachedStatus = yield* getCachedStatus(cwd);
const initialRemote = cachedStatus?.remote?.value ?? null;
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
yield* Effect.acquireRelease(
retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
),
() => releaseRemotePoller(cwd),
);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
@@ -528,7 +575,7 @@ export const make = Effect.gen(function* () {
Stream.filter((event) => event.cwd === cwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
);
}),
);
+19 -19
View File
@@ -330,14 +330,14 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.subscribeTerminalMetadata, AuthTerminalOperateScope],
[WS_METHODS.previewOpen, AuthOrchestrationOperateScope],
[WS_METHODS.previewNavigate, AuthOrchestrationOperateScope],
[WS_METHODS.previewResize, AuthOrchestrationOperateScope],
[WS_METHODS.previewRefresh, AuthOrchestrationOperateScope],
[WS_METHODS.previewClose, AuthOrchestrationOperateScope],
[WS_METHODS.previewList, AuthOrchestrationReadScope],
[WS_METHODS.previewReportStatus, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationConnect, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationRespond, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationReportOwner, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationClearOwner, AuthOrchestrationOperateScope],
[WS_METHODS.previewAutomationFocusHost, AuthOrchestrationOperateScope],
[WS_METHODS.subscribePreviewEvents, AuthOrchestrationReadScope],
[WS_METHODS.subscribeDiscoveredLocalServers, AuthOrchestrationReadScope],
[WS_METHODS.subscribeServerConfig, AuthOrchestrationReadScope],
@@ -385,7 +385,10 @@ function toAuthAccessStreamEvent(
}
}
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 +403,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;
@@ -1622,6 +1624,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 +1656,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) =>
@@ -1791,8 +1791,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 +1812,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 +1850,6 @@ export const websocketRpcRouteLayer = Layer.unwrap(
EnvironmentInternalError: HttpServerRespondable.toResponse,
}),
),
),
),
);
}),
);
+1 -1
View File
@@ -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",
+5 -3
View File
@@ -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);
});
});
+2
View File
@@ -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}
/>
</>
);
}
+5 -2
View File
@@ -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}
/>
);
})}
+163 -22
View File
@@ -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);
}
+8 -3
View File
@@ -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);
});
});
+69 -1
View File
@@ -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() },
},
};
}),
@@ -47,6 +47,14 @@ describe("browser target resolver", () => {
).toBe("http://localhost:3000/app");
});
it("preserves localhost server-picker values when the prepared base is 127.0.0.1", async () => {
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173/app?x=1#top"),
).toBe("http://localhost:5173/app?x=1#top");
});
it("normalizes public URLs without treating them as environment ports", async () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "example.com/app")).toBe(
@@ -24,6 +24,11 @@ const isPrivateNetworkHost = (host: string): boolean => {
);
};
const isLocalLoopbackHost = (host: string): boolean => {
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
};
export function resolveBrowserNavigationTarget(
environmentId: EnvironmentId,
target: BrowserNavigationTarget,
@@ -68,6 +73,12 @@ export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl:
const normalizedUrl = normalizePreviewUrl(rawUrl);
const parsed = new URL(normalizedUrl);
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
const environmentUrl = new URL(connection.httpBaseUrl);
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
return normalizedUrl;
}
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
return resolveBrowserNavigationTarget(environmentId, {
kind: "environment-port",
@@ -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 });
});
});
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more