Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex d7849fa702 refactor(connection): preserve persistence failure causes
Co-authored-by: codex <[email protected]>
2026-06-20 18:10:46 -07:00
258 changed files with 4585 additions and 20018 deletions

No files matched your search

@@ -48,9 +48,7 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -58,9 +56,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -78,6 +73,4 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
+14 -36
View File
@@ -100,41 +100,25 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
const envEntries = [
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync(
targetBinaryPath,
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
@@ -302,12 +286,6 @@ function buildMacLauncher(electronBinaryPath) {
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
@@ -1,28 +0,0 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
});
@@ -43,16 +43,7 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -79,11 +70,6 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -113,34 +99,6 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+2 -45
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -115,60 +114,18 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers,
headers: request.headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
const response = await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
+10 -387
View File
@@ -1,5 +1,4 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -19,25 +18,16 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const {
createFromPath,
fromId,
getFocusedWebContents,
mkdir,
showItemInFolder,
webviewSend,
writeFile,
writeImage,
} = vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
@@ -54,7 +44,6 @@ vi.mock("electron", () => ({
},
webContents: {
fromId,
getFocusedWebContents,
},
}));
@@ -92,7 +81,6 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
@@ -109,8 +97,6 @@ const withManager = <A>(
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
@@ -264,197 +250,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -716,178 +511,6 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
+74 -236
View File
@@ -25,7 +25,6 @@ import type {
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import {
type BrowserWindow,
@@ -63,7 +62,6 @@ import {
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -380,7 +378,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
artifactDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
@@ -857,24 +854,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
commandParams?: Record<string, unknown>,
) => Effect.Effect<unknown, PreviewManagerError>;
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
send: SendCommand,
enableRuntime: boolean,
) {
yield* Effect.all(
[
...(enableRuntime ? [send("Runtime.enable")] : []),
send("Input.setIgnoreInputEvents", { ignore: false }),
],
{ concurrency: 2, discard: true },
);
});
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
tabId: string,
wc: Electron.WebContents,
action: string,
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
) {
const sequence = yield* nextCounter(actionSequenceRef);
const startedAt = yield* currentIso;
@@ -915,22 +899,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return result;
},
);
// Cleanup commands must still run after human input invalidates the action's
// control epoch. Otherwise a partially dispatched input can leave Chromium
// with a held key or focus emulation enabled for subsequent actions.
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
function* (method, commandParams) {
return yield* attemptPromise(
{
operation: `${action}.cleanup.${method}`,
tabId,
webContentsId: wc.id,
},
() => wc.debugger.sendCommand(method, commandParams),
);
},
);
return yield* use(send, sendCleanup);
return yield* use(send);
});
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
exit: Exit.Exit<A, PreviewManagerError>,
@@ -1122,62 +1091,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
) {
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
if (wc.isDestroyed()) return;
const zoomFactor = yield* attempt(
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
() => wc.getZoomFactor(),
).pipe(Effect.option);
const computedNavStatus = computeNavStatus(wc);
const canGoBack = wc.navigationHistory.canGoBack();
const canGoForward = wc.navigationHistory.canGoForward();
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
const navStatus =
preserveLoadFailure &&
current.navStatus.kind === "LoadFailed" &&
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const state: PreviewTabState = {
...current,
navStatus,
canGoBack,
canGoForward,
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
yield* update(tabId, {
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
});
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const failed = (
_event: Event,
code: number,
description: string,
validatedUrl: string,
isMainFrame: boolean,
): void => {
if (code === -3 || !isMainFrame) return;
const sync = () => runFork(syncState());
const failed = (_event: Event, code: number, description: string): void => {
if (code === -3) return;
runFork(
update(tabId, {
navStatus: {
kind: "LoadFailed",
url: validatedUrl || wc.getURL(),
url: wc.getURL(),
title: wc.getTitle(),
code,
description,
@@ -1232,8 +1161,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("did-navigate", sync);
wc.off("did-navigate-in-page", sync);
wc.off("page-title-updated", sync);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
@@ -1244,8 +1173,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("did-navigate", sync);
wc.on("did-navigate-in-page", sync);
wc.on("page-title-updated", sync);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
@@ -1351,40 +1280,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
return;
}
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
if (replacedWebContentsId !== null) {
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
yield* Effect.all(
[
detachControlSession(replacedWebContentsId),
detachListeners(replacedWebContentsId),
detachControlSession(tab.webContentsId),
detachListeners(tab.webContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
}
const zoomFactor =
replacedWebContentsId !== null
? yield* attempt(
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
() => {
wc.setZoomFactor(tab.zoomFactor);
return tab.zoomFactor;
},
)
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
wc.getZoomFactor(),
);
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
@@ -1403,7 +1313,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor,
updatedAt: registeredAt,
};
return [
@@ -1421,6 +1330,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
@@ -2032,7 +1946,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationClickInput,
send: SendCommand,
) {
yield* prepareAutomationInput(send, true);
yield* Effect.all(
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
{ concurrency: 2, discard: true },
);
const point = yield* resolveClickPoint(tabId, send, input);
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
tabId,
@@ -2094,7 +2011,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
tabId: string,
send: SendCommand,
input: PreviewAutomationTypeInput,
@@ -2104,15 +2021,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const locatorJson = locator
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
: null;
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
const result = yield* evaluateWithDebugger<
| { ok: true }
| { invalidSelector: true; message: string }
| { notEditable: true }
| { notFound: true }
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
>(
tabId,
send,
@@ -2120,54 +2030,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try {
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
if (!element) return { notFound: true };
const textControl =
element instanceof HTMLTextAreaElement ||
(element instanceof HTMLInputElement &&
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
const editable = textControl || element.isContentEditable;
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
element.focus();
if (document.activeElement !== element) return { notEditable: true };
const clear = ${input.clear ?? false};
if (clear) {
if (textControl) {
element.select();
} else {
const range = document.createRange();
range.selectNodeContents(element);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
if (${input.clear ?? false}) {
if ("value" in element) element.value = "";
else if (element.isContentEditable) element.textContent = "";
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
}
const text = ${textJson};
let inserted = true;
if (text.length > 0) {
inserted = document.execCommand("insertText", false, text);
} else if (clear) {
document.execCommand("delete", false);
const cleared = textControl
? element.value.length === 0
: (element.textContent ?? "").length === 0;
if (!cleared) {
if (textControl) {
const prototype = element instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
if (valueSetter) valueSetter.call(element, "");
else element.value = "";
} else {
element.replaceChildren();
}
element.dispatchEvent(new InputEvent("input", {
bubbles: true,
inputType: "deleteContentBackward",
}));
}
}
if (!inserted) return { notEditable: true };
element.dispatchEvent(new Event("change", { bubbles: true }));
return { ok: true };
} catch (error) {
return { invalidSelector: true, message: String(error) };
@@ -2191,12 +2059,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
...automationSelectorDiagnostics(input),
});
}
if ("notEditable" in result) {
return yield* new PreviewAutomationTargetNotEditableError({
tabId,
...automationSelectorDiagnostics(input),
});
}
});
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
@@ -2204,10 +2066,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationTypeInput,
send: SendCommand,
) {
// CDP Input.insertText silently drops text until Electron has activated a hidden
// guest WebContents with a pointer event. Editing in the page runtime keeps
// background automation deterministic without stealing foreground app focus.
yield* typeIntoAutomationTarget(tabId, send, input);
yield* send("Runtime.enable");
yield* focusAutomationTarget(tabId, send, input);
yield* send("Input.insertText", { text: input.text });
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
yield* evaluateWithDebugger(
tabId,
send,
`(() => {
const element = document.activeElement;
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
element?.dispatchEvent(new Event("change", { bubbles: true }));
})()`,
false,
);
});
const automationType = Effect.fn("PreviewManager.automationType")(function* (
@@ -2222,54 +2097,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
tabId: string,
wc: Electron.WebContents,
input: PreviewAutomationPressInput,
send: SendCommand,
sendCleanup: SendCommand,
) {
yield* prepareAutomationInput(send, false);
const keySequence = makePreviewAutomationKeySequence(input, {
isMac: hostPlatform === "darwin",
});
const previouslyFocused = yield* attempt(
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
() => webContents.getFocusedWebContents(),
);
let keyDownAttempted = false;
const releaseInput = Effect.gen(function* () {
if (keyDownAttempted) {
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
Effect.ignore,
);
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
yield* attempt(
{
operation: "automationPress.restoreFocusedWebContents",
tabId,
webContentsId: previouslyFocused.id,
},
() => previouslyFocused.focus(),
).pipe(Effect.ignore);
}
});
// Focus the guest WebContents itself, not its containing BrowserWindow. This
// activates native keyboard behavior for hidden/background previews without
// changing which thread is mounted in the UI. Restore the previous renderer
// after dispatch so automation never leaves the app's input focus behind.
yield* Effect.gen(function* () {
yield* attempt(
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
() => wc.focus(),
);
yield* send("Page.bringToFront");
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
yield* expectAgentInput(tabId, keySequence.signal);
keyDownAttempted = true;
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
}).pipe(Effect.ensuring(releaseInput));
}, 0);
const key = input.key;
const text = key.length === 1 ? key : undefined;
const params = {
key,
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
};
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
});
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
@@ -2277,8 +2130,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationPressInput,
) {
const wc = yield* requireWebContents(tabId);
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
performAutomationPress(tabId, wc, input, send, sendCleanup),
yield* withControlSession(tabId, wc, "press", (send) =>
performAutomationPress(tabId, input, send),
);
});
@@ -2676,20 +2529,6 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
}
}
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
"PreviewAutomationTargetNotEditableError",
{
tabId: Schema.String,
selectorKind: PreviewAutomationSelectorKind,
selectorLength: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
}
}
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
"PreviewAutomationCoordinatesOutsideViewportError",
{
@@ -2792,7 +2631,6 @@ export const PreviewManagerError = Schema.Union([
PreviewAutomationDebuggerAttachedError,
PreviewAutomationEvaluationError,
PreviewAutomationTargetNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationCoordinatesOutsideViewportError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationResultTooLargeError,
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
-203
View File
@@ -1,203 +0,0 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -28,7 +29,6 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -4,7 +4,6 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -48,14 +47,12 @@ function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
setWindowOpenHandler: vi.fn(),
@@ -82,7 +79,6 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -241,73 +237,6 @@ describe("DesktopWindow", () => {
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
if (!didFailLoad || !didFinishLoad) {
return yield* Effect.die("renderer load listeners were not registered");
}
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
yield* TestClock.adjust(100);
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
["t3code-dev://app/"],
["t3code-dev://app/"],
]);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
didFinishLoad();
yield* TestClock.adjust(250);
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it("retries only transient failures for the development renderer", () => {
assert.isTrue(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -3,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "https://example.com/",
}),
);
});
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+3 -95
View File
@@ -1,6 +1,5 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -23,16 +22,6 @@ const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
-102, // ERR_CONNECTION_REFUSED
-105, // ERR_NAME_NOT_RESOLVED
-106, // ERR_INTERNET_DISCONNECTED
-118, // ERR_CONNECTION_TIMED_OUT
]);
type WindowTitleBarOptions = Pick<
Electron.BrowserWindowConstructorOptions,
@@ -97,22 +86,6 @@ export function isSameOriginRendererNavigation(input: {
}
}
export function isRetryableDevelopmentRendererLoadFailure(input: {
readonly applicationUrl: string;
readonly errorCode: number;
readonly isMainFrame: boolean;
readonly validatedUrl: string;
}): boolean {
return (
input.isMainFrame &&
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
isSameOriginRendererNavigation({
applicationUrl: input.applicationUrl,
navigationUrl: input.validatedUrl,
})
);
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -179,7 +152,6 @@ export const make = Effect.gen(function* () {
const previewManager = yield* PreviewManager.PreviewManager;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
@@ -305,61 +277,7 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
}
const retryFiber = developmentLoadRetryFiber;
developmentLoadRetryFiber = undefined;
runFork(Fiber.interrupt(retryFiber));
};
const loadApplication = () => {
if (window.isDestroyed()) {
return;
}
void window.loadURL(applicationUrl).catch(() => undefined);
};
const scheduleDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
return undefined;
}
const retryIndex = Math.min(
developmentLoadRetryIndex,
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
);
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
developmentLoadRetryIndex += 1;
developmentLoadRetryFiber = runFork(
Effect.sleep(retryInMs).pipe(
Effect.andThen(
Effect.sync(() => {
developmentLoadRetryFiber = undefined;
if (!window.isDestroyed()) {
loadApplication();
}
}),
),
),
);
return retryInMs;
};
window.webContents.on("did-finish-load", () => {
if (
environment.isDevelopment &&
!isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: window.webContents.getURL(),
})
) {
return;
}
clearDevelopmentLoadRetry();
developmentLoadRetryIndex = 0;
window.setTitle(environment.displayName);
});
window.webContents.on(
@@ -368,22 +286,11 @@ export const make = Effect.gen(function* () {
if (!isMainFrame) {
return;
}
const retryInMs =
environment.isDevelopment &&
isRetryableDevelopmentRendererLoadFailure({
applicationUrl,
errorCode,
isMainFrame,
validatedUrl: validatedURL,
})
? scheduleDevelopmentLoadRetry()
: undefined;
void runPromise(
logWindowWarning("main window failed to load", {
errorCode,
errorDescription,
url: validatedURL,
...(retryInMs === undefined ? {} : { retryInMs }),
}),
);
},
@@ -405,13 +312,14 @@ export const make = Effect.gen(function* () {
void runPromise(electronWindow.reveal(window));
});
loadApplication();
if (environment.isDevelopment) {
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
clearDevelopmentLoadRetry();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^7.0.3"
"astro": "^6.0.4"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
+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.2.0",
"@legendapp/list": "3.0.0-beta.44",
"@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.7",
"react-native-keyboard-controller": "1.21.6",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "0.35.9",
"react-native-nitro-modules": "^0.35.4",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
+2 -1
View File
@@ -18,7 +18,8 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
+58 -49
View File
@@ -58,23 +58,8 @@ const LegacyStoredShellSnapshot = Schema.Struct({
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
});
}
function shellPersistenceError(
operation:
| "load-shell"
| "save-shell"
| "load-thread"
| "save-thread"
| "remove-thread"
| "clear-environment",
cause: unknown,
) {
return new ConnectionPersistenceError({
operation,
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
detail: `Could not ${operation} the local connection catalog.`,
cause,
});
}
@@ -100,7 +85,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
},
);
@@ -117,16 +102,6 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
);
});
function targetPersistenceError(
operation: "list-targets" | "register-connection" | "remove-connection",
error: ConnectionTransientError,
) {
return new ConnectionPersistenceError({
operation,
message: error.message,
});
}
const secureCatalogStorage: SecureCatalogStorage = {
getItem: (key) =>
Effect.tryPromise({
@@ -163,7 +138,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
directory.create({ idempotent: true, intermediates: true });
return new File(directory, shellSnapshotFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
});
});
@@ -184,18 +159,29 @@ export const connectionStorageLayer = Layer.effectContext(
const targetStore = ConnectionTargetStore.of({
list: catalog.read.pipe(
Effect.map((document) => document.targets),
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
),
),
});
const registrationStore = ConnectionRegistrationStore.of({
register: (registration) =>
catalog
.update((document) => registerConnectionInCatalog(document, registration))
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
.pipe(
Effect.mapError(
(cause) =>
new ConnectionPersistenceError({ operation: "register-connection", cause }),
),
),
remove: (target) =>
catalog
.update((document) => removeConnectionFromCatalog(document, target))
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
.pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
),
),
});
const profileStore = ProfileStore.make({
get: (connectionId) =>
@@ -283,15 +269,19 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -303,15 +293,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
),
);
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
@@ -326,7 +320,11 @@ export const connectionStorageLayer = Layer.effectContext(
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -334,7 +332,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-shell", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
});
}),
loadThread: (environmentId, threadId) =>
@@ -345,15 +343,19 @@ export const connectionStorageLayer = Layer.effectContext(
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -368,7 +370,11 @@ export const connectionStorageLayer = Layer.effectContext(
threadId: thread.id,
thread,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
).pipe(
Effect.mapError(
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -376,7 +382,7 @@ export const connectionStorageLayer = Layer.effectContext(
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-thread", cause),
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
});
}),
removeThread: (environmentId, threadId) =>
@@ -389,7 +395,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.mapError((cause) =>
cause._tag === "ConnectionPersistenceError"
? cause
: shellPersistenceError("remove-thread", cause),
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
),
),
clear: (environmentId) =>
@@ -398,14 +404,16 @@ export const connectionStorageLayer = Layer.effectContext(
if (file.exists) {
yield* Effect.try({
try: () => file.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
@@ -415,7 +423,8 @@ export const connectionStorageLayer = Layer.effectContext(
if (threadDirectory.exists) {
yield* Effect.try({
try: () => threadDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
catch: (cause) =>
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
});
}
}),
@@ -835,7 +835,7 @@ describe("mobile cloud link environment client", () => {
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(connectRequestBody)).toMatchObject({
deviceId: "device-1",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
clientKeyThumbprint: "client-proof-key-thumbprint",
});
expect(createProofMock).toHaveBeenCalledWith({
method: "POST",
@@ -484,7 +484,6 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
scopes: [RelayEnvironmentConnectScope],
environmentId: input.environmentId,
deviceId,
client: authClientMetadata(),
})
.pipe(
Effect.mapError(
@@ -498,30 +497,21 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
message: "Relay returned credentials for a different environment.",
});
}
if (!("credential" in connect)) {
return yield* new CloudEnvironmentLinkError({
message:
connect.approvalStatus === "rejected"
? "This device was rejected by the environment. Approve it in the environment settings to connect."
: "Waiting for this device to be approved in the environment settings.",
});
}
const authorizedConnect = connect;
if (input.expectedEnvironment) {
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.expectedEnvironment,
connect: authorizedConnect,
connect,
});
}
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
),
);
if (descriptor.environmentId !== authorizedConnect.environmentId) {
if (descriptor.environmentId !== connect.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Connected endpoint descriptor does not match the selected environment.",
});
@@ -530,12 +520,12 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
url: new URL("/oauth/token", authorizedConnect.endpoint.httpBaseUrl).toString(),
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
})
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
const bootstrap = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
credential: authorizedConnect.credential,
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
dpopProof: bootstrapDpop,
clientMetadata: authClientMetadata(),
}).pipe(
@@ -543,16 +533,16 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
),
);
const pairingUrl = new URL(authorizedConnect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", authorizedConnect.credential]]).toString();
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
displayUrl: authorizedConnect.endpoint.httpBaseUrl,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
wsBaseUrl: authorizedConnect.endpoint.wsBaseUrl,
displayUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
wsBaseUrl: connect.endpoint.wsBaseUrl,
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
@@ -30,9 +30,7 @@ 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";
@@ -65,7 +63,6 @@ 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)";
@@ -81,12 +78,6 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
) {
return;
}
setProject(directProject);
return;
}
@@ -114,16 +105,10 @@ 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.loadBranches, selectedProject]);
}, [flow, selectedProject]);
useEffect(() => {
if (!selectedProject) {
@@ -307,7 +292,11 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
// 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);
}
function handleEnvironmentMenuAction(event: string) {
@@ -377,42 +366,27 @@ 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 (
!modelSelection ||
initialMessageText.length === 0 ||
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
flow.submitting ||
(workspaceMode === "worktree" && !selectedBranchName)
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
const result = await createProjectThread({
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
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,
});
flow.setSubmitting(false);
@@ -1,7 +1,6 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
@@ -92,7 +91,7 @@ export interface ThreadComposerProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onSendMessage: () => Promise<void>;
readonly onUpdateModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
@@ -448,7 +447,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const { onChangeDraftMessage, onUpdateInteractionMode, draftMessage, onSendMessage } = props;
const handleSend = useCallback(() => {
void onSendMessage();
void onSendMessage().then(() => {
inputRef.current?.blur();
});
}, [onSendMessage]);
const handleCommandSelect = useCallback(
(item: ComposerCommandItem) => {
@@ -1,10 +1,7 @@
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,
@@ -16,8 +13,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, useLayoutEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent } from "react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { View, type GestureResponderEvent, type LayoutChangeEvent } 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";
@@ -28,7 +25,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 { scopedThreadKey } from "../../lib/scopedEntities";
import { resolveThreadFeedBottomInset } from "../../lib/threadFeedLayout";
import type {
PendingApproval,
PendingUserInput,
@@ -76,7 +73,7 @@ export interface ThreadDetailScreenProps {
readonly onNativePasteImages: (uris: ReadonlyArray<string>) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
readonly onSendMessage: () => Promise<MessageId | null>;
readonly onSendMessage: () => Promise<void>;
readonly onReconnectEnvironment: () => void;
readonly onUpdateThreadModelSelection: (modelSelection: ModelSelection) => void;
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
@@ -209,33 +206,25 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const insets = useSafeAreaInsets();
const headerHeight = useHeaderHeight();
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
const composerOverlayRef = useRef<View>(null);
const listRef = useRef<LegendListRef>(null);
const composerRef = useRef<ComposerEditorHandle>(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 + 8;
const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
listRef,
composerOverlayRef,
estimatedOverlayHeight,
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight;
const [measuredOverlayHeight, setMeasuredOverlayHeight] = useState(0);
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)
@@ -265,67 +254,15 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
[completeDrawerGesture, isSplitLayout],
);
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 handleOverlayLayout = useCallback((event: LayoutChangeEvent) => {
const nextHeight = Math.ceil(event.nativeEvent.layout.height);
setMeasuredOverlayHeight((current) =>
Math.abs(current - nextHeight) > 1 ? nextHeight : current,
);
}, []);
const collapseComposer = useCallback(() => {
composerEditorRef.current?.blur();
composerRef.current?.blur();
}, []);
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
@@ -378,13 +315,10 @@ 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={estimatedOverlayHeight}
contentBottomInset={feedBottomInset}
layoutVariant={layoutVariant}
composerExpanded={composerExpanded}
skills={selectedProviderSkills}
/>
</View>
@@ -398,7 +332,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
<View onLayout={handleOverlayLayout}>
{props.activeWorkStartedAt ? (
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
@@ -427,7 +361,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
<ThreadComposer
editorRef={composerEditorRef}
editorRef={composerRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
@@ -446,7 +380,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onSendMessage={props.onSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
+172 -164
View File
@@ -1,20 +1,10 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { KeyboardAvoidingLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import type { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useRouter } from "expo-router";
import {
memo,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
Markdown,
type CustomRenderers,
@@ -25,6 +15,8 @@ import {
ActivityIndicator,
Image,
Linking,
type NativeScrollEvent,
type NativeSyntheticEvent,
Pressable,
ScrollView,
StyleSheet,
@@ -37,7 +29,6 @@ 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 {
@@ -73,11 +64,14 @@ import {
type ThreadFeedEntry,
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import { isThreadFeedNearEnd } from "../../lib/threadFeedLayout";
import { relativeTime } from "../../lib/time";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
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",
@@ -99,13 +93,10 @@ 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>;
}
@@ -655,6 +646,7 @@ function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
readonly unsettledTurnId: TurnId | null;
@@ -697,18 +689,6 @@ function renderFeedEntry(
);
}
if (entry.type === "work-toggle") {
return (
<ThreadWorkGroupToggle
expanded={entry.expanded}
hiddenCount={entry.hiddenCount}
iconSubtleColor={iconSubtleColor}
onlyToolActivities={entry.onlyToolActivities}
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
/>
);
}
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
@@ -832,13 +812,39 @@ function renderFeedEntry(
);
}
if (entry.type === "queued-message") {
return (
<View className="mb-5 items-end">
<View
className="max-w-[85%] gap-2 rounded-[22px] rounded-br-[6px] px-3.5 py-2.5 opacity-60"
style={{ backgroundColor: userBubbleColor }}
>
<Text className="font-sans text-base leading-[22px] text-white">
{entry.queuedMessage.text}
</Text>
{entry.queuedMessage.attachments.length > 0 ? (
<Text className="font-t3-medium text-xs text-white/75">
{entry.queuedMessage.attachments.length} image
{entry.queuedMessage.attachments.length === 1 ? "" : "s"} attached
</Text>
) : null}
</View>
<Text className="mt-1.5 px-1 text-right font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
{entry.sending ? "dispatching" : `${relativeTime(entry.createdAt)} • pending`}
</Text>
</View>
);
}
return (
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={props.onToggleWorkRow}
/>
);
@@ -1116,13 +1122,17 @@ 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 disclosureAnchorKeyRef = useRef<string | 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 [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1183,6 +1193,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1191,6 +1202,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1198,34 +1210,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
userBubbleColor,
],
);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
if (expanded) {
ids.add(groupId);
}
}
return ids;
}, [expandedWorkGroups]);
const presentedFeed = useMemo(
() =>
deriveThreadFeedPresentation(
props.feed,
props.latestTurn,
expandedTurnIds,
expandedWorkGroupIds,
),
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(
presentedFeed,
props.anchorMessageId,
(entry) => (entry.type === "message" ? entry.id : null),
{ anchorOffset: topContentInset + CHAT_LIST_ANCHOR_OFFSET },
),
[presentedFeed, props.anchorMessageId, topContentInset],
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
[expandedTurnIds, props.feed, props.latestTurn],
);
const terminalAssistantMessageIds = useMemo(() => {
const terminalIdsByTurn = new Map<TurnId, string>();
@@ -1242,6 +1229,54 @@ 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;
@@ -1273,6 +1308,9 @@ 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);
}
@@ -1282,39 +1320,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
};
}, []);
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
if (foldSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(foldSettleSecondFrameRef.current);
}
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
disclosureAnchorKeyRef.current = null;
setDisclosureToggleSettling(false);
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
});
}, []);
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
}, []);
const maintainVisibleContentPosition = useMemo(
() => ({
data: true,
size: true,
shouldRestorePosition: shouldRestoreVisibleContentPosition,
}),
[shouldRestoreVisibleContentPosition],
);
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
copyTextWithHaptic(value, {
target: "thread-work-row",
@@ -1332,49 +1337,51 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, 1200);
}, []);
const onToggleWorkGroup = useCallback(
(groupId: string) => {
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
setInteractionState((current) => ({
...current,
expandedWorkGroups: {
...current.expandedWorkGroups,
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
},
}));
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleWorkGroup = useCallback((groupId: string) => {
setInteractionState((current) => ({
...current,
expandedWorkGroups: {
...current.expandedWorkGroups,
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
},
}));
}, []);
const onToggleWorkRow = useCallback(
(rowId: string) => {
suspendEndScrollMaintenanceForDisclosure(rowId);
setInteractionState((current) => ({
...current,
expandedWorkRows: {
...current.expandedWorkRows,
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
},
}));
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleWorkRow = useCallback((rowId: string) => {
setInteractionState((current) => ({
...current,
expandedWorkRows: {
...current.expandedWorkRows,
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
},
}));
}, []);
const onToggleTurnFold = useCallback(
(turnId: TurnId) => {
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
setInteractionState((current) => {
const next = new Set(current.expandedTurnIds);
if (next.has(turnId)) {
next.delete(turnId);
} else {
next.add(turnId);
}
return { ...current, expandedTurnIds: next };
const onToggleTurnFold = useCallback((turnId: TurnId) => {
suppressAutoFollowRef.current = true;
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
if (foldSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(foldSettleSecondFrameRef.current);
}
setInteractionState((current) => {
const next = new Set(current.expandedTurnIds);
if (next.has(turnId)) {
next.delete(turnId);
} else {
next.add(turnId);
}
return { ...current, expandedTurnIds: next };
});
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
suppressAutoFollowRef.current = false;
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
},
[suspendEndScrollMaintenanceForDisclosure],
);
});
}, []);
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
@@ -1385,6 +1392,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
renderFeedEntry(info, {
environmentId: props.environmentId,
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1404,6 +1412,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1449,60 +1458,59 @@ 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 }}>
<KeyboardAwareLegendList
ref={props.listRef}
<KeyboardAvoidingLegendList
ref={listRef}
key={props.threadId}
style={{ flex: 1 }}
automaticallyAdjustsScrollIndicatorInsets={false}
contentInset={{ top: 0, bottom: 0 }}
scrollIndicatorInsets={{ top: topContentInset, bottom: 0 }}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
disclosureToggleSettling
? false
: {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}
}
maintainVisibleContentPosition={maintainVisibleContentPosition}
alignItemsAtEnd
maintainScrollAtEnd={{
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
}}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
keyExtractor={(entry) => entry.id}
keyExtractor={(entry) => `${entry.type}:${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,7 +1,13 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} 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";
@@ -73,6 +79,18 @@ 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<{
@@ -87,18 +105,6 @@ 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"));
@@ -151,6 +157,51 @@ 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 ||
@@ -384,7 +435,7 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
selectedThread={selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
@@ -415,9 +466,9 @@ export function ThreadRouteScreen() {
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import React, { useCallback, useMemo, useRef, useState } from "react";
import type {
EnvironmentId,
@@ -23,7 +23,6 @@ import {
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
@@ -159,15 +158,34 @@ 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);
}, []);
@@ -229,33 +247,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,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
selectedProject?.defaultModelSelection ?? null,
),
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
selectedProjectDraft.modelSelection,
],
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
);
const selectedModel =
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) ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
? `${selectedModel.instanceId}:${selectedModel.model}`
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -264,31 +282,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
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 selectedProviderSkills =
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
const setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedProjectDraftKey) {
if (!selectedModel || !selectedModelIdentity) {
return;
}
const nextSelection: ModelSelection = options
@@ -297,11 +297,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: nextSelection,
});
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
},
[selectedModel, selectedProjectDraftKey],
[selectedModel, selectedModelIdentity],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
@@ -380,85 +381,62 @@ 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) => {
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
},
});
setSelectedBranchName(branch.name);
setSelectedWorktreePath(
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
);
},
[selectedProject, selectedProjectDraftKey, workspaceMode],
[selectedProject],
);
const refreshBranches = branchState.refresh;
const loadBranches = useCallback(async () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
}, [refreshBranches, selectedProject]);
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
return;
}
const preferredBranch =
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
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);
}
}
}, [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],
);
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -535,11 +513,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setProject,
selectBranch,
selectEnvironment,
setInteractionMode,
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setWorkspaceMode,
submitting,
workspaceMode,
appendAttachments,
@@ -6,6 +6,7 @@ import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
@@ -71,9 +72,11 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
}) {
const colorScheme = useColorScheme();
@@ -86,10 +89,14 @@ export function ThreadWorkLog(props: {
return null;
}
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows =
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
return (
<View className="-mx-1 mb-1 px-1 py-0">
<View className="-mx-1 mb-3 px-1 py-0.5">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
work log
@@ -97,7 +104,7 @@ export function ThreadWorkLog(props: {
) : null}
<View className="gap-px">
{rows.map((row) => {
{visibleRows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
@@ -125,13 +132,13 @@ export function ThreadWorkLog(props: {
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="rounded-md px-0.5 py-0"
className="rounded-md px-0.5 py-0.5"
>
<View className="min-h-8 flex-row items-center gap-1.5">
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={13}
size={14}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
@@ -139,7 +146,7 @@ export function ThreadWorkLog(props: {
</View>
<Text
className="min-w-0 flex-1 text-xs leading-4 text-foreground"
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
numberOfLines={1}
>
<Text
@@ -192,7 +199,7 @@ export function ThreadWorkLog(props: {
</Pressable>
{expanded && row.fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
@@ -214,59 +221,41 @@ export function ThreadWorkLog(props: {
);
})}
</View>
</View>
);
}
export function ThreadWorkGroupToggle(props: {
readonly expanded: boolean;
readonly hiddenCount: number;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onlyToolActivities: boolean;
readonly onToggle: () => void;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const noun = props.onlyToolActivities
? props.hiddenCount === 1
? "tool call"
: "tool calls"
: props.hiddenCount === 1
? "log entry"
: "log entries";
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
const expandedLabel = props.onlyToolActivities
? "Show fewer tool calls"
: "Show fewer log entries";
return (
<View className="-mx-1 mb-1 px-1 py-0">
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
hitSlop={4}
onPress={() => {
void Haptics.selectionAsync();
props.onToggle();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
>
<View className="h-[18px] w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={12}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
</Text>
</Pressable>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? "Show fewer tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
}
hitSlop={4}
onPress={() => {
triggerDisclosureFeedback();
props.onToggleGroup();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
>
<View className="h-5 w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={13}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? "Show fewer tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
</Text>
</Pressable>
) : null}
</View>
);
}
@@ -1,11 +0,0 @@
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,
});
+7 -66
View File
@@ -11,12 +11,7 @@ import {
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import {
buildThreadFeed,
deriveThreadFeedPresentation,
type ThreadFeedActivity,
type ThreadFeedEntry,
} from "./threadActivity";
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
@@ -91,7 +86,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
expect(feed).toMatchObject([
{
type: "activity-group",
@@ -149,7 +144,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
const group = feed[0];
expect(group).toMatchObject({
@@ -214,7 +209,7 @@ describe("buildThreadFeed", () => {
],
});
const group = buildThreadFeed(thread)[0];
const group = buildThreadFeed(thread, [], null)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
@@ -276,7 +271,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
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({
@@ -364,7 +359,7 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
turnId: firstTurnId,
@@ -404,65 +399,11 @@ describe("buildThreadFeed", () => {
],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(thread, [], null);
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
expect(feed[0]).toMatchObject({
type: "activity-group",
activities: [{ status: "failure" }],
});
});
it("models work-log overflow as list rows", () => {
const activity = (
id: string,
createdAt: string,
status: ThreadFeedActivity["status"] = "success",
): ThreadFeedActivity => ({
id,
createdAt,
turnId: null,
summary: `Tool ${id}`,
detail: null,
fullDetail: null,
copyText: id,
icon: "command",
toolLike: true,
status,
});
const feed: ThreadFeedEntry[] = [
{
type: "activity-group",
id: "work-group-1",
createdAt: "2026-04-01T00:00:01.000Z",
turnId: null,
activities: [
activity("activity-1", "2026-04-01T00:00:01.000Z"),
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
activity("activity-2", "2026-04-01T00:00:03.000Z"),
activity("activity-3", "2026-04-01T00:00:04.000Z"),
],
},
];
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
expect(collapsed[1]).toMatchObject({
type: "work-toggle",
groupId: "work-group-1",
hiddenCount: 2,
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
expect(expanded.map((entry) => entry.id)).toEqual([
"activity-1",
"activity-2",
"activity-3",
"work-toggle:work-group-1",
]);
expect(expanded.at(-1)).toMatchObject({
type: "work-toggle",
expanded: true,
});
});
});
+21 -68
View File
@@ -1,5 +1,6 @@
import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
import type {
MessageId,
OrchestrationLatestTurn,
OrchestrationThread,
OrchestrationThreadActivity,
@@ -9,6 +10,7 @@ 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";
@@ -55,8 +57,6 @@ export interface ThreadFeedActivity {
readonly status: "success" | "failure" | "neutral" | null;
}
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
interface WorkLogEntry {
@@ -88,6 +88,13 @@ 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;
@@ -97,7 +104,7 @@ type RawThreadFeedEntry =
};
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" }>
| Extract<RawThreadFeedEntry, { type: "message" | "queued-message" }>
| {
readonly type: "activity-group";
readonly id: string;
@@ -105,16 +112,6 @@ export type ThreadFeedEntry =
readonly turnId: TurnId | null;
readonly activities: ReadonlyArray<ThreadFeedActivity>;
}
| {
readonly type: "work-toggle";
readonly id: string;
readonly createdAt: string;
readonly turnId: TurnId | null;
readonly groupId: string;
readonly hiddenCount: number;
readonly expanded: boolean;
readonly onlyToolActivities: boolean;
}
| {
readonly type: "turn-fold";
readonly id: string;
@@ -1104,11 +1101,8 @@ export function deriveThreadFeedPresentation(
feed: ReadonlyArray<ThreadFeedEntry>,
latestTurn: ThreadFeedLatestTurn | null,
expandedTurnIds: ReadonlySet<TurnId>,
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
): ThreadFeedEntry[] {
const sourceFeed = feed.filter(
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
);
const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorId.values()) {
@@ -1133,62 +1127,12 @@ export function deriveThreadFeedPresentation(
});
}
if (!collapsedEntryIds.has(entry.id)) {
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
result.push(entry);
}
}
return result;
}
function appendPresentedFeedEntry(
result: ThreadFeedEntry[],
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
expandedWorkGroupIds: ReadonlySet<string>,
): void {
if (entry.type !== "activity-group") {
result.push(entry);
return;
}
const activities = entry.activities.filter(
(activity) => !(activity.toolLike && activity.status === "neutral"),
);
if (activities.length === 0) {
return;
}
if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
result.push({
...entry,
activities,
});
return;
}
const groupId = entry.id;
const expanded = expandedWorkGroupIds.has(groupId);
const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
for (const activity of visibleActivities) {
result.push({
type: "activity-group",
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
activities: [activity],
});
}
result.push({
type: "work-toggle",
id: `work-toggle:${groupId}`,
createdAt: entry.createdAt,
turnId: entry.turnId,
groupId,
hiddenCount,
expanded,
onlyToolActivities: activities.every((activity) => activity.toolLike),
});
}
export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
@@ -1311,6 +1255,8 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
thread: OrchestrationThread,
queuedMessages: ReadonlyArray<QueuedThreadMessage>,
dispatchingQueuedMessageId: MessageId | null,
options?: {
readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
},
@@ -1327,6 +1273,13 @@ 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) {
@@ -0,0 +1,32 @@
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
@@ -0,0 +1,22 @@
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;
}
+13 -65
View File
@@ -1,38 +1,32 @@
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
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 { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } 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 = 2;
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
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.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
schemaVersion: Schema.Literal(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,
});
@@ -46,37 +40,9 @@ 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,
@@ -153,21 +119,3 @@ 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";
}
+1 -78
View File
@@ -1,21 +1,11 @@
import { describe, expect, it } from "@effect/vitest";
import {
CommandId,
EnvironmentId,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
@@ -76,54 +66,6 @@ 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,
@@ -329,23 +271,4 @@ 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,136 +1,14 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
removeComposerDraftsForEnvironment,
} from "./use-composer-drafts";
import { type ComposerDraft, 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");
@@ -139,15 +17,12 @@ 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,
});
});
});
+22 -124
View File
@@ -1,18 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import {
ModelSelection as ModelSelectionSchema,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import type { EnvironmentId } 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";
@@ -38,47 +29,13 @@ 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;
}
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
}
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: [],
@@ -97,32 +54,13 @@ 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 &&
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)),
);
return draft.text.length === 0 && draft.attachments.length === 0;
}
async function getComposerDraftsFile() {
@@ -142,7 +80,20 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "read";
const raw = await file.text();
operation = "decode";
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
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)
);
}),
);
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
@@ -165,10 +116,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document = {
const document: PersistedComposerDrafts = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
} as const;
};
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
@@ -331,55 +282,6 @@ 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]) {
@@ -396,12 +298,8 @@ 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) && !draftKey.startsWith(newTaskPrefix),
),
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
);
}
@@ -1,15 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
@@ -26,13 +18,11 @@ import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
clearComposerDraftContent,
clearComposerDraft,
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -40,6 +30,7 @@ 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;
@@ -76,6 +67,7 @@ export function useThreadComposerState() {
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const composerDrafts = useAtomValue(composerDraftsAtom);
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
useEffect(() => {
@@ -89,19 +81,23 @@ export function useThreadComposerState() {
() => (selectedThreadKey ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []) : []),
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
() =>
selectedThreadDetail
? buildThreadFeed(
selectedThreadDetail,
selectedThreadQueuedMessages,
dispatchingQueuedMessageId,
)
: [],
[dispatchingQueuedMessageId, selectedThreadDetail, selectedThreadQueuedMessages],
);
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;
@@ -115,6 +111,7 @@ export function useThreadComposerState() {
};
}, [selectedThreadDetail, selectedThreadShell]);
const queuedSendStartedAt = selectedThreadQueuedMessages[0]?.createdAt ?? null;
const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
@@ -124,52 +121,51 @@ export function useThreadComposerState() {
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
null,
queuedSendStartedAt,
);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
}, [
queuedSendStartedAt,
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 null;
return;
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
const draft = composerDrafts[threadKey];
const text = (draft?.text ?? "").trim();
const attachments = draft?.attachments ?? [];
if (text.length === 0 && attachments.length === 0) {
return null;
return;
}
const metadata = makeQueuedMessageMetadata();
const messageId = MessageId.make(metadata.messageId);
try {
await enqueueThreadOutboxMessage({
environmentId: selectedThreadShell.environmentId,
threadId: selectedThreadShell.id,
messageId,
messageId: MessageId.make(metadata.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,
});
clearComposerDraftContent(threadKey);
return messageId;
clearComposerDraft(threadKey);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
return null;
}
}, [selectedThreadDetail, selectedThreadShell]);
}, [composerDrafts, selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -259,45 +255,12 @@ 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,
@@ -305,8 +268,5 @@ export function useThreadComposerState() {
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,
onUpdateRuntimeMode,
onUpdateInteractionMode,
};
}
+33 -116
View File
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { CommandId, type MessageId } from "@t3tools/contracts";
import { 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";
@@ -11,13 +10,10 @@ import { appAtomRegistry } from "./atom-registry";
import { useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
@@ -48,21 +44,8 @@ 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();
@@ -85,98 +68,6 @@ 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: {
@@ -188,15 +79,41 @@ export function useThreadOutboxDrain(): void {
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
return completeDelivery(deliveryResult);
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;
}
},
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
[startTurn],
);
useEffect(() => {
+13 -260
View File
@@ -19,23 +19,6 @@ const emitInterleavedAssistantToolCalls =
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
const hangLoadSessionAfterReplay = process.env.T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY === "1";
const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
const emitStaleXAiPromptCompleteBeforeSecondHang =
process.env.T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG === "1";
const emitOverlappingXAiPromptCompleteOutOfOrder =
process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
@@ -53,21 +36,8 @@ let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
function promptIdFromRequestMeta(
request: Pick<AcpSchema.PromptRequest, "_meta">,
): string | undefined {
const meta = request._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
function logExit(reason: string): void {
if (!exitLogPath) {
return;
@@ -75,10 +45,6 @@ function logExit(reason: string): void {
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
@@ -318,66 +284,22 @@ const program = Effect.gen(function* () {
}),
);
const emitLoadReplayNotifications = (requestedSessionId: string) => {
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "replay-tool-1",
title: "Replay tool",
kind: "search",
status: "completed",
},
});
writeJsonRpcNotification("session/update", {
_meta: { isReplay: true },
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed assistant text" },
},
});
};
yield* agent.handleLoadSession((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (failLoadSession) {
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
}
if (hangLoadSessionAfterReplay || delayLoadSessionAfterReplay) {
emitLoadReplayNotifications(requestedSessionId);
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay-tail" },
},
});
yield* Effect.sleep(loadSessionDelayMs);
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}
if (emitLoadReplay) {
emitLoadReplayNotifications(requestedSessionId);
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
agent.client
.sessionUpdate({
sessionId: String(request.sessionId ?? sessionId),
update: {
sessionUpdate: "user_message_chunk",
content: { type: "text", text: "replay" },
},
});
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
})
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionModel((request) =>
@@ -434,152 +356,19 @@ const program = Effect.gen(function* () {
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "late after cancel" },
},
});
});
}
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
promptCount += 1;
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (failPrompt) {
return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 1) {
return {
stopReason: "end_turn",
_meta: {
promptId: "mock-stale-xai-prompt-1",
requestId: "mock-stale-xai-prompt-1",
},
};
}
if (emitStaleXAiPromptCompleteBeforeSecondHang && promptCount === 2) {
const currentPromptId = promptIdFromRequestMeta(request) ?? "mock-current-xai-prompt-2";
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: "mock-stale-xai-prompt-1",
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: currentPromptId,
stopReason: "end_turn",
agentResult: null,
});
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 1) {
overlappingFirstPromptId = promptIdFromRequestMeta(request);
return yield* Effect.never;
}
if (emitOverlappingXAiPromptCompleteOutOfOrder && promptCount === 2) {
const secondPromptId = promptIdFromRequestMeta(request);
if (overlappingFirstPromptId !== undefined && secondPromptId !== undefined) {
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: secondPromptId,
stopReason: "end_turn",
agentResult: null,
});
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: overlappingFirstPromptId,
stopReason: "end_turn",
agentResult: null,
});
}
return yield* Effect.never;
}
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
return yield* Effect.never;
}
if (emitXAiPromptCompleteThenHang) {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "hello from " },
},
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child before completion" },
},
});
}
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
sessionId: requestedSessionId,
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-prompt-1",
...(omitXAiPromptCompleteStopReason ? {} : { stopReason: "end_turn" }),
agentResult: null,
});
if (emitForeignSessionUpdates) {
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
writeJsonRpcNotification("session/update", {
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child after completion" },
},
});
}
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "mock" },
},
});
return yield* Effect.never;
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
@@ -810,42 +599,6 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitForeignSessionUpdates) {
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "root before child" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "child content" },
},
});
yield* agent.client.sessionUpdate({
sessionId: "mock-child-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "child-tool-call-1",
title: "Child-only tool",
kind: "other",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: " root after child" },
},
});
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
-414
View File
@@ -1,414 +0,0 @@
import {
AuthConnectSecurityMode,
type AuthClientMetadata,
type AuthClientPresentationMetadata,
type AuthConnectClient,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
import type { AuthConnectClientRepositoryError } from "../persistence/Errors.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
const CONNECT_SECURITY_MODE_SECRET = "connect-security-mode";
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const connectClientInternalErrorContext = {
cause: Schema.Defect(),
};
export class ConnectSecurityModeLoadError extends Schema.TaggedErrorClass<ConnectSecurityModeLoadError>()(
"ConnectSecurityModeLoadError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to load Connect security mode.";
}
}
export class ConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ConnectSecurityModeUpdateError>()(
"ConnectSecurityModeUpdateError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to update Connect security mode.";
}
}
export class ConnectClientsLoadError extends Schema.TaggedErrorClass<ConnectClientsLoadError>()(
"ConnectClientsLoadError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to load Connect clients.";
}
}
export class ConnectClientRequestError extends Schema.TaggedErrorClass<ConnectClientRequestError>()(
"ConnectClientRequestError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to record Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientApprovalError extends Schema.TaggedErrorClass<ConnectClientApprovalError>()(
"ConnectClientApprovalError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to approve Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientRejectionError extends Schema.TaggedErrorClass<ConnectClientRejectionError>()(
"ConnectClientRejectionError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to reject Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientRevocationError extends Schema.TaggedErrorClass<ConnectClientRevocationError>()(
"ConnectClientRevocationError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export const ConnectClientStoreError = Schema.Union([
ConnectSecurityModeLoadError,
ConnectSecurityModeUpdateError,
ConnectClientsLoadError,
ConnectClientRequestError,
ConnectClientApprovalError,
ConnectClientRejectionError,
ConnectClientRevocationError,
]);
export type ConnectClientStoreError = typeof ConnectClientStoreError.Type;
export const isConnectClientStoreError = Schema.is(ConnectClientStoreError);
export type ConnectClientChange =
| {
readonly type: "connectSecurityModeUpdated";
readonly mode: AuthConnectSecurityMode;
}
| {
readonly type: "connectClientUpserted";
readonly client: AuthConnectClient;
}
| {
readonly type: "connectClientRemoved";
readonly clientProofKeyThumbprint: string;
};
export type ConnectClientAuthorization =
| {
readonly mode: "account";
readonly status: "approved";
}
| {
readonly mode: "client-approval";
readonly status: "pending" | "approved" | "rejected";
readonly client: AuthConnectClient;
};
export class ConnectClientStore extends Context.Service<
ConnectClientStore,
{
readonly getSecurityMode: () => Effect.Effect<
AuthConnectSecurityMode,
ConnectSecurityModeLoadError
>;
readonly setSecurityMode: (
mode: AuthConnectSecurityMode,
) => Effect.Effect<AuthConnectSecurityMode, ConnectSecurityModeUpdateError>;
readonly listClients: () => Effect.Effect<
ReadonlyArray<AuthConnectClient>,
ConnectClientsLoadError
>;
readonly requestClient: (input: {
readonly cloudUserId: string;
readonly clientProofKeyThumbprint: string;
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<
ConnectClientAuthorization,
ConnectClientRequestError | ConnectSecurityModeLoadError
>;
readonly approve: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientApprovalError>;
readonly reject: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientRejectionError>;
readonly revoke: (
clientProofKeyThumbprint: string,
) => Effect.Effect<boolean, ConnectClientRevocationError>;
readonly streamChanges: Stream.Stream<ConnectClientChange>;
}
>()("t3/auth/ConnectClientStore") {}
function toAuthClientMetadata(
record: AuthConnectClients.AuthConnectClientMetadataRecord,
): AuthClientMetadata {
return {
...(record.label ? { label: record.label } : {}),
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
...(record.userAgent ? { userAgent: record.userAgent } : {}),
deviceType: record.deviceType,
...(record.os ? { os: record.os } : {}),
...(record.browser ? { browser: record.browser } : {}),
};
}
function toAuthConnectClient(
record: AuthConnectClients.AuthConnectClientRecord,
): AuthConnectClient {
return {
clientProofKeyThumbprint: record.clientProofKeyThumbprint,
cloudUserId: record.cloudUserId,
...(record.deviceId ? { deviceId: record.deviceId } : {}),
status: record.status,
client: toAuthClientMetadata(record.client),
requestedAt: DateTime.toUtc(record.requestedAt),
updatedAt: DateTime.toUtc(record.updatedAt),
approvedAt: record.approvedAt === null ? null : DateTime.toUtc(record.approvedAt),
rejectedAt: record.rejectedAt === null ? null : DateTime.toUtc(record.rejectedAt),
lastSeenAt: record.lastSeenAt === null ? null : DateTime.toUtc(record.lastSeenAt),
};
}
function fromPresentationMetadata(
client: AuthClientPresentationMetadata | undefined,
): AuthConnectClients.AuthConnectClientMetadataRecord {
return {
label: client?.label ?? null,
ipAddress: null,
userAgent: null,
deviceType: client?.deviceType ?? "unknown",
os: client?.os ?? null,
browser: null,
};
}
function decodeSecurityMode(bytes: Uint8Array): AuthConnectSecurityMode {
const value = textDecoder.decode(bytes).trim();
return value === "client-approval" ? "client-approval" : "account";
}
function encodeSecurityMode(mode: AuthConnectSecurityMode): Uint8Array {
return textEncoder.encode(mode);
}
export const make = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const repository = yield* AuthConnectClients.AuthConnectClientRepository;
const changesPubSub = yield* PubSub.unbounded<ConnectClientChange>();
const emitMode = (mode: AuthConnectSecurityMode) =>
PubSub.publish(changesPubSub, {
type: "connectSecurityModeUpdated",
mode,
}).pipe(Effect.asVoid);
const emitUpsert = (client: AuthConnectClient) =>
PubSub.publish(changesPubSub, {
type: "connectClientUpserted",
client,
}).pipe(Effect.asVoid);
const emitRemoved = (clientProofKeyThumbprint: string) =>
PubSub.publish(changesPubSub, {
type: "connectClientRemoved",
clientProofKeyThumbprint,
}).pipe(Effect.asVoid);
const getSecurityMode: ConnectClientStore["Service"]["getSecurityMode"] = () =>
secrets.get(CONNECT_SECURITY_MODE_SECRET).pipe(
Effect.map((mode) =>
Option.isSome(mode) ? decodeSecurityMode(mode.value) : ("account" as const),
),
Effect.mapError((cause) => new ConnectSecurityModeLoadError({ cause })),
Effect.withSpan("ConnectClientStore.getSecurityMode"),
);
const setSecurityMode: ConnectClientStore["Service"]["setSecurityMode"] = (mode) =>
secrets.set(CONNECT_SECURITY_MODE_SECRET, encodeSecurityMode(mode)).pipe(
Effect.as(mode),
Effect.tap(emitMode),
Effect.mapError((cause) => new ConnectSecurityModeUpdateError({ cause })),
Effect.withSpan("ConnectClientStore.setSecurityMode"),
);
const listClients: ConnectClientStore["Service"]["listClients"] = () =>
repository.listActive().pipe(
Effect.map((clients) => clients.map(toAuthConnectClient)),
Effect.mapError((cause) => new ConnectClientsLoadError({ cause })),
Effect.withSpan("ConnectClientStore.listClients"),
);
const requestClient: ConnectClientStore["Service"]["requestClient"] = Effect.fn(
"ConnectClientStore.requestClient",
)(function* (input) {
const mode = yield* getSecurityMode();
if (mode === "account") {
return { mode, status: "approved" as const };
}
const requestedAt = yield* DateTime.now;
const record = yield* repository
.upsertRequest({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cloudUserId: input.cloudUserId,
deviceId: input.deviceId ?? null,
client: fromPresentationMetadata(input.client),
requestedAt,
})
.pipe(
Effect.mapError(
(cause) =>
new ConnectClientRequestError({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cause,
}),
),
);
const visibleClient = toAuthConnectClient(record);
yield* emitUpsert(visibleClient);
if (record.status !== "approved") {
return { mode, status: record.status, client: visibleClient };
}
const seenAt = yield* DateTime.now;
const seen = yield* repository
.markSeen({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
seenAt,
})
.pipe(
Effect.mapError(
(cause) =>
new ConnectClientRequestError({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cause,
}),
),
);
if (Option.isSome(seen)) {
const seenClient = toAuthConnectClient(seen.value);
yield* emitUpsert(seenClient);
return { mode, status: "approved" as const, client: seenClient };
}
return { mode, status: "rejected" as const, client: visibleClient };
});
const updateDecision = <E extends ConnectClientApprovalError | ConnectClientRejectionError>(
clientProofKeyThumbprint: string,
status: "approved" | "rejected",
toError: (cause: AuthConnectClientRepositoryError) => E,
): Effect.Effect<Option.Option<AuthConnectClient>, E> =>
DateTime.now.pipe(
Effect.flatMap((decidedAt) =>
repository.updateStatus({
clientProofKeyThumbprint,
status,
decidedAt,
}),
),
Effect.mapError(toError),
Effect.map((updated) => Option.map(updated, toAuthConnectClient)),
Effect.tap((updated) => (Option.isSome(updated) ? emitUpsert(updated.value) : Effect.void)),
);
const approve: ConnectClientStore["Service"]["approve"] = (clientProofKeyThumbprint) =>
updateDecision(
clientProofKeyThumbprint,
"approved",
(cause) =>
new ConnectClientApprovalError({
clientProofKeyThumbprint,
cause,
}),
).pipe(Effect.withSpan("ConnectClientStore.approve"));
const reject: ConnectClientStore["Service"]["reject"] = (clientProofKeyThumbprint) =>
updateDecision(
clientProofKeyThumbprint,
"rejected",
(cause) =>
new ConnectClientRejectionError({
clientProofKeyThumbprint,
cause,
}),
).pipe(Effect.withSpan("ConnectClientStore.reject"));
const revoke: ConnectClientStore["Service"]["revoke"] = (clientProofKeyThumbprint) =>
DateTime.now.pipe(
Effect.flatMap((revokedAt) =>
repository.revoke({
clientProofKeyThumbprint,
revokedAt,
}),
),
Effect.tap((revoked) => (revoked ? emitRemoved(clientProofKeyThumbprint) : Effect.void)),
Effect.mapError(
(cause) =>
new ConnectClientRevocationError({
clientProofKeyThumbprint,
cause,
}),
),
Effect.withSpan("ConnectClientStore.revoke"),
);
return ConnectClientStore.of({
getSecurityMode,
setSecurityMode,
listClients,
requestClient,
approve,
reject,
revoke,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
});
});
export const layer = Layer.effect(ConnectClientStore, make).pipe(
Layer.provideMerge(AuthConnectClients.layer),
);
-179
View File
@@ -3,9 +3,6 @@ import {
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthStandardClientScopes,
type AuthClientPresentationMetadata,
type AuthConnectClient,
type AuthConnectSecurityMode,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
type AuthClientMetadata,
@@ -29,11 +26,9 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
import * as ConnectClientStore from "./ConnectClientStore.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as SessionStore from "./SessionStore.ts";
@@ -312,83 +307,6 @@ export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<
}
}
export class ServerAuthConnectSecurityModeReadError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeReadError>()(
"ServerAuthConnectSecurityModeReadError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to read Connect security mode.";
}
}
export class ServerAuthConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeUpdateError>()(
"ServerAuthConnectSecurityModeUpdateError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to update Connect security mode.";
}
}
export class ServerAuthConnectClientsListError extends Schema.TaggedErrorClass<ServerAuthConnectClientsListError>()(
"ServerAuthConnectClientsListError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to list Connect clients.";
}
}
export class ServerAuthConnectClientRequestError extends Schema.TaggedErrorClass<ServerAuthConnectClientRequestError>()(
"ServerAuthConnectClientRequestError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to authorize Connect client request.";
}
}
export class ServerAuthConnectClientApprovalError extends Schema.TaggedErrorClass<ServerAuthConnectClientApprovalError>()(
"ServerAuthConnectClientApprovalError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to approve Connect client.";
}
}
export class ServerAuthConnectClientRejectionError extends Schema.TaggedErrorClass<ServerAuthConnectClientRejectionError>()(
"ServerAuthConnectClientRejectionError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to reject Connect client.";
}
}
export class ServerAuthConnectClientRevocationError extends Schema.TaggedErrorClass<ServerAuthConnectClientRevocationError>()(
"ServerAuthConnectClientRevocationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke Connect client.";
}
}
export const ServerAuthInternalError = Schema.Union([
ServerAuthBootstrapCredentialValidationError,
ServerAuthSessionCredentialValidationError,
@@ -412,13 +330,6 @@ export const ServerAuthInternalError = Schema.Union([
ServerAuthCloudRelayIssuerMissingError,
ServerAuthCloudHealthJwtSigningError,
ServerAuthCloudMintJwtSigningError,
ServerAuthConnectSecurityModeReadError,
ServerAuthConnectSecurityModeUpdateError,
ServerAuthConnectClientsListError,
ServerAuthConnectClientRequestError,
ServerAuthConnectClientApprovalError,
ServerAuthConnectClientRejectionError,
ServerAuthConnectClientRevocationError,
]);
export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
@@ -565,33 +476,6 @@ export class EnvironmentAuth extends Context.Service<
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly getConnectSecurityMode: () => Effect.Effect<
AuthConnectSecurityMode,
ServerAuthInternalError
>;
readonly setConnectSecurityMode: (
mode: AuthConnectSecurityMode,
) => Effect.Effect<AuthConnectSecurityMode, ServerAuthInternalError>;
readonly listConnectClients: () => Effect.Effect<
ReadonlyArray<AuthConnectClient>,
ServerAuthInternalError
>;
readonly authorizeConnectClientRequest: (input: {
readonly cloudUserId: string;
readonly clientProofKeyThumbprint: string;
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<ConnectClientStore.ConnectClientAuthorization, ServerAuthInternalError>;
readonly approveConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
readonly rejectConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
readonly revokeConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly streamConnectClientChanges: Stream.Stream<ConnectClientStore.ConnectClientChange>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
@@ -673,7 +557,6 @@ export const make = Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
const connectClients = yield* ConnectClientStore.ConnectClientStore;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const descriptor = yield* policy.getDescriptor();
@@ -1020,59 +903,6 @@ export const make = Effect.gen(function* () {
Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
);
const getConnectSecurityMode: EnvironmentAuth["Service"]["getConnectSecurityMode"] = () =>
connectClients.getSecurityMode().pipe(
Effect.mapError((cause) => new ServerAuthConnectSecurityModeReadError({ cause })),
Effect.withSpan("EnvironmentAuth.getConnectSecurityMode"),
);
const setConnectSecurityMode: EnvironmentAuth["Service"]["setConnectSecurityMode"] = (mode) =>
connectClients.setSecurityMode(mode).pipe(
Effect.mapError((cause) => new ServerAuthConnectSecurityModeUpdateError({ cause })),
Effect.withSpan("EnvironmentAuth.setConnectSecurityMode"),
);
const listConnectClients: EnvironmentAuth["Service"]["listConnectClients"] = () =>
connectClients.listClients().pipe(
Effect.mapError((cause) => new ServerAuthConnectClientsListError({ cause })),
Effect.withSpan("EnvironmentAuth.listConnectClients"),
);
const authorizeConnectClientRequest: EnvironmentAuth["Service"]["authorizeConnectClientRequest"] =
(input) =>
connectClients.requestClient(input).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectSecurityModeLoadError"
? new ServerAuthConnectSecurityModeReadError({ cause })
: new ServerAuthConnectClientRequestError({ cause }),
),
Effect.withSpan("EnvironmentAuth.authorizeConnectClientRequest"),
);
const approveConnectClient: EnvironmentAuth["Service"]["approveConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.approve(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientApprovalError({ cause })),
Effect.withSpan("EnvironmentAuth.approveConnectClient"),
);
const rejectConnectClient: EnvironmentAuth["Service"]["rejectConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.reject(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientRejectionError({ cause })),
Effect.withSpan("EnvironmentAuth.rejectConnectClient"),
);
const revokeConnectClient: EnvironmentAuth["Service"]["revokeConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.revoke(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeConnectClient"),
);
const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
issueStartupPairingCredential().pipe(
Effect.map((issued) => {
@@ -1143,14 +973,6 @@ export const make = Effect.gen(function* () {
listClientSessions,
revokeClientSession,
revokeOtherClientSessions,
getConnectSecurityMode,
setConnectSecurityMode,
listConnectClients,
authorizeConnectClientRequest,
approveConnectClient,
rejectConnectClient,
revokeConnectClient,
streamConnectClientChanges: connectClients.streamChanges,
authenticateHttpRequest,
authenticateWebSocketUpgrade,
issueWebSocketTicket,
@@ -1161,7 +983,6 @@ export const make = Effect.gen(function* () {
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
Layer.provideMerge(PairingGrantStore.layer),
Layer.provideMerge(SessionStore.layer),
Layer.provideMerge(ConnectClientStore.layer),
Layer.provideMerge(EnvironmentAuthPolicy.layer),
);
+4 -80
View File
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
create: () => Effect.void,
getById: () => Effect.fail(repositoryFailure),
listActive: () => Effect.succeed([]),
revoke: () => Effect.fail(repositoryFailure),
revokeAllExcept: () => Effect.fail(repositoryFailure),
revoke: () => Effect.succeed(false),
revokeAllExcept: () => Effect.succeed([]),
setLastConnectedAt: () => Effect.void,
});
@@ -104,29 +104,11 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
expect(sessionError.cause).toBe(repositoryFailure);
expect(websocketError.cause).toBe(repositoryFailure);
if (sessionError._tag === "SessionCredentialVerificationError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
}
if (websocketError._tag === "WebSocketTokenVerificationError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
}
expect(revokeError).toMatchObject({
_tag: "SessionRevocationError",
sessionId: issued.sessionId,
cause: repositoryFailure,
});
expect(revokeOthersError).toMatchObject({
_tag: "OtherSessionsRevocationError",
currentSessionId: issued.sessionId,
cause: repositoryFailure,
});
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
);
it.effect("verifies session tokens against the Effect clock", () =>
@@ -163,52 +145,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
yield* TestClock.adjust(Duration.seconds(2));
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(error._tag).toBe("WebSocketSessionExpiredError");
if (error._tag === "WebSocketSessionExpiredError") {
expect(error.sessionId).toBe(issued.sessionId);
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
error.expiresAt.epochMilliseconds,
);
}
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
it.effect("includes expiry context when session and websocket tokens expire", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const issued = yield* sessions.issue({
method: "bearer-access-token",
subject: "short-lived-token",
ttl: Duration.seconds(1),
});
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
ttl: Duration.seconds(1),
});
yield* TestClock.adjust(Duration.seconds(2));
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
expect(sessionError._tag).toBe("SessionTokenExpiredError");
if (sessionError._tag === "SessionTokenExpiredError") {
expect(sessionError.sessionId).toBe(issued.sessionId);
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
sessionError.expiresAt.epochMilliseconds,
);
}
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
if (websocketError._tag === "WebSocketTokenExpiredError") {
expect(websocketError.sessionId).toBe(issued.sessionId);
expect(websocketError.expiresAt.epochMilliseconds).toBe(
websocket.expiresAt.epochMilliseconds,
);
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
websocketError.expiresAt.epochMilliseconds,
);
}
expect(error.message).toContain("expired");
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
);
@@ -236,16 +173,12 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
ipAddress: "192.168.1.88",
},
});
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
yield* sessions.markConnected(client.sessionId);
const beforeRevoke = yield* sessions.listActive();
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
const afterRevoke = yield* sessions.listActive();
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
const revokedClientWebSocket = yield* Effect.flip(
sessions.verifyWebSocketToken(clientWebSocket.token),
);
expect(beforeRevoke).toHaveLength(2);
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
@@ -261,16 +194,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(revokedCount).toBe(1);
expect(afterRevoke).toHaveLength(1);
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
if (revokedClient._tag === "SessionTokenRevokedError") {
expect(revokedClient.sessionId).toBe(client.sessionId);
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
}
expect(revokedClient.message).toContain("revoked");
}).pipe(Effect.provide(makeSessionStoreLayer())),
);
+146 -225
View File
@@ -7,6 +7,7 @@ import {
type AuthEnvironmentScope,
type ServerAuthSessionMethod,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
@@ -92,11 +93,7 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
"SessionTokenExpiredError",
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
{},
) {
override get message(): string {
return "Session token expired.";
@@ -105,9 +102,7 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
"UnknownSessionTokenError",
{
sessionId: AuthSessionId,
},
{},
) {
override get message(): string {
return "Unknown session token.";
@@ -116,10 +111,7 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
"SessionTokenRevokedError",
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
{},
) {
override get message(): string {
return "Session token revoked.";
@@ -128,10 +120,7 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
"InvalidSessionExpirationClaimError",
{
sessionId: AuthSessionId,
expirationClaim: Schema.Number,
},
{},
) {
override get message(): string {
return "Invalid `exp` claim";
@@ -169,11 +158,7 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
"WebSocketTokenExpiredError",
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
{},
) {
override get message(): string {
return "Websocket token expired.";
@@ -182,9 +167,7 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
"UnknownWebSocketSessionError",
{
sessionId: AuthSessionId,
},
{},
) {
override get message(): string {
return "Unknown websocket session.";
@@ -193,11 +176,7 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
"WebSocketSessionExpiredError",
{
sessionId: AuthSessionId,
expiresAt: Schema.DateTimeUtc,
observedAt: Schema.DateTimeUtc,
},
{},
) {
override get message(): string {
return "Websocket session expired.";
@@ -206,10 +185,7 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
"WebSocketSessionRevokedError",
{
sessionId: AuthSessionId,
revokedAt: Schema.DateTimeUtc,
},
{},
) {
override get message(): string {
return "Websocket session revoked.";
@@ -242,7 +218,6 @@ const sessionCredentialInternalErrorContext = {
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
"SessionClaimsEncodingError",
{
sessionId: AuthSessionId,
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
...sessionCredentialInternalErrorContext,
},
@@ -255,7 +230,6 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
"SessionCredentialIssueError",
{
sessionId: Schema.optional(AuthSessionId),
...sessionCredentialInternalErrorContext,
},
) {
@@ -267,7 +241,6 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
"SessionCredentialVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -279,7 +252,6 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
"WebSocketTokenIssueError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -291,7 +263,6 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
"WebSocketTokenVerificationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -314,7 +285,6 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
"SessionRevocationError",
{
sessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -326,7 +296,6 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
"OtherSessionsRevocationError",
{
currentSessionId: AuthSessionId,
...sessionCredentialInternalErrorContext,
},
) {
@@ -570,11 +539,7 @@ export const make = Effect.gen(function* () {
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
function* (input) {
const sessionId = AuthSessionId.make(
yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
),
);
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -594,37 +559,27 @@ export const make = Effect.gen(function* () {
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionCredentialIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_session_claims",
cause,
}),
}),
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
const client = input?.client ?? createDefaultClientMetadata();
yield* authSessions
.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
})
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
yield* authSessions.create({
sessionId,
subject: claims.sub,
scopes: claims.scopes,
method: claims.method,
client: {
label: client.label ?? null,
ipAddress: client.ipAddress ?? null,
userAgent: client.userAgent ?? null,
deviceType: client.deviceType,
os: client.os ?? null,
browser: client.browser ?? null,
},
issuedAt,
expiresAt,
});
yield* emitUpsert(
toAuthClientSession({
sessionId,
@@ -649,6 +604,7 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies IssuedSession;
},
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
);
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
@@ -667,37 +623,22 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
);
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new SessionTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new SessionTokenExpiredError({});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
),
);
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
return yield* new UnknownSessionTokenError({});
}
if (row.value.revokedAt !== null) {
return yield* new SessionTokenRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
return yield* new SessionTokenRevokedError({});
}
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({});
}
return {
@@ -711,111 +652,95 @@ export const make = Effect.gen(function* () {
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new SessionCredentialVerificationError({ cause }),
),
);
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
"SessionStore.issueWebSocketToken",
)(function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new WebSocketTokenIssueError({
sessionId,
cause: new SessionClaimsEncodingError({
sessionId,
operation: "encode_websocket_claims",
cause,
}),
}),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
});
)(
function* (sessionId, input) {
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
});
const claims: WebSocketClaims = {
v: 1,
kind: "websocket",
sid: sessionId,
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) =>
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
expiresAt,
};
},
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
);
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
"SessionStore.verifyWebSocketToken",
)(function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
)(
function* (token) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) {
return yield* new MalformedWebSocketTokenError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const expectedSignature = signPayload(encodedPayload, signingSecret);
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
return yield* new InvalidWebSocketTokenSignatureError({});
}
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
);
const observedAt = yield* DateTime.now;
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new InvalidSessionExpirationClaimError({
sessionId: claims.sid,
expirationClaim: claims.exp,
});
}
if (claims.exp <= observedAt.epochMilliseconds) {
return yield* new WebSocketTokenExpiredError({
sessionId: claims.sid,
expiresAt: expiresAt.value,
observedAt,
});
}
const row = yield* authSessions
.getById({ sessionId: claims.sid })
.pipe(
Effect.mapError(
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
),
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
);
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
}
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
return yield* new WebSocketSessionExpiredError({
sessionId: claims.sid,
expiresAt: row.value.expiresAt,
observedAt,
});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({
sessionId: claims.sid,
revokedAt: row.value.revokedAt,
});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
});
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
return yield* new WebSocketTokenExpiredError({});
}
const row = yield* authSessions.getById({ sessionId: claims.sid });
if (Option.isNone(row)) {
return yield* new UnknownWebSocketSessionError({});
}
if (row.value.expiresAt.epochMilliseconds <= now) {
return yield* new WebSocketSessionExpiredError({});
}
if (row.value.revokedAt !== null) {
return yield* new WebSocketSessionRevokedError({});
}
return {
sessionId: row.value.sessionId,
token,
method: row.value.method,
client: toClientMetadata(row.value.client),
expiresAt: row.value.expiresAt,
subject: row.value.subject,
scopes: row.value.scopes,
} satisfies VerifiedSession;
},
Effect.mapError((cause) =>
isSessionCredentialInvalidError(cause)
? cause
: new WebSocketTokenVerificationError({ cause }),
),
);
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
function* () {
@@ -843,12 +768,10 @@ export const make = Effect.gen(function* () {
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revoked = yield* authSessions
.revoke({
sessionId,
revokedAt,
})
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
const revoked = yield* authSessions.revoke({
sessionId,
revokedAt,
});
if (revoked) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
@@ -859,41 +782,39 @@ export const make = Effect.gen(function* () {
}
return revoked;
},
Effect.mapError((cause) => new SessionRevocationError({ cause })),
);
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
"SessionStore.revokeAllExcept",
)(function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions
.revokeAllExcept({
)(
function* (sessionId) {
const revokedAt = yield* DateTime.now;
const revokedSessionIds = yield* authSessions.revokeAllExcept({
currentSessionId: sessionId,
revokedAt,
})
.pipe(
Effect.mapError(
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
),
);
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
});
if (revokedSessionIds.length > 0) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
for (const revokedSessionId of revokedSessionIds) {
next.delete(revokedSessionId);
}
return next;
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
{
concurrency: "unbounded",
discard: true,
},
);
}
return revokedSessionIds.length;
},
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
);
return SessionStore.of({
cookieName,
+18 -9
View File
@@ -3,8 +3,7 @@ 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 * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
@@ -14,6 +13,22 @@ 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 =>
@@ -33,17 +48,11 @@ 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: url.value.href,
url: requestAbsoluteUrl(input.request),
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
-76
View File
@@ -27,7 +27,6 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Cookies from "effect/unstable/http/Cookies";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -420,81 +419,6 @@ export const authHttpApiLayer = HttpApiBuilder.group(
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
)
.handle(
"connectSecurityMode",
Effect.fn("environment.auth.connectSecurityMode")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const mode = yield* serverAuth.setConnectSecurityMode(args.payload.mode);
return { mode };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_security_mode_update_failed", error),
),
),
)
.handle(
"connectClients",
Effect.fn("environment.auth.connectClients")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listConnectClients();
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_clients_load_failed", error),
),
),
)
.handle(
"approveConnectClient",
Effect.fn("environment.auth.approveConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const client = yield* serverAuth.approveConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { client: Option.getOrNull(client) };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_approval_failed", error),
),
),
)
.handle(
"rejectConnectClient",
Effect.fn("environment.auth.rejectConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const client = yield* serverAuth.rejectConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { client: Option.getOrNull(client) };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_rejection_failed", error),
),
),
)
.handle(
"revokeConnectClient",
Effect.fn("environment.auth.revokeConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const revoked = yield* serverAuth.revokeConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { revoked };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_revoke_failed", error),
),
),
);
}),
);
+11 -253
View File
@@ -1,19 +1,14 @@
import {
AuthConnectClient,
AuthConnectSecurityMode,
AuthRelayWriteScope,
EnvironmentHttpApi,
type AuthConnectClient as AuthConnectClientType,
type RelayClientInstallProgressEvent,
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -21,8 +16,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
@@ -58,69 +52,9 @@ interface CloudCliStatus {
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
readonly connectSecurityMode: AuthConnectSecurityMode;
readonly relayClient: RelayClient.RelayClientStatus;
}
const ConnectSecurityModeOutput = Schema.Struct({
mode: AuthConnectSecurityMode,
});
const encodeConnectSecurityModeOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityModeOutput),
);
const ConnectSecurityClientsOutput = Schema.Struct({
clients: Schema.Array(AuthConnectClient),
});
const ConnectSecurityClientDecisionOutput = Schema.Struct({
client: Schema.NullOr(AuthConnectClient),
});
const ConnectSecurityClientRevokeOutput = Schema.Struct({
revoked: Schema.Boolean,
});
const encodeConnectSecurityClientsOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientsOutput),
);
const encodeConnectSecurityClientDecisionOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientDecisionOutput),
);
const encodeConnectSecurityClientRevokeOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientRevokeOutput),
);
function formatConnectClientLabel(client: AuthConnectClientType): string {
return (
client.client.label ??
client.client.os ??
`client ${client.clientProofKeyThumbprint.slice(0, 12)}`
);
}
function formatConnectClientDetails(client: AuthConnectClientType): string {
const details = [
client.client.deviceType !== "unknown" ? client.client.deviceType : null,
client.client.os ?? null,
client.deviceId ? `device ${client.deviceId}` : null,
client.lastSeenAt ? `last seen ${DateTime.formatIso(client.lastSeenAt)}` : null,
`requested ${DateTime.formatIso(client.requestedAt)}`,
].filter((value): value is string => value !== null);
return details.join(", ");
}
function formatConnectClientList(clients: ReadonlyArray<AuthConnectClientType>): string {
if (clients.length === 0) {
return "No T3 Connect clients are registered.";
}
return [
"T3 Connect clients",
...clients.map(
(client) =>
` ${client.clientProofKeyThumbprint} ${client.status} ${formatConnectClientLabel(
client,
)} (${formatConnectClientDetails(client)})`,
),
].join("\n");
}
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
switch (executable.status) {
case "available": {
@@ -169,9 +103,6 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
` Client approval: ${
status.connectSecurityMode === "client-approval" ? "required" : "account-wide"
}`,
` Relay: ${status.relayUrl ?? "not provisioned"}`,
...formatRelayClientStatus(status.relayClient),
...(nextStep ? ["", `Next: ${nextStep}`] : []),
@@ -480,26 +411,22 @@ const connectStatusCommand = Command.make("status", {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const relayClient = yield* RelayClient.RelayClient;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const [desired, authenticated, cloudUserId, relayUrl, connectSecurityMode, executable] =
yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
environmentAuth.getConnectSecurityMode(),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const status: CloudCliStatus = {
desired,
authenticated,
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
connectSecurityMode,
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
@@ -511,174 +438,6 @@ const connectStatusCommand = Command.make("status", {
),
);
const connectSecurityModeFlag = Flag.choice("mode", ["account", "client-approval"] as const).pipe(
Flag.withDescription("Connect security mode."),
Flag.optional,
);
const connectClientThumbprintArgument = Argument.string("client-proof-key-thumbprint").pipe(
Argument.withDescription("T3 Connect client proof key thumbprint."),
);
const connectSecurityClientsCommand = Command.make("clients", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("List T3 Connect clients registered for approval."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const clients = yield* environmentAuth.listConnectClients();
if (flags.json) {
const output = yield* encodeConnectSecurityClientsOutputJson({ clients });
yield* Console.log(output);
return;
}
yield* Console.log(formatConnectClientList(clients));
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityApproveCommand = Command.make("approve", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Approve a T3 Connect client."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const client = yield* environmentAuth.approveConnectClient(flags.clientProofKeyThumbprint);
const clientOrNull = Option.getOrNull(client);
if (flags.json) {
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
client: clientOrNull,
});
yield* Console.log(output);
return;
}
yield* Console.log(
clientOrNull
? `Approved T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityRejectCommand = Command.make("reject", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Reject a T3 Connect client."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const client = yield* environmentAuth.rejectConnectClient(flags.clientProofKeyThumbprint);
const clientOrNull = Option.getOrNull(client);
if (flags.json) {
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
client: clientOrNull,
});
yield* Console.log(output);
return;
}
yield* Console.log(
clientOrNull
? `Rejected T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityRevokeCommand = Command.make("revoke", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Revoke a T3 Connect client approval record."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const revoked = yield* environmentAuth.revokeConnectClient(flags.clientProofKeyThumbprint);
if (flags.json) {
const output = yield* encodeConnectSecurityClientRevokeOutputJson({ revoked });
yield* Console.log(output);
return;
}
yield* Console.log(
revoked
? `Revoked T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityCommand = Command.make("security", {
...projectLocationFlags,
mode: connectSecurityModeFlag,
json: jsonFlag,
}).pipe(
Command.withDescription("Read or update T3 Connect client-approval mode."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const mode = Option.isSome(flags.mode)
? yield* environmentAuth.setConnectSecurityMode(flags.mode.value)
: yield* environmentAuth.getConnectSecurityMode();
if (flags.json) {
const output = yield* encodeConnectSecurityModeOutputJson({ mode });
yield* Console.log(output);
return;
}
yield* Console.log(
mode === "client-approval"
? "T3 Connect client approval is required."
: "T3 Connect uses account-wide access.",
);
}),
{
quietLogs: flags.json,
},
),
),
Command.withSubcommands([
connectSecurityClientsCommand,
connectSecurityApproveCommand,
connectSecurityRejectCommand,
connectSecurityRevokeCommand,
]),
);
const connectUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
@@ -703,7 +462,6 @@ export const connectCommand = Command.make("connect").pipe(
connectLoginCommand,
connectLinkCommand,
connectStatusCommand,
connectSecurityCommand,
connectUnlinkCommand,
connectLogoutCommand,
]),
+4 -9
View File
@@ -2,11 +2,7 @@ import { assert, it } from "@effect/vitest";
import { EnvironmentInternalError } from "@t3tools/contracts";
import {
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerRequestError,
projectCommandErrorFromLiveServerRequest,
} from "./project.ts";
import { ProjectCommandError } from "./project.ts";
it("maps declared server failures into structural project command errors", () => {
const cause = new EnvironmentInternalError({
@@ -15,9 +11,8 @@ it("maps declared server failures into structural project command errors", () =>
traceId: "trace-123",
});
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.code, "internal_error");
assert.strictEqual(error.traceId, "trace-123");
@@ -28,10 +23,10 @@ it("maps declared server failures into structural project command errors", () =>
it("preserves unexpected server failures without deriving the message from them", () => {
const cause = new Error("credential abc123 was rejected");
const error = projectCommandErrorFromLiveServerRequest(cause);
const error = ProjectCommandError.fromLiveServerRequest(cause);
assert.instanceOf(error, ProjectLiveServerRequestError);
assert.strictEqual(error.operation, "callLiveServer");
assert.strictEqual(error.detail, "Failed to call the running server.");
assert.strictEqual(error.message, "Failed to call the running server.");
assert.strictEqual(error.cause, cause);
});
+49 -138
View File
@@ -51,148 +51,62 @@ type ProjectCliDispatchCommand = Extract<
>;
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
const ProjectCommandOperation = Schema.Literals([
"generateProjectCommandId",
"callLiveServer",
"validateProjectTitle",
"resolveProjectTarget",
"addProject",
]);
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
"ProjectCommandIdGenerationError",
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
"ProjectCommandError",
{
operation: Schema.Literal("generateProjectCommandId"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to generate a project command identifier.";
}
}
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
"ProjectLiveServerDeclaredResponseError",
{
operation: Schema.Literal("callLiveServer"),
code: Schema.String,
traceId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed (${this.code}, trace ${this.traceId}).`;
}
}
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
"ProjectLiveServerUndeclaredStatusError",
{
operation: Schema.Literal("callLiveServer"),
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Server request failed with undeclared status ${this.status}.`;
}
}
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
"ProjectLiveServerRequestError",
{
operation: Schema.Literal("callLiveServer"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to call the running server.";
}
}
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
"ProjectTitleEmptyError",
{
operation: Schema.Literal("validateProjectTitle"),
title: Schema.String,
},
) {
override get message(): string {
return "Project title cannot be empty.";
}
}
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
"ProjectIdentifierEmptyError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
},
) {
override get message(): string {
return "Project identifier cannot be empty.";
}
}
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
"ProjectNotFoundError",
{
operation: Schema.Literal("resolveProjectTarget"),
identifier: Schema.String,
normalizedWorkspaceRoot: Schema.optional(Schema.String),
activeProjectCount: Schema.Number,
operation: ProjectCommandOperation,
detail: Schema.String,
code: Schema.optional(Schema.String),
traceId: Schema.optional(Schema.String),
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `No active project found for '${this.identifier}'.`;
}
}
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
"ProjectAlreadyExistsError",
{
operation: Schema.Literal("addProject"),
projectId: ProjectId,
workspaceRoot: Schema.String,
},
) {
override get message(): string {
return `An active project already exists for '${this.workspaceRoot}'.`;
}
}
export const ProjectCommandError = Schema.Union([
ProjectCommandIdGenerationError,
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerUndeclaredStatusError,
ProjectLiveServerRequestError,
ProjectTitleEmptyError,
ProjectIdentifierEmptyError,
ProjectNotFoundError,
ProjectAlreadyExistsError,
]);
export type ProjectCommandError = typeof ProjectCommandError.Type;
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectLiveServerDeclaredResponseError({
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
if (isEnvironmentHttpCommonError(cause)) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectCommandError({
operation: "callLiveServer",
detail: `Server request failed with undeclared status ${cause.response.status}.`,
status: cause.response.status,
cause,
});
}
return new ProjectCommandError({
operation: "callLiveServer",
code: cause.code,
traceId: cause.traceId,
cause,
});
}
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
return new ProjectLiveServerUndeclaredStatusError({
operation: "callLiveServer",
status: cause.response.status,
detail: "Failed to call the running server.",
cause,
});
}
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
override get message(): string {
return this.detail;
}
}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
(cause) =>
new ProjectCommandIdGenerationError({
new ProjectCommandError({
operation: "generateProjectCommandId",
detail: "Failed to generate a project command identifier.",
cause,
}),
),
@@ -244,9 +158,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
if (trimmed.length > 0) {
return trimmed;
}
return yield* new ProjectTitleEmptyError({
return yield* new ProjectCommandError({
operation: "validateProjectTitle",
title: explicitTitle,
detail: "Project title cannot be empty.",
});
}
@@ -261,9 +175,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* new ProjectIdentifierEmptyError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: input.identifier,
detail: "Project identifier cannot be empty.",
});
}
@@ -290,11 +204,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* new ProjectNotFoundError({
return yield* new ProjectCommandError({
operation: "resolveProjectTarget",
identifier: trimmedIdentifier,
activeProjectCount: activeProjects.length,
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
detail: `No active project found for '${trimmedIdentifier}'.`,
...(normalizedWorkspaceRootResult._tag === "Failure"
? { cause: normalizedWorkspaceRootResult.failure }
: {}),
@@ -316,7 +228,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
});
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const dispatchLiveOrchestrationCommand = (
@@ -332,7 +244,7 @@ const dispatchLiveOrchestrationCommand = (
} as Parameters<typeof client.orchestration.dispatch>[0]);
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
@@ -464,10 +376,9 @@ const projectAddCommand = Command.make("add", {
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* new ProjectAlreadyExistsError({
return yield* new ProjectCommandError({
operation: "addProject",
projectId: existingProject.id,
workspaceRoot,
detail: `An active project already exists for '${workspaceRoot}'.`,
});
}
+9 -66
View File
@@ -608,17 +608,15 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
dependencies: CloudHttpDependencies,
) {
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity, connectSecurityMode] =
yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
dependencies.environmentAuth.getConnectSecurityMode(),
],
{ concurrency: 5 },
);
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
],
{ concurrency: 4 },
);
return {
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
@@ -627,7 +625,6 @@ const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function
publishAgentActivity: Option.isSome(publishAgentActivity)
? bytesToString(publishAgentActivity.value) === "true"
: false,
connectSecurityMode,
} satisfies EnvironmentCloudLinkStateResult;
});
@@ -640,9 +637,6 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
);
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
@@ -686,9 +680,6 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
@@ -877,54 +868,6 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
const connectAuthorization = yield* dependencies.environmentAuth.authorizeConnectClientRequest({
cloudUserId: linkedCloudUserId,
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
...(proof.deviceId ? { deviceId: proof.deviceId } : {}),
...(proof.client ? { client: proof.client } : {}),
});
if (
connectAuthorization.mode === "client-approval" &&
connectAuthorization.status !== "approved"
) {
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
const responsePayload = {
iss: `t3-env:${environmentId}`,
aud: normalizeRelayIssuer(relayIssuer),
sub: environmentId,
jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
iat: nowSeconds,
exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
environmentId,
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
requestNonce: proof.nonce,
status: "pending_approval",
approvalStatus: connectAuthorization.status,
} satisfies RelayEnvironmentMintResponseProofPayload;
const responseProof = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_MINT_RESPONSE_TYP,
payload: responsePayload,
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
cause,
}),
),
);
const response = {
status: "pending_approval",
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
approvalStatus: connectAuthorization.status,
requestedAt: DateTime.formatIso(connectAuthorization.client.requestedAt),
proof: responseProof,
} satisfies RelayEnvironmentMintResponseShape;
yield* appendCloudCredentialResponseHeaders;
return response;
}
const issued = yield* dependencies.environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
+39 -17
View File
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
if (result.status === 0) {
return;
}
throw new Error(
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
throw new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd,
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
});
}
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
(error as { _tag?: unknown })._tag === "GitHubCliError"
);
}
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
return fakeGhOutput("");
},
catch: (error) =>
GitHubCli.isGitHubCliError(error)
isGitHubCliError(error)
? error
: new GitHubCli.GitHubCliCommandError({
: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: error,
detail:
error instanceof Error
? `Failed to simulate gh checkout: ${error.message}`
: "Failed to simulate gh checkout.",
}),
});
}
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
if (!cloneUrls) {
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository lookup: ${repository}`),
detail: `Unexpected repository lookup: ${repository}`,
}),
);
}
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
detail: `Unexpected gh command: ${args.join(" ")}`,
}),
);
};
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
createRepository: (input) =>
Effect.fail(
new GitHubCli.GitHubCliCommandError({
new GitHubCli.GitHubCliError({
operation: "createRepository",
command: "gh",
cwd: input.cwd,
cause: new Error(`Unexpected repository create: ${input.repository}`),
detail: `Unexpected repository create: ${input.repository}`,
}),
),
checkoutPullRequest: (input) =>
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2463,10 +2483,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliUnavailableError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not available on PATH"),
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
}),
},
});
@@ -2493,10 +2514,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
failWith: new GitHubCli.GitHubCliAuthenticationError({
failWith: new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: repoDir,
cause: new Error("gh is not authenticated"),
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
}),
},
});
+1 -6
View File
@@ -44,18 +44,13 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
return HttpRouter.cors({
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
: {}),
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
maxAge: 600,
-1
View File
@@ -198,7 +198,6 @@ 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");
+75 -56
View File
@@ -1,6 +1,5 @@
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -35,7 +34,7 @@ const client = McpSchema.McpServerClient.of({
});
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
Layer.provideMerge(PreviewAutomationBroker.layer),
);
it("normalizes empty successful notification responses to accepted", () => {
@@ -55,26 +54,36 @@ it.effect("returns bounded structural preview snapshot failures", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const events = yield* broker.connect({
const requests = yield* broker.connect({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(events, (event) =>
event.type === "connected"
? Effect.void
: broker.respond({
clientId: "mcp-failure-client",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: false,
error: {
_tag: "PreviewAutomationExecutionError",
message: "sensitive renderer failure",
detail: { consoleOutput: "sensitive browser output" },
},
}),
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: false,
error: {
_tag: "PreviewAutomationExecutionError",
message: "sensitive renderer failure",
detail: { consoleOutput: "sensitive browser output" },
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-failure-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: {} })
@@ -154,50 +163,60 @@ it.effect("registers annotated tools and preserves authenticated request context
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const events = yield* broker.connect({
const requests = yield* broker.connect({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* Stream.runForEach(events, (event) =>
event.type === "connected"
? Effect.void
: broker.respond({
clientId: "mcp-test-client",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: true,
result:
event.request.operation === "snapshot"
? {
url: "http://example.test/",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
accessibilityTree: {},
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
screenshot: {
mimeType: "image/png",
data: Buffer.from("png").toString("base64"),
width: 10,
height: 5,
},
}
: event.request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: true,
result:
request.operation === "snapshot"
? {
url: "http://example.test/",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
accessibilityTree: {},
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
screenshot: {
mimeType: "image/png",
data: Buffer.from("png").toString("base64"),
width: 10,
height: 5,
},
}
: request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
+4 -1
View File
@@ -214,4 +214,7 @@ const McpTransportLive = McpServer.layerHttp({
path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpTransportLive),
Layer.provide(PreviewAutomationBroker.layer),
);
@@ -1,39 +0,0 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationUnavailableError,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as McpInvocationContext from "./McpInvocationContext.ts";
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
const invocation: McpInvocationContext.McpInvocationScope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(),
issuedAt: 1,
expiresAt: 2,
};
return Effect.gen(function* () {
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.flip,
);
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
expect(error).toMatchObject({
capability: "preview",
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
});
expect(error.message).toBe("MCP credential does not grant the preview capability.");
});
});
+3 -11
View File
@@ -1,9 +1,5 @@
import {
type EnvironmentId,
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -30,11 +26,7 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
capability,
environmentId: invocation.environmentId,
threadId: invocation.threadId,
providerSessionId: invocation.providerSessionId,
providerInstanceId: invocation.providerInstanceId,
message: `MCP credential does not grant the ${capability} capability.`,
});
}
return invocation;
@@ -1,28 +1,20 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationClientDisconnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoAvailableHostError,
PreviewAutomationTargetNotEditableError,
PreviewTabId,
PreviewAutomationNoFocusedOwnerError,
ProviderInstanceId,
ThreadId,
type PreviewAutomationHost,
type PreviewAutomationRequest,
type PreviewAutomationStreamEvent,
type PreviewAutomationOwner,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const makeBroker = PreviewAutomationBroker.make.pipe(Effect.provide(NodeServices.layer));
const scope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
@@ -30,42 +22,27 @@ const scope = {
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
expiresAt: 2,
};
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
const makeOwner = (overrides: Partial<PreviewAutomationOwner> = {}): PreviewAutomationOwner => ({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: null,
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
...overrides,
});
type RoutedRequest = PreviewAutomationRequest & {
readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
};
const requestsFrom = (
events: Stream.Stream<PreviewAutomationStreamEvent>,
onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
): Stream.Stream<RoutedRequest> =>
events.pipe(
Stream.filterMap((event) => {
if (event.type === "connected") {
onConnected(event.connectionId);
return Result.failVoid;
}
return Result.succeed({ ...event.request, connectionId: event.connectionId });
}),
);
it.effect("atomically registers a connected host and correlates its response", () =>
it.effect("atomically registers a connected owner and correlates its response", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: { available: true },
@@ -84,39 +61,6 @@ it.effect("atomically registers a connected host and correlates its response", (
),
);
it.effect("announces a live replacement stream before delivering requests", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const events = yield* broker.connect(makeHost());
const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
const consumer = yield* events.pipe(
Stream.take(2),
Stream.runForEach((event) => {
receivedTypes.push(event.type);
return event.type === "connected"
? Effect.void
: broker.respond({
clientId: "client-1",
connectionId: event.connectionId,
requestId: event.request.requestId,
ok: true,
result: "ready",
});
}),
Effect.forkScoped,
);
yield* Effect.yieldNow;
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
yield* Fiber.join(consumer);
expect(receivedTypes).toEqual(["connected", "request"]);
expect(result).toBe("ready");
}),
),
);
it.effect("preserves bounded request and remote selector diagnostics", () => {
const locator = "role=button[name='request-secret']";
const remoteMessage = "Unexpected token near remote-secret.";
@@ -128,12 +72,10 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
return Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ tabId: "tab-1" }));
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
error: remoteError,
@@ -146,7 +88,6 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
scope,
operation: "click",
input: { locator },
tabId: PreviewTabId.make("tab-1"),
timeoutMs: 1_234,
})
.pipe(Effect.flip);
@@ -180,61 +121,13 @@ it.effect("preserves bounded request and remote selector diagnostics", () => {
);
});
it.effect("classifies a remote non-editable target without collapsing it to execution", () => {
const remoteError = {
_tag: "PreviewAutomationTargetNotEditableError",
message: "remote target details",
detail: { selectorKind: "focused-element" },
} as const;
return Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
error: remoteError,
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({
scope,
operation: "type",
input: { text: "hello" },
tabId: PreviewTabId.make("tab-1"),
})
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError);
expect(error).toMatchObject({
operation: "type",
tabId: "tab-1",
selectorKind: "focused-element",
remoteTag: "PreviewAutomationTargetNotEditableError",
});
expect(error.message).toBe("Preview automation type requires an editable focused element.");
}),
);
});
it.effect("distinguishes malformed remote failures", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: false,
}),
broker.respond({ requestId: request.requestId, ok: false }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
@@ -257,14 +150,13 @@ it.effect("distinguishes malformed remote failures", () =>
),
);
it.effect("rejects calls when no connected host exists", () =>
it.effect("rejects calls when no focused owner exists", () =>
Effect.gen(function* () {
const broker = yield* makeBroker;
const broker = yield* PreviewAutomationBroker.make;
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
expect(error).toMatchObject({
operation: "status",
environmentId: scope.environmentId,
@@ -275,425 +167,32 @@ it.effect("rejects calls when no connected host exists", () =>
}),
);
it.effect("does not create host state from focus updates without a live stream", () =>
Effect.gen(function* () {
const broker = yield* makeBroker;
yield* broker.focusHost({
clientId: "client-1",
environmentId: scope.environmentId,
connectionId: "connection-missing",
focused: true,
});
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
}),
);
it.effect("removes host availability when the authoritative request stream disconnects", () =>
it.effect("routes interactive commands to a hidden durable browser host", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const beforeAcquisition = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(
makeOwner({ clientId: "client-hidden", tabId: "tab-hidden" }),
);
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Fiber.interrupt(consumer);
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
}),
),
);
it.effect("routes requests for background threads through an environment-level host", () =>
it.effect("lets the browser host resolve an active tab that has not been reported yet", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const backgroundThreadId = ThreadId.make("thread-background");
const requests = requestsFrom(yield* broker.connect(makeHost()));
let routedThreadId: string | undefined;
yield* Stream.runForEach(requests, (request) => {
routedThreadId = request.threadId;
return broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "background",
});
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const result = yield* broker.invoke<string>({
scope: {
...scope,
threadId: backgroundThreadId,
providerSessionId: "provider-session-background",
},
operation: "status",
input: {},
});
expect(result).toBe("background");
expect(routedThreadId).toBe(backgroundThreadId);
}),
),
);
it.effect("never routes a provider session to a host from another environment", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const matchingRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-matching" })),
);
const foreignRequests = requestsFrom(
yield* broker.connect(
makeHost({
clientId: "client-foreign",
environmentId: EnvironmentId.make("environment-foreign"),
}),
),
);
yield* Stream.runForEach(matchingRequests, (request) =>
broker.respond({
clientId: "client-matching",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "matching",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(foreignRequests, (request) =>
broker.respond({
clientId: "client-foreign",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "foreign",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"matching",
);
}),
),
);
it.effect("pins a provider session to its initial host despite later focus changes", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
let secondConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
(connectionId) => {
secondConnectionId = connectionId;
},
);
yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: "connection-stale",
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: firstConnectionId,
focused: true,
});
const firstPinnedScope = {
...scope,
providerSessionId: "provider-session-first-pinned",
};
expect(
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
).toBe("first");
yield* broker.focusHost({
clientId: "client-second",
environmentId: scope.environmentId,
connectionId: secondConnectionId,
focused: true,
});
expect(
yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
).toBe("first");
expect(
yield* broker.invoke<string>({
scope: { ...scope, providerSessionId: "provider-session-second-pinned" },
operation: "status",
input: {},
}),
).toBe("second");
}),
),
);
it.effect("does not route new operations to legacy hosts that did not advertise support", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const legacyEvents = yield* broker.connect(makeHost());
yield* Stream.runDrain(legacyEvents).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId });
}),
),
);
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const capableRequests = requestsFrom(
yield* broker.connect(
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
),
);
const legacyRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
);
yield* Stream.runForEach(capableRequests, (request) =>
broker.respond({
clientId: "client-capable",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "capable",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(legacyRequests, (request) =>
broker.respond({
clientId: "client-legacy",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "legacy",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(
yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
).toBe("capable");
}),
),
);
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const legacyRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-legacy" })),
);
yield* Stream.runForEach(legacyRequests, (request) =>
broker.respond({
clientId: "client-legacy",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "legacy",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"legacy",
);
const capableRequests = requestsFrom(
yield* broker.connect(
makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
),
);
yield* Stream.runForEach(capableRequests, (request) =>
broker.respond({
clientId: "client-capable",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "capable",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const error = yield* broker
.invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"legacy",
);
}),
),
);
it.effect("ignores stale focus updates for a different environment", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
);
yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: EnvironmentId.make("environment-stale"),
connectionId: firstConnectionId,
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
}),
),
);
it.effect("fails over a pinned provider session only after its host disconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
const firstRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-first" })),
(connectionId) => {
firstConnectionId = connectionId;
},
);
const secondRequests = requestsFrom(
yield* broker.connect(makeHost({ clientId: "client-second" })),
);
const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
broker.respond({
clientId: "client-first",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "first",
}),
).pipe(Effect.forkScoped);
yield* Stream.runForEach(secondRequests, (request) =>
broker.respond({
clientId: "client-second",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "second",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.focusHost({
clientId: "client-first",
environmentId: scope.environmentId,
connectionId: firstConnectionId,
focused: true,
});
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("first");
yield* Fiber.interrupt(firstConsumer);
yield* Effect.yieldNow;
expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
"second",
);
}),
),
);
it.effect("lets the browser host resolve an active tab locally", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ tabId: null }));
let routedTabId: string | undefined;
yield* Stream.runForEach(requests, (request) => {
routedTabId = request.tabId;
return broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
});
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
@@ -704,55 +203,61 @@ it.effect("lets the browser host resolve an active tab locally", () =>
),
);
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
it.effect("preserves current owner metadata when its request stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
let firstConnectionId = "";
let replacementConnectionId = "";
const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
firstConnectionId = connectionId;
});
const broker = yield* PreviewAutomationBroker.make;
const firstRequests = yield* broker.connect(makeOwner());
yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
yield* broker.reportOwner(makeOwner({ tabId: "tab-current", visible: true }));
const reconnectedRequests = yield* broker.connect(makeOwner());
let routedTabId: string | undefined;
yield* Stream.runForEach(reconnectedRequests, (request) => {
routedTabId = request.tabId;
return broker.respond({ requestId: request.requestId, ok: true });
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const replacementRequests = requestsFrom(
yield* broker.connect(makeHost()),
(connectionId) => {
replacementConnectionId = connectionId;
},
);
yield* Stream.runForEach(replacementRequests, (request) =>
broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "replacement",
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
expect(replacementConnectionId).not.toBe(firstConnectionId);
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
expect(result).toBe("replacement");
expect(routedTabId).toBe("tab-current");
}),
),
);
it.effect("fails requests assigned to the stream that is replaced", () =>
it.effect("ignores stale owner cleanup after the client moves to another thread", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner());
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.clearOwner({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: ThreadId.make("thread-stale"),
});
yield* broker.invoke<void>({ scope, operation: "status", input: {} });
}),
),
);
it.effect("fails requests assigned to a browser stream when that stream reconnects", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.make;
const _requests = yield* broker.connect(makeOwner());
const pending = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
const _replacementRequests = yield* broker.connect(makeOwner());
const error = yield* Fiber.join(pending);
expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
@@ -770,40 +275,25 @@ it.effect("fails requests assigned to the stream that is replaced", () =>
),
);
it.effect("accepts responses only from the host that received the request", () =>
it.effect("falls back to an older connected owner when a newer report is not connected", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* makeBroker;
const requests = requestsFrom(yield* broker.connect(makeHost()));
const broker = yield* PreviewAutomationBroker.make;
const requests = yield* broker.connect(makeOwner({ clientId: "client-connected" }));
yield* Stream.runForEach(requests, (request) =>
Effect.gen(function* () {
yield* broker.respond({
clientId: "client-foreign",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "foreign",
});
yield* broker.respond({
clientId: "client-1",
connectionId: "connection-stale",
requestId: request.requestId,
ok: true,
result: "stale",
});
yield* broker.respond({
clientId: "client-1",
connectionId: request.connectionId,
requestId: request.requestId,
ok: true,
result: "owner",
});
}),
broker.respond({ requestId: request.requestId, ok: true, result: "connected" }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner(
makeOwner({
clientId: "client-report-only",
focusedAt: "2026-06-11T00:00:01.000Z",
}),
);
const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
expect(result).toBe("owner");
expect(result).toBe("connected");
}),
),
);
+142 -267
View File
@@ -1,29 +1,26 @@
import {
PREVIEW_AUTOMATION_V1_OPERATIONS,
PreviewAutomationClientDisconnectedError,
PreviewAutomationControlInterruptedError,
PreviewAutomationExecutionError,
PreviewAutomationHostNotConnectedError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationMalformedResponseError,
PreviewAutomationNoAvailableHostError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationRemoteUnavailableError,
PreviewAutomationRequestQueueClosedError,
PreviewAutomationResultTooLargeError,
PreviewAutomationTabNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationTimeoutError,
PreviewAutomationUnsupportedClientError,
type PreviewAutomationError,
type PreviewAutomationOperation,
type PreviewAutomationHost,
type PreviewAutomationHostFocus,
type PreviewAutomationOwner,
type PreviewAutomationOwnerIdentity,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
type PreviewAutomationStreamEvent,
type PreviewTabId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -46,9 +43,12 @@ export class PreviewAutomationBroker extends Context.Service<
PreviewAutomationBroker,
{
readonly connect: (
host: PreviewAutomationHost,
) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
owner: PreviewAutomationOwner,
) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
readonly reportOwner: (
owner: PreviewAutomationOwner,
) => Effect.Effect<void, PreviewAutomationError>;
readonly clearOwner: (owner: PreviewAutomationOwnerIdentity) => Effect.Effect<void>;
readonly respond: (
response: PreviewAutomationResponse,
) => Effect.Effect<void, PreviewAutomationError>;
@@ -60,12 +60,7 @@ export class PreviewAutomationBroker extends Context.Service<
interface ClientConnection {
readonly clientId: string;
readonly connectionId: string;
readonly environmentId: PreviewAutomationHost["environmentId"];
readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
readonly focused: boolean;
readonly focusOrder: number;
readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;
readonly queue: Queue.Queue<PreviewAutomationRequest>;
}
interface PendingRequest {
@@ -74,13 +69,6 @@ interface PendingRequest {
readonly context: PreviewAutomationRequestErrorContext;
}
interface HostAssignment {
readonly clientId: ClientConnection["clientId"];
readonly connectionId: ClientConnection["connectionId"];
readonly queue: ClientConnection["queue"];
readonly expiresAt: number;
}
interface PreviewAutomationRequestErrorContext {
readonly operation: PreviewAutomationOperation;
readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
@@ -88,7 +76,6 @@ interface PreviewAutomationRequestErrorContext {
readonly providerSessionId: string;
readonly providerInstanceId: McpInvocationContext.McpInvocationScope["providerInstanceId"];
readonly clientId: string;
readonly connectionId: ClientConnection["connectionId"];
readonly requestId: string;
readonly tabId?: PreviewTabId;
readonly timeoutMs: number;
@@ -98,36 +85,11 @@ interface PreviewAutomationRequestErrorContext {
interface BrokerState {
readonly clients: ReadonlyMap<string, ClientConnection>;
readonly assignments: ReadonlyMap<string, HostAssignment>;
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
readonly pending: ReadonlyMap<string, PendingRequest>;
readonly requestSequence: number;
readonly focusSequence: number;
}
const removeConnectionFromState = (
current: BrokerState,
clientId: string,
queue: ClientConnection["queue"],
): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
const clients = new Map(current.clients);
const assignments = new Map(current.assignments);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
for (const [assignmentKey, assignment] of assignments) {
if (assignment.queue === queue) assignments.delete(assignmentKey);
}
for (const [requestId, entry] of pending) {
if (entry.queue !== queue) continue;
pending.delete(requestId);
disconnected.push(entry);
}
return {
state: { ...current, clients, assignments, pending },
disconnected,
};
};
const selectorDiagnosticsFromInput = (
input: unknown,
): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
@@ -141,14 +103,6 @@ const selectorDiagnosticsFromInput = (
return {};
};
const hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>
`${scope.environmentId}\u0000${scope.providerSessionId}`;
const supportsOperation = (
connection: ClientConnection,
operation: PreviewAutomationOperation,
): boolean => connection.supportedOperations.has(operation);
type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
function remoteDetailKind(detail: unknown): RemoteDetailKind {
@@ -177,8 +131,8 @@ const classifyResponseError = (
cause: error,
};
switch (error._tag) {
case "PreviewAutomationNoAvailableHostError":
return new PreviewAutomationNoAvailableHostError({
case "PreviewAutomationNoFocusedOwnerError":
return new PreviewAutomationNoFocusedOwnerError({
...context,
...remoteDiagnostics,
});
@@ -208,36 +162,6 @@ const classifyResponseError = (
...remoteDiagnostics,
});
}
case "PreviewAutomationTargetNotEditableError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
const remoteSelectorKind =
detail &&
"selectorKind" in detail &&
(detail.selectorKind === "focused-element" ||
detail.selectorKind === "locator" ||
detail.selectorKind === "selector")
? detail.selectorKind
: undefined;
const remoteSelectorLength =
detail &&
"selectorLength" in detail &&
typeof detail.selectorLength === "number" &&
Number.isInteger(detail.selectorLength) &&
detail.selectorLength >= 0
? detail.selectorLength
: undefined;
return new PreviewAutomationTargetNotEditableError({
...context,
...remoteDiagnostics,
...(remoteSelectorKind === undefined && context.selectorKind === undefined
? {}
: { selectorKind: remoteSelectorKind ?? context.selectorKind }),
...(remoteSelectorLength === undefined && context.selectorLength === undefined
? {}
: { selectorLength: remoteSelectorLength ?? context.selectorLength }),
});
}
case "PreviewAutomationResultTooLargeError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
@@ -269,21 +193,36 @@ const classifyResponseError = (
};
export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const crypto = yield* Crypto.Crypto;
const state = yield* SynchronizedRef.make<BrokerState>({
clients: new Map(),
assignments: new Map(),
owners: new Map(),
pending: new Map(),
requestSequence: 0,
focusSequence: 0,
});
const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
clientId: string,
queue: ClientConnection["queue"],
disconnected: ReadonlyArray<PendingRequest>,
) {
const toFail = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
if (current.clients.get(clientId)?.queue === queue) {
clients.delete(clientId);
owners.delete(clientId);
}
for (const [requestId, entry] of pending) {
if (entry.queue === queue) {
pending.delete(requestId);
disconnected.push(entry);
}
}
return [disconnected, { ...current, clients, owners, pending }] as const;
});
yield* Effect.forEach(
disconnected,
toFail,
({ deferred, context }) =>
Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
{ discard: true },
@@ -291,89 +230,54 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
yield* Queue.shutdown(queue);
});
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
clientId: string,
queue: ClientConnection["queue"],
) {
const disconnected = yield* SynchronizedRef.modify(state, (current) => {
const removed = removeConnectionFromState(current, clientId, queue);
return [removed.disconnected, removed.state] as const;
});
yield* closeConnection(queue, disconnected);
});
const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
host: PreviewAutomationHost,
) {
const clientId = host.clientId;
const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();
const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
yield* Queue.offer(queue, { type: "connected", connectionId });
const connection: ClientConnection = {
clientId,
connectionId,
environmentId: host.environmentId,
supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
focused: false,
focusOrder: 0,
queue,
};
const registration = yield* SynchronizedRef.modify(state, (current) => {
const previousConnection = current.clients.get(clientId);
const removed = previousConnection
? removeConnectionFromState(current, clientId, previousConnection.queue)
: { state: current, disconnected: [] };
const clients = new Map(removed.state.clients);
const focusSequence = removed.state.focusSequence + 1;
const registeredConnection = { ...connection, focusOrder: focusSequence };
clients.set(clientId, registeredConnection);
return [
{
previousConnection,
disconnected: removed.disconnected,
registeredConnection,
},
{ ...removed.state, clients, focusSequence },
] as const;
});
if (registration.previousConnection) {
yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
}
return registration.registeredConnection;
});
const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
"PreviewAutomationBroker.connect",
)((host) =>
Effect.succeed(
Stream.unwrap(
Effect.acquireRelease(acquireConnection(host), (connection) =>
disconnect(connection.clientId, connection.queue),
).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
),
),
);
)(function* (owner) {
const clientId = owner.clientId;
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
const previous = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const existingOwner = current.owners.get(clientId);
clients.set(clientId, { clientId, queue });
owners.set(
clientId,
existingOwner?.environmentId === owner.environmentId &&
existingOwner.threadId === owner.threadId
? { ...existingOwner, supportsAutomation: owner.supportsAutomation }
: owner,
);
return [current.clients.get(clientId), { ...current, clients, owners }] as const;
});
if (previous) yield* disconnect(clientId, previous.queue);
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
});
const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
"PreviewAutomationBroker.focusHost",
)(function* (host) {
const reportOwner: PreviewAutomationBroker["Service"]["reportOwner"] = Effect.fn(
"PreviewAutomationBroker.reportOwner",
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const currentHost = current.clients.get(host.clientId);
const owners = new Map(current.owners);
owners.set(owner.clientId, owner);
return { ...current, owners };
});
});
const clearOwner: PreviewAutomationBroker["Service"]["clearOwner"] = Effect.fn(
"PreviewAutomationBroker.clearOwner",
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const currentOwner = current.owners.get(owner.clientId);
if (
!currentHost ||
currentHost.environmentId !== host.environmentId ||
currentHost.connectionId !== host.connectionId
!currentOwner ||
currentOwner.environmentId !== owner.environmentId ||
currentOwner.threadId !== owner.threadId
) {
return current;
}
const clients = new Map(current.clients);
const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
clients.set(host.clientId, {
...currentHost,
focused: host.focused,
focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
});
return { ...current, clients, focusSequence };
const owners = new Map(current.owners);
owners.delete(owner.clientId);
return { ...current, owners };
});
});
@@ -382,13 +286,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
)(function* (response) {
const pending = yield* SynchronizedRef.modify(state, (current) => {
const entry = current.pending.get(response.requestId);
if (
!entry ||
entry.context.clientId !== response.clientId ||
entry.context.connectionId !== response.connectionId
) {
return [undefined, current] as const;
}
if (!entry) return [undefined, current] as const;
const next = new Map(current.pending);
next.delete(response.requestId);
return [entry, { ...current, pending: next }] as const;
@@ -409,83 +307,29 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
): Effect.fn.Return<A, PreviewAutomationError> {
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const now = yield* Clock.currentTimeMillis;
const route = yield* SynchronizedRef.modify(state, (current) => {
const assignments = new Map(
Array.from(current.assignments).filter(([, assignment]) => {
const connection = current.clients.get(assignment.clientId);
return (
assignment.expiresAt > now &&
connection?.connectionId === assignment.connectionId &&
connection.queue === assignment.queue
);
}),
);
const assignmentKey = hostAssignmentKey(input.scope);
const assigned = assignments.get(assignmentKey);
const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
// Keep one provider session on one physical desktop runtime so a
// multi-step browser interaction cannot jump between independent
// Electron cookie/DOM state. A live assignment that predates an
// operation is not silently moved to a newer client: the caller gets a
// capability failure and can deliberately start a fresh provider
// session. A dead lease is pruned above and may fail over.
const connection =
hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
? assignedConnection
: hasLiveAssignment
? undefined
: Array.from(current.clients.values())
.filter(
(host) =>
host.environmentId === input.scope.environmentId &&
supportsOperation(host, input.operation),
)
.sort(
(left, right) =>
right.supportedOperations.size - left.supportedOperations.size ||
Number(right.focused) - Number(left.focused) ||
right.focusOrder - left.focusOrder,
)[0];
if (!connection) {
if (!hasLiveAssignment) assignments.delete(assignmentKey);
return [undefined, { ...current, assignments }] as const;
const current = yield* SynchronizedRef.get(state);
const candidates = Array.from(current.owners.values())
.filter(
(owner) =>
owner.environmentId === input.scope.environmentId &&
owner.threadId === input.scope.threadId &&
owner.supportsAutomation,
)
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
const owner = candidates.find((candidate) => current.clients.has(candidate.clientId));
if (!owner) {
const disconnectedOwner = candidates[0];
if (disconnectedOwner) {
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: disconnectedOwner.clientId,
});
}
assignments.set(assignmentKey, {
clientId: connection.clientId,
connectionId: connection.connectionId,
queue: connection.queue,
expiresAt: input.scope.expiresAt,
});
const requestId = `preview-${current.requestSequence}`;
const tabId = input.tabId;
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
const context: PreviewAutomationRequestErrorContext = {
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: connection.clientId,
connectionId: connection.connectionId,
requestId,
...(tabId === undefined ? {} : { tabId }),
timeoutMs,
...selectorDiagnostics,
};
const pending = new Map(current.pending);
pending.set(requestId, { queue: connection.queue, deferred, context });
return [
{ connection, requestId, requestContext: context },
{ ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
] as const;
});
if (!route) {
return yield* new PreviewAutomationNoAvailableHostError({
return yield* new PreviewAutomationNoFocusedOwnerError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
@@ -493,7 +337,42 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
providerInstanceId: input.scope.providerInstanceId,
});
}
const { connection, requestId, requestContext } = route;
const connection = current.clients.get(owner.clientId);
if (!connection) {
return yield* new PreviewAutomationHostNotConnectedError({
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
});
}
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const [requestId, requestContext] = yield* SynchronizedRef.modify(state, (next) => {
const requestId = `preview-${next.requestSequence}`;
const tabId = input.tabId ?? owner.tabId ?? undefined;
const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
const context: PreviewAutomationRequestErrorContext = {
operation: input.operation,
environmentId: input.scope.environmentId,
threadId: input.scope.threadId,
providerSessionId: input.scope.providerSessionId,
providerInstanceId: input.scope.providerInstanceId,
clientId: owner.clientId,
requestId,
...(tabId === undefined ? {} : { tabId }),
timeoutMs,
...selectorDiagnostics,
};
const pending = new Map(next.pending);
pending.set(requestId, { queue: connection.queue, deferred, context });
return [
[requestId, context] as const,
{ ...next, pending, requestSequence: next.requestSequence + 1 },
] as const;
});
const removePending = SynchronizedRef.update(state, (next) => {
if (!next.pending.has(requestId)) return next;
const pending = new Map(next.pending);
@@ -502,16 +381,12 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
});
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
const offered = yield* Queue.offer(connection.queue, {
type: "request",
connectionId: connection.connectionId,
request: {
requestId,
threadId: input.scope.threadId,
tabId: requestContext.tabId,
operation: input.operation,
input: input.input,
timeoutMs,
},
requestId,
threadId: input.scope.threadId,
tabId: requestContext.tabId,
operation: input.operation,
input: input.input,
timeoutMs,
});
if (!offered) {
const completion = yield* Deferred.poll(deferred);
@@ -529,7 +404,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
});
return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
export const layer = Layer.effect(PreviewAutomationBroker, make);
@@ -3,7 +3,6 @@ import type {
PreviewAutomationOperation,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationResizeResult,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -40,8 +39,6 @@ const handlers = {
reuseExistingTab: input.reuseExistingTab ?? true,
}),
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
preview_resize: (input) =>
invoke<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
+1 -18
View File
@@ -7,8 +7,6 @@ import {
PreviewAutomationPressInput,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationResizeInput,
PreviewAutomationResizeResult,
PreviewAutomationScrollInput,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
@@ -37,7 +35,7 @@ const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
export const PreviewStatusTool = Tool.make("preview_status", {
description:
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size.",
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
success: PreviewAutomationStatus,
failure: PreviewAutomationError,
dependencies,
@@ -71,19 +69,6 @@ export const PreviewNavigateTool = safeBrowserTool(
}).annotate(Tool.Title, "Navigate browser preview"),
);
export const PreviewResizeTool = safeBrowserTool(
Tool.make("preview_resize", {
description:
"Set the active collaborative browser tab to fill-panel sizing, an independently resizable freeform size, or a Chrome-standard device preset. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
parameters: PreviewAutomationResizeInput,
success: PreviewAutomationResizeResult,
failure: PreviewAutomationError,
dependencies,
})
.annotate(Tool.Title, "Resize browser viewport")
.annotate(Tool.Idempotent, true),
);
export const PreviewSnapshotTool = readonlyBrowserTool(
Tool.make("preview_snapshot", {
description:
@@ -183,7 +168,6 @@ export const PreviewToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewSnapshotTool,
PreviewClickTool,
PreviewTypeTool,
@@ -199,7 +183,6 @@ export const PreviewStandardToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewResizeTool,
PreviewClickTool,
PreviewTypeTool,
PreviewPressTool,
@@ -1,439 +0,0 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { AuthClientMetadataDeviceType, AuthConnectClientStatus } from "@t3tools/contracts";
import {
type AuthConnectClientRepositoryError,
PersistenceDecodeError,
type PersistenceErrorCorrelation,
PersistenceSqlError,
} from "./Errors.ts";
export const AuthConnectClientMetadataRecord = Schema.Struct({
label: Schema.NullOr(Schema.String),
ipAddress: Schema.NullOr(Schema.String),
userAgent: Schema.NullOr(Schema.String),
deviceType: AuthClientMetadataDeviceType,
os: Schema.NullOr(Schema.String),
browser: Schema.NullOr(Schema.String),
});
export type AuthConnectClientMetadataRecord = typeof AuthConnectClientMetadataRecord.Type;
export const AuthConnectClientRecord = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
status: AuthConnectClientStatus,
client: AuthConnectClientMetadataRecord,
requestedAt: Schema.DateTimeUtcFromString,
updatedAt: Schema.DateTimeUtcFromString,
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
export type AuthConnectClientRecord = typeof AuthConnectClientRecord.Type;
export const UpsertAuthConnectClientRequestInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
client: AuthConnectClientMetadataRecord,
requestedAt: Schema.DateTimeUtcFromString,
});
export type UpsertAuthConnectClientRequestInput = typeof UpsertAuthConnectClientRequestInput.Type;
export const UpdateAuthConnectClientStatusInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
status: Schema.Literals(["approved", "rejected"]),
decidedAt: Schema.DateTimeUtcFromString,
});
export type UpdateAuthConnectClientStatusInput = typeof UpdateAuthConnectClientStatusInput.Type;
export const RevokeAuthConnectClientInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
revokedAt: Schema.DateTimeUtcFromString,
});
export type RevokeAuthConnectClientInput = typeof RevokeAuthConnectClientInput.Type;
export const MarkAuthConnectClientSeenInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
seenAt: Schema.DateTimeUtcFromString,
});
export type MarkAuthConnectClientSeenInput = typeof MarkAuthConnectClientSeenInput.Type;
export class AuthConnectClientRepository extends Context.Service<
AuthConnectClientRepository,
{
readonly upsertRequest: (
input: UpsertAuthConnectClientRequestInput,
) => Effect.Effect<AuthConnectClientRecord, AuthConnectClientRepositoryError>;
readonly updateStatus: (
input: UpdateAuthConnectClientStatusInput,
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
readonly revoke: (
input: RevokeAuthConnectClientInput,
) => Effect.Effect<boolean, AuthConnectClientRepositoryError>;
readonly markSeen: (
input: MarkAuthConnectClientSeenInput,
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthConnectClientRecord>,
AuthConnectClientRepositoryError
>;
}
>()("t3/persistence/AuthConnectClients/AuthConnectClientRepository") {}
const AuthConnectClientDbRow = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
status: AuthConnectClientStatus,
clientLabel: Schema.NullOr(Schema.String),
clientIpAddress: Schema.NullOr(Schema.String),
clientUserAgent: Schema.NullOr(Schema.String),
clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
clientOs: Schema.NullOr(Schema.String),
clientBrowser: Schema.NullOr(Schema.String),
requestedAt: Schema.DateTimeUtcFromString,
updatedAt: Schema.DateTimeUtcFromString,
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
const AuthConnectClientRawDbRow = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.Unknown,
deviceId: Schema.Unknown,
status: Schema.Unknown,
clientLabel: Schema.Unknown,
clientIpAddress: Schema.Unknown,
clientUserAgent: Schema.Unknown,
clientDeviceType: Schema.Unknown,
clientOs: Schema.Unknown,
clientBrowser: Schema.Unknown,
requestedAt: Schema.Unknown,
updatedAt: Schema.Unknown,
approvedAt: Schema.Unknown,
rejectedAt: Schema.Unknown,
revokedAt: Schema.Unknown,
lastSeenAt: Schema.Unknown,
});
const decodeAuthConnectClientDbRow = Schema.decodeUnknownEffect(AuthConnectClientDbRow);
function toAuthConnectClientRecord(
row: typeof AuthConnectClientDbRow.Type,
): AuthConnectClientRecord {
return {
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
cloudUserId: row.cloudUserId,
deviceId: row.deviceId,
status: row.status,
client: {
label: row.clientLabel,
ipAddress: row.clientIpAddress,
userAgent: row.clientUserAgent,
deviceType: row.clientDeviceType,
os: row.clientOs,
browser: row.clientBrowser,
},
requestedAt: row.requestedAt,
updatedAt: row.updatedAt,
approvedAt: row.approvedAt,
rejectedAt: row.rejectedAt,
revokedAt: row.revokedAt,
lastSeenAt: row.lastSeenAt,
};
}
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
correlation?: PersistenceErrorCorrelation,
) {
return (cause: unknown): AuthConnectClientRepositoryError =>
Schema.isSchemaError(cause)
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
: new PersistenceSqlError({
operation: sqlOperation,
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
const rowSelection = `
client_proof_key_thumbprint AS "clientProofKeyThumbprint",
cloud_user_id AS "cloudUserId",
device_id AS "deviceId",
status AS "status",
client_label AS "clientLabel",
client_ip_address AS "clientIpAddress",
client_user_agent AS "clientUserAgent",
client_device_type AS "clientDeviceType",
client_os AS "clientOs",
client_browser AS "clientBrowser",
requested_at AS "requestedAt",
updated_at AS "updatedAt",
approved_at AS "approvedAt",
rejected_at AS "rejectedAt",
revoked_at AS "revokedAt",
last_seen_at AS "lastSeenAt"
`;
export const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertRequestRow = SqlSchema.findOne({
Request: UpsertAuthConnectClientRequestInput,
Result: AuthConnectClientRawDbRow,
execute: (input) =>
sql`
INSERT INTO auth_connect_clients (
client_proof_key_thumbprint,
cloud_user_id,
device_id,
status,
client_label,
client_ip_address,
client_user_agent,
client_device_type,
client_os,
client_browser,
requested_at,
updated_at,
approved_at,
rejected_at,
revoked_at,
last_seen_at
)
VALUES (
${input.clientProofKeyThumbprint},
${input.cloudUserId},
${input.deviceId},
'pending',
${input.client.label},
${input.client.ipAddress},
${input.client.userAgent},
${input.client.deviceType},
${input.client.os},
${input.client.browser},
${input.requestedAt},
${input.requestedAt},
NULL,
NULL,
NULL,
NULL
)
ON CONFLICT(client_proof_key_thumbprint) DO UPDATE SET
cloud_user_id = excluded.cloud_user_id,
device_id = excluded.device_id,
status = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.status
ELSE 'pending'
END,
client_label = excluded.client_label,
client_ip_address = excluded.client_ip_address,
client_user_agent = excluded.client_user_agent,
client_device_type = excluded.client_device_type,
client_os = excluded.client_os,
client_browser = excluded.client_browser,
requested_at = excluded.requested_at,
updated_at = excluded.updated_at,
approved_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.approved_at
ELSE NULL
END,
rejected_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.rejected_at
ELSE NULL
END,
last_seen_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.last_seen_at
ELSE NULL
END,
revoked_at = NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const updateStatusRow = SqlSchema.findOneOption({
Request: UpdateAuthConnectClientStatusInput,
Result: AuthConnectClientRawDbRow,
execute: ({ clientProofKeyThumbprint, status, decidedAt }) =>
sql`
UPDATE auth_connect_clients
SET
status = ${status},
updated_at = ${decidedAt},
approved_at = CASE WHEN ${status} = 'approved' THEN ${decidedAt} ELSE approved_at END,
rejected_at = CASE WHEN ${status} = 'rejected' THEN ${decidedAt} ELSE rejected_at END,
revoked_at = NULL
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND revoked_at IS NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const revokeRow = SqlSchema.findAll({
Request: RevokeAuthConnectClientInput,
Result: Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
execute: ({ clientProofKeyThumbprint, revokedAt }) =>
sql`
UPDATE auth_connect_clients
SET
revoked_at = ${revokedAt},
updated_at = ${revokedAt}
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND revoked_at IS NULL
RETURNING client_proof_key_thumbprint AS "clientProofKeyThumbprint"
`,
});
const markSeenRow = SqlSchema.findOneOption({
Request: MarkAuthConnectClientSeenInput,
Result: AuthConnectClientRawDbRow,
execute: ({ clientProofKeyThumbprint, seenAt }) =>
sql`
UPDATE auth_connect_clients
SET
last_seen_at = ${seenAt},
updated_at = ${seenAt}
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND status = 'approved'
AND revoked_at IS NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const listRows = SqlSchema.findAll({
Request: Schema.Void,
Result: AuthConnectClientRawDbRow,
execute: () =>
sql`
SELECT ${sql.unsafe(rowSelection)}
FROM auth_connect_clients
WHERE revoked_at IS NULL
ORDER BY
CASE status
WHEN 'pending' THEN 0
WHEN 'approved' THEN 1
ELSE 2
END,
updated_at DESC,
client_proof_key_thumbprint DESC
`,
});
const decodeRow = (
row: typeof AuthConnectClientRawDbRow.Type,
operation: string,
): Effect.Effect<AuthConnectClientRecord, PersistenceDecodeError> =>
decodeAuthConnectClientDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(operation, cause, {
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
}),
),
Effect.map(toAuthConnectClientRecord),
);
const upsertRequest: AuthConnectClientRepository["Service"]["upsertRequest"] = (input) =>
upsertRequestRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.upsertRequest:query",
"AuthConnectClientRepository.upsertRequest:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((row) =>
decodeRow(row, "AuthConnectClientRepository.upsertRequest:decodeRow"),
),
);
const updateStatus: AuthConnectClientRepository["Service"]["updateStatus"] = (input) =>
updateStatusRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.updateStatus:query",
"AuthConnectClientRepository.updateStatus:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRow(row, "AuthConnectClientRepository.updateStatus:decodeRow").pipe(
Effect.map(Option.some),
),
}),
),
);
const revoke: AuthConnectClientRepository["Service"]["revoke"] = (input) =>
revokeRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.revoke:query",
"AuthConnectClientRepository.revoke:decodeRows",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.map((rows) => rows.length > 0),
);
const markSeen: AuthConnectClientRepository["Service"]["markSeen"] = (input) =>
markSeenRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.markSeen:query",
"AuthConnectClientRepository.markSeen:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRow(row, "AuthConnectClientRepository.markSeen:decodeRow").pipe(
Effect.map(Option.some),
),
}),
),
);
const listActive: AuthConnectClientRepository["Service"]["listActive"] = () =>
listRows().pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.listActive:query",
"AuthConnectClientRepository.listActive:decodeRows",
),
),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeRow(row, "AuthConnectClientRepository.listActive:decodeRows"),
),
),
);
return {
upsertRequest,
updateStatus,
revoke,
markSeen,
listActive,
} satisfies AuthConnectClientRepository["Service"];
});
export const layer = Layer.effect(AuthConnectClientRepository, make);
-2
View File
@@ -23,7 +23,6 @@ export const PersistenceErrorCorrelation = Schema.Union([
Schema.Struct({ sessionId: Schema.String }),
Schema.Struct({ currentSessionId: Schema.String }),
Schema.Struct({ pairingLinkId: Schema.String }),
Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
Schema.Struct({ threadId: Schema.String }),
]);
export type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;
@@ -135,6 +134,5 @@ export type OrchestrationCommandReceiptRepositoryError =
export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthConnectClientRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
@@ -45,7 +45,6 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_AuthConnectClientApprovals.ts";
/**
* Migration loader with all migrations defined inline.
@@ -90,7 +89,6 @@ export const migrationEntries = [
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "AuthConnectClientApprovals", Migration0033],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -1,37 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS auth_connect_clients (
client_proof_key_thumbprint TEXT PRIMARY KEY,
cloud_user_id TEXT NOT NULL,
device_id TEXT,
status TEXT NOT NULL,
client_label TEXT,
client_ip_address TEXT,
client_user_agent TEXT,
client_device_type TEXT NOT NULL DEFAULT 'unknown',
client_os TEXT,
client_browser TEXT,
requested_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
approved_at TEXT,
rejected_at TEXT,
revoked_at TEXT,
last_seen_at TEXT
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_active
ON auth_connect_clients(revoked_at, status, updated_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_cloud_user
ON auth_connect_clients(cloud_user_id, revoked_at)
`;
});
-55
View File
@@ -151,61 +151,6 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
}),
);
it.effect("resizes a tab and preserves its viewport across navigation reports", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
const resized = yield* manager.resize({
threadId,
tabId: opened.tabId,
viewport: { _tag: "freeform", width: 1024, height: 768 },
});
expect(resized.viewport).toEqual({ _tag: "freeform", width: 1024, height: 768 });
const navigated = yield* manager.navigate({
threadId,
tabId: opened.tabId,
url: "http://localhost:5173/resized",
});
expect(navigated.viewport).toEqual(resized.viewport);
yield* manager.reportStatus({
threadId,
tabId: opened.tabId,
navStatus: { _tag: "Success", url: "http://localhost:5173/resized", title: "Resized" },
canGoBack: true,
canGoForward: false,
});
const listed = yield* manager.list({ threadId });
expect(listed.sessions[0]?.viewport).toEqual(resized.viewport);
const events = yield* collector.drain;
expect(events.map((event) => event.type)).toEqual([
"opened",
"resized",
"navigated",
"navigated",
]);
}),
);
it.effect("rejects resize for an unknown tab", () =>
Effect.gen(function* () {
const manager = yield* PreviewManager.PreviewManager;
const error = yield* Effect.flip(
manager.resize({
threadId: freshThreadId(),
tabId: "tab_missing",
viewport: { _tag: "fill" },
}),
);
expect(error._tag).toBe("PreviewSessionLookupError");
}),
);
it.effect("reportStatus emits failed for LoadFailed nav", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
-38
View File
@@ -20,8 +20,6 @@ import {
type PreviewOpenInput,
type PreviewRefreshInput,
type PreviewReportStatusInput,
type PreviewResizeInput,
FILL_PREVIEW_VIEWPORT,
PreviewSessionLookupError,
type PreviewSessionSnapshot,
} from "@t3tools/contracts";
@@ -47,9 +45,6 @@ export class PreviewManager extends Context.Service<
input: PreviewNavigateInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
readonly resize: (
input: PreviewResizeInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
@@ -119,7 +114,6 @@ const buildLoadingSnapshot = (input: {
navStatus: { _tag: "Loading", url: input.url, title: input.title },
canGoBack: false,
canGoForward: false,
viewport: FILL_PREVIEW_VIEWPORT,
updatedAt: input.updatedAt,
});
@@ -133,7 +127,6 @@ const buildIdleSnapshot = (input: {
navStatus: { _tag: "Idle" },
canGoBack: false,
canGoForward: false,
viewport: FILL_PREVIEW_VIEWPORT,
updatedAt: input.updatedAt,
});
@@ -244,7 +237,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
navStatus: { _tag: "Success", url, title: resolvedTitle },
canGoBack: session.snapshot.canGoBack,
canGoForward: session.snapshot.canGoForward,
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
updatedAt,
};
return {
@@ -277,7 +269,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
navStatus: input.navStatus,
canGoBack: input.canGoBack,
canGoForward: input.canGoForward,
viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
updatedAt,
};
const emit: PreviewEvent =
@@ -308,34 +299,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
);
});
const resize: PreviewManager["Service"]["resize"] = Effect.fn("PreviewManager.resize")(
function* (input) {
return yield* mutateExistingSession(
input.threadId,
input.tabId,
Effect.fn("PreviewManager.resizeSession")(function* (session) {
const updatedAt = yield* currentIsoTimestamp;
const snapshot: PreviewSessionSnapshot = {
...session.snapshot,
viewport: input.viewport,
updatedAt,
};
return {
next: { ...session, snapshot },
emit: {
type: "resized",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
snapshot,
},
result: snapshot,
};
}),
);
},
);
const refresh: PreviewManager["Service"]["refresh"] = Effect.fn("PreviewManager.refresh")(
function* (input) {
// Verify the session exists; the desktop bridge handles the actual reload
@@ -397,7 +360,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
open,
navigate,
reportStatus,
resize,
refresh,
close,
list,
@@ -113,23 +113,6 @@ async function waitForFileContent(filePath: string, attempts = 40) {
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
function waitForJsonLogMatch(
filePath: string,
predicate: (entry: Record<string, unknown>) => boolean,
attempts = 40,
) {
return Effect.gen(function* () {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const requests = yield* Effect.promise(() => readJsonLines(filePath));
if (requests.some(predicate)) {
return requests;
}
yield* Effect.yieldNow;
}
return yield* Effect.promise(() => readJsonLines(filePath));
});
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
@@ -1021,10 +1004,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
assert.equal(turnCompleted.payload.stopReason, "cancelled");
}
const requests = yield* waitForJsonLogMatch(
requestLogPath,
(entry) => entry.method === "session/cancel",
);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
assert.isTrue(
requests.some(
@@ -785,9 +785,6 @@ export function makeCursorAdapter(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "EventStreamBarrier":
yield* Deferred.succeed(event.acknowledge, undefined);
return;
case "ModeChanged":
return;
case "AssistantItemStarted":
@@ -4,7 +4,6 @@ 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";
@@ -25,11 +24,7 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -298,18 +293,6 @@ 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", () => {
@@ -355,11 +338,12 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: cursorAcpDiscoveryFailedMessage,
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
}),
).toMatchObject({
status: "error",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
models: [
{
slug: "claude-sonnet-4-6",
@@ -427,28 +411,10 @@ 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 runNode(
const provider = await Effect.runPromise(
checkCursorProviderStatus(
{
enabled: true,
@@ -460,7 +426,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
),
).pipe(Effect.provide(NodeServices.layer)),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -477,13 +443,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await runNode(
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.scoped),
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -499,13 +465,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await runNode(
await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}),
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,13 +62,6 @@ 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,
@@ -615,14 +608,6 @@ 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;
@@ -1035,7 +1020,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1094,7 +1079,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_MESSAGE;
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
} 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) {
@@ -10,23 +10,20 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import {
ApprovalRequestId,
GrokSettings,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TurnId,
ProviderInstanceId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
import { makeGrokAdapter } from "./GrokAdapter.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -48,11 +45,7 @@ exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
return wrapperPath;
}
function waitForFileContent(
filePath: string,
attempts = 40,
expectedContent?: string,
): Effect.Effect<string> {
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
Effect.gen(function* () {
if (remainingAttempts <= 0) {
@@ -61,10 +54,7 @@ function waitForFileContent(
const raw = yield* Effect.tryPromise(() => NodeFSP.readFile(filePath, "utf8")).pipe(
Effect.orElseSucceed(() => ""),
);
if (
raw.trim().length > 0 &&
(expectedContent === undefined || raw.includes(expectedContent))
) {
if (raw.trim().length > 0) {
return raw;
}
yield* Effect.sleep("25 millis");
@@ -89,39 +79,6 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
it("requires a settlement to match the live Grok turn", () => {
const staleTurnId = TurnId.make("stale-turn");
const replacementTurnId = TurnId.make("replacement-turn");
assert.isFalse(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "session-1",
expectedAcpSessionId: "session-1",
liveActiveTurnId: replacementTurnId,
liveSessionActiveTurnId: replacementTurnId,
turnId: staleTurnId,
}),
);
assert.isFalse(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "replacement-session",
expectedAcpSessionId: "stale-session",
liveActiveTurnId: staleTurnId,
liveSessionActiveTurnId: staleTurnId,
turnId: staleTurnId,
}),
);
assert.isTrue(
grokPromptSettlementBelongsToContext({
liveAcpSessionId: "session-1",
expectedAcpSessionId: "session-1",
liveActiveTurnId: staleTurnId,
liveSessionActiveTurnId: staleTurnId,
turnId: staleTurnId,
}),
);
});
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
Effect.gen(function* () {
@@ -218,783 +175,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
}),
);
it.effect("reports a Grok session running only while the prompt is in flight", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-session-ready-after-prompt");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_TOOL_CALLS: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const requestOpened =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "request.opened" }>>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "request.opened"
? Deferred.succeed(requestOpened, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "approval-required",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "check lifecycle", attachments: [] })
.pipe(Effect.forkChild);
const requestOpenedEvent = yield* Deferred.await(requestOpened);
const runningSessions = yield* adapter.listSessions();
const runningSession = runningSessions.find((session) => session.threadId === threadId);
assert.equal(runningSession?.status, "running");
assert.isDefined(runningSession?.activeTurnId);
yield* adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(requestOpenedEvent.requestId)),
"accept",
);
yield* Fiber.join(sendTurnFiber);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("restores ready without completing an unstarted turn when preparation fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-preparation-failure-while-connecting");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: "prepare invalid attachment",
attachments: [
{
type: "image",
id: "missing-image",
name: "missing.png",
mimeType: "image/png",
sizeBytes: 1,
},
],
}),
);
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(error._tag, "ProviderAdapterRequestError");
assert.isUndefined(turnCompletedEvent);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("completes a Grok turn from xAI prompt completion when the prompt RPC hangs", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-prompt-complete-fallback");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnResult = yield* adapter.sendTurn({
threadId,
input: "exercise fallback",
attachments: [],
});
yield* Deferred.await(turnCompleted);
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
const eventTypes = runtimeEvents.map((event) => event.type);
const content = runtimeEvents
.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "content.delta" }> =>
event.type === "content.delta" && String(event.threadId) === String(threadId),
)
.map((event) => event.payload.delta)
.join("");
const terminalIndex = runtimeEvents.findIndex(
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const turnOutputTypes = new Set([
"content.delta",
"item.started",
"item.updated",
"item.completed",
"turn.plan.updated",
]);
const outputAfterTerminal = runtimeEvents
.slice(terminalIndex + 1)
.filter(
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
);
const toolTitles = runtimeEvents.flatMap((event) =>
event.type === "item.updated" && event.payload.title ? [event.payload.title] : [],
);
assert.equal(sendTurnResult.threadId, threadId);
assert.include(eventTypes, "turn.completed");
assert.equal(content, "hello from mock");
assert.isAtLeast(terminalIndex, 0);
assert.deepEqual(outputAfterTerminal, []);
assert.notInclude(toolTitles, "Child-only tool");
assert.equal(turnCompletedEvent?.payload.stopReason, "end_turn");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const contentDelta = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "interrupt after prompt",
attachments: [],
})
.pipe(Effect.forkChild);
yield* Deferred.await(contentDelta);
for (let yieldAttempt = 0; yieldAttempt < 6; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
yield* Fiber.interrupt(sendTurnFiber);
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const snapshot = yield* adapter.readThread(threadId);
assert.equal(snapshot.turns.length, 1);
assert.equal(snapshot.turns[0]?.items.length, 1);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("does not report a synthetic stop reason when xAI omits one", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-prompt-complete-missing-stop-reason");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({
threadId,
input: "exercise missing stop reason",
attachments: [],
});
yield* Deferred.await(turnCompleted);
const turnCompletedEvent = runtimeEvents.find(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed",
);
assert.equal(turnCompletedEvent?.payload.state, "completed");
assert.isNull(turnCompletedEvent?.payload.stopReason);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("lets Stop unblock a fully silent Grok prompt and accept a follow-up turn", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-after-full-silence");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* Effect.gen(function* () {
yield* Effect.sleep("500 millis");
yield* adapter.interruptTurn(threadId);
}).pipe(Effect.forkChild({ startImmediately: true }));
yield* adapter.sendTurn({
threadId,
input: "hang forever",
attachments: [],
});
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const cancelledEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.lengthOf(cancelledEvents, 1);
assert.equal(cancelledEvents[0]?.payload.state, "cancelled");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
const followUpEventsBefore = runtimeEvents.length;
yield* adapter.sendTurn({
threadId,
input: "continue after stop",
attachments: [],
});
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const followUpCompletedEvents = runtimeEvents
.slice(followUpEventsBefore)
.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
assert.lengthOf(followUpCompletedEvents, 1);
assert.equal(followUpCompletedEvents[0]?.payload.state, "completed");
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("does not let a cancelled prompt settlement consume the follow-up prompt slot", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-cancelled-settlement-before-follow-up");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-cancel-race-")),
);
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const firstTurnStarted = yield* Deferred.make<TurnId>();
const twoTurnsCompleted = yield* Deferred.make<void>();
const completedCountRef = yield* Ref.make(0);
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "turn.started" && event.turnId !== undefined) {
yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
return;
}
if (event.type !== "turn.completed") {
return;
}
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
if (completedCount === 2) {
yield* Deferred.succeed(twoTurnsCompleted, undefined);
}
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const firstSendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "cancel this prompt", attachments: [] })
.pipe(Effect.forkChild);
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
const followUp = yield* adapter
.sendTurn({ threadId, input: "complete the follow-up", attachments: [] })
.pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("2 seconds"));
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
const turnCompletedEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.notEqual(String(followUp.turnId), String(firstTurnId));
assert.deepEqual(
turnCompletedEvents.map((event) => [String(event.turnId), event.payload.state]),
[
[String(firstTurnId), "cancelled"],
[String(followUp.turnId), "completed"],
],
);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("drops late ACP notifications after a turn is cancelled", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_HANG_PROMPT_FOREVER: "1",
T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1",
}),
);
const lateNativeUpdate = yield* Deferred.make<void>();
const adapter = yield* makeTestAdapter(wrapperPath, {
nativeEventLogger: {
filePath: "memory://grok-cancelled-native-events",
write: (record: unknown) =>
JSON.stringify(record).includes("late after cancel")
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
: Effect.void,
close: () => Effect.void,
},
});
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnStarted = yield* Deferred.make<TurnId>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.started" &&
event.turnId !== undefined &&
String(event.threadId) === String(threadId)
? Deferred.succeed(turnStarted, event.turnId).pipe(Effect.asVoid)
: Effect.void,
),
),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "cancel before the late update", attachments: [] })
.pipe(Effect.forkChild);
const turnId = yield* Deferred.await(turnStarted).pipe(Effect.timeout("2 seconds"));
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
yield* Deferred.await(lateNativeUpdate).pipe(Effect.timeout("2 seconds"));
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
const cancelledIndex = runtimeEvents.findIndex(
(event) =>
event.type === "turn.completed" &&
String(event.threadId) === String(threadId) &&
String(event.turnId) === String(turnId) &&
event.payload.state === "cancelled",
);
const turnOutputTypes = new Set([
"content.delta",
"item.started",
"item.updated",
"item.completed",
"turn.plan.updated",
]);
const outputAfterCancellation = runtimeEvents
.slice(cancelledIndex + 1)
.filter(
(event) => String(event.threadId) === String(threadId) && turnOutputTypes.has(event.type),
);
assert.isAtLeast(cancelledIndex, 0);
assert.deepEqual(outputAfterCancellation, []);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}).pipe(TestClock.withLive),
);
it.effect("lets Stop cancel during the xAI completion drain window", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-during-completion-drain");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const activeTurnIdRef = yield* Ref.make<TurnId | undefined>(undefined);
const trailingChunkTurnId = yield* Deferred.make<TurnId>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.gen(function* () {
runtimeEvents.push(event);
if (String(event.threadId) !== String(threadId)) {
return;
}
if (event.type === "turn.started") {
yield* Ref.set(activeTurnIdRef, event.turnId);
}
if (event.type !== "content.delta" || event.payload.delta !== "mock") {
return;
}
const turnId = event.turnId ?? (yield* Ref.get(activeTurnIdRef));
if (turnId === undefined) {
return;
}
yield* Deferred.succeed(trailingChunkTurnId, turnId).pipe(Effect.ignore);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "cancel during completion drain",
attachments: [],
})
.pipe(Effect.forkChild);
const turnId = yield* Deferred.await(trailingChunkTurnId).pipe(Effect.timeout("2 seconds"));
yield* adapter.interruptTurn(threadId, turnId).pipe(Effect.timeout("2 seconds"));
yield* Fiber.join(sendTurnFiber).pipe(Effect.timeout("2 seconds"));
const turnCompletedEvents = runtimeEvents.filter(
(event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
event.type === "turn.completed" && String(event.threadId) === String(threadId),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.lengthOf(turnCompletedEvents, 1);
assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("settles the in-flight prompt before emitting completion", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-completion-before-next-turn");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const completedCountRef = yield* Ref.make(0);
const secondTurnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (event.type !== "turn.completed" || String(event.threadId) !== String(threadId)) {
return Effect.void;
}
return Ref.modify(completedCountRef, (count) => {
const nextCount = count + 1;
return [nextCount, nextCount] as const;
}).pipe(
Effect.flatMap((count) => {
if (count === 1) {
return adapter
.sendTurn({
threadId,
input: "second turn after completion",
attachments: [],
})
.pipe(Effect.forkChild, Effect.asVoid);
}
if (count === 2) {
return Deferred.succeed(secondTurnCompleted, undefined).pipe(Effect.asVoid);
}
return Effect.void;
}),
);
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.sendTurn({
threadId,
input: "first turn",
attachments: [],
});
yield* Deferred.await(secondTurnCompleted);
const completedCount = yield* Ref.get(completedCountRef);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
assert.equal(completedCount, 2);
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("restores a Grok session to ready when the prompt RPC fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-prompt-failure-ready");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_FAIL_PROMPT: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: "fail prompt",
attachments: [],
}),
);
const readySessions = yield* adapter.listSessions();
const readySession = readySessions.find((session) => session.threadId === threadId);
const failedTurnCompleted = runtimeEvents.find(
(event) => event.type === "turn.completed" && event.threadId === threadId,
);
assert.equal(error._tag, "ProviderAdapterRequestError");
assert.equal(readySession?.status, "ready");
assert.isUndefined(readySession?.activeTurnId);
assert.equal(failedTurnCompleted?.type, "turn.completed");
if (failedTurnCompleted?.type === "turn.completed") {
assert.equal(failedTurnCompleted.payload.state, "failed");
assert.isString(failedTurnCompleted.payload.errorMessage);
}
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-load-replay-filter");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EMIT_LOAD_REPLAY: "1",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
).pipe(Effect.forkChild);
const session = yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
resumeCursor: { schemaVersion: 1, sessionId: "mock-session-1" },
});
yield* adapter.sendTurn({
threadId,
input: "after resume",
attachments: [],
});
assert.deepStrictEqual(session.resumeCursor, {
schemaVersion: 1,
sessionId: "mock-session-1",
});
assert.isFalse(
runtimeEvents.some(
(event) => event.type === "item.completed" && event.payload.title === "Replay tool",
),
);
assert.isFalse(
runtimeEvents.some(
(event) =>
event.type === "content.delta" && event.payload.delta === "replayed assistant text",
),
);
yield* Fiber.interrupt(runtimeEventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
@@ -1151,7 +331,6 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
assert.deepEqual(resolvedEvent.payload.answers, {
"Which scope should Grok use?": "Workspace",
});
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
yield* Fiber.join(sendTurnFiber);
yield* Fiber.interrupt(eventsFiber);
+56 -512
View File
@@ -22,7 +22,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
@@ -63,7 +62,6 @@ import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
promptResponseHasMissingXAiStopReason,
XAiAskUserQuestionRequest,
} from "../acp/XAiAcpExtension.ts";
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
@@ -110,8 +108,6 @@ interface GrokSessionContext {
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
interruptedTurnIds: Set<TurnId>;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
* continues it, and only the last remaining prompt settles the turn. */
@@ -140,38 +136,10 @@ function settlePendingUserInputsAsCancelled(
);
}
function appendPromptResultToTurn(
ctx: GrokSessionContext,
turnId: TurnId,
promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,
result: EffectAcpSchema.PromptResponse,
): void {
const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === turnId
? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }
: turn,
)
: [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
const resolveSessionCallbackTurnId = (
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
threadId: ThreadId,
): TurnId | undefined => {
const ctx = sessions.get(threadId);
return ctx ? resolveCallbackTurnId(ctx) : undefined;
};
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
if (!isRecord(raw)) return undefined;
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
@@ -202,28 +170,6 @@ function selectAutoApprovedPermissionOption(
);
}
function completedStopReasonFromPromptResponse(
response: EffectAcpSchema.PromptResponse | undefined,
): EffectAcpSchema.StopReason | null {
if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {
return null;
}
return response.stopReason;
}
export function grokPromptSettlementBelongsToContext(input: {
readonly liveAcpSessionId: string;
readonly expectedAcpSessionId: string;
readonly liveActiveTurnId: TurnId | undefined;
readonly liveSessionActiveTurnId: TurnId | undefined;
readonly turnId: TurnId;
}): boolean {
return (
input.liveAcpSessionId === input.expectedAcpSessionId &&
(input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)
);
}
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
@@ -294,144 +240,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
const settlePromptInFlight = (
threadId: ThreadId,
turnId: TurnId,
expectedAcpSessionId: string,
options?: {
readonly errorMessage?: string;
readonly completedStopReason?: EffectAcpSchema.StopReason | null;
readonly emitTurnCompletion?: boolean;
/** Interrupt/cancel: drop every outstanding prompt slot and settle once. */
readonly settleAllPrompts?: boolean;
},
) =>
Effect.gen(function* () {
const liveCtx = sessions.get(threadId);
if (!liveCtx) {
return;
}
const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({
liveAcpSessionId: liveCtx.acpSessionId,
expectedAcpSessionId,
liveActiveTurnId: liveCtx.activeTurnId,
liveSessionActiveTurnId: liveCtx.session.activeTurnId,
turnId,
});
if (!settlementBelongsToLiveContext) {
// interruptTurn already consumed every prompt slot for this turn. A
// late prompt result must neither emit a second terminal event nor
// consume a slot belonging to a newer turn on the same ACP session.
if (
liveCtx.acpSessionId !== expectedAcpSessionId ||
liveCtx.interruptedTurnIds.has(turnId)
) {
return;
}
if (options?.emitTurnCompletion !== false) {
if (options?.errorMessage !== undefined) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId,
payload: {
state: "failed",
errorMessage: options.errorMessage,
},
});
} else if (options?.completedStopReason !== undefined) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId,
payload: {
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
stopReason: options.completedStopReason ?? null,
},
});
}
}
return;
}
let settleTurnId = turnId;
if (options?.settleAllPrompts) {
liveCtx.promptsInFlight = 0;
if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {
const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;
if (!fallbackTurnId) {
if (liveCtx.session.status === "running" || liveCtx.session.status === "connecting") {
const updatedAt = yield* nowIso;
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
liveCtx.activeTurnId = undefined;
liveCtx.session = {
...readySession,
status: "ready",
updatedAt,
};
}
return;
}
settleTurnId = fallbackTurnId;
}
} else {
const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);
if (
remainingPrompts > 0 ||
liveCtx.activeTurnId !== settleTurnId ||
liveCtx.session.activeTurnId !== settleTurnId
) {
liveCtx.promptsInFlight = remainingPrompts;
return;
}
liveCtx.promptsInFlight = remainingPrompts;
}
const updatedAt = yield* nowIso;
const canEmitTurnCompletion =
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;
const shouldEmitCompletedTurn =
options?.completedStopReason !== undefined && canEmitTurnCompletion;
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
liveCtx.activeTurnId = undefined;
liveCtx.session = {
...readySession,
status: "ready",
updatedAt,
};
if (options?.emitTurnCompletion === false) {
return;
}
if (shouldEmitFailedTurn) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId: settleTurnId,
payload: {
state: "failed",
errorMessage: options.errorMessage,
},
});
} else if (shouldEmitCompletedTurn) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId,
turnId: settleTurnId,
payload: {
state: options.completedStopReason === "cancelled" ? "cancelled" : "completed",
stopReason: options.completedStopReason ?? null,
},
});
}
});
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
Effect.gen(function* () {
if (!nativeEventLogger) return;
@@ -463,8 +271,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const emitPlanUpdate = (
ctx: GrokSessionContext,
turnId: TurnId | undefined,
stamp: { readonly eventId: EventId; readonly createdAt: string },
payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
@@ -476,17 +282,17 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
method: string,
) =>
Effect.gen(function* () {
const fingerprint = `${turnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
ctx.lastPlanFingerprint = fingerprint;
yield* offerRuntimeEvent(
makeAcpPlanUpdatedEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId,
turnId: ctx.activeTurnId,
payload,
source: "acp.jsonrpc",
method,
@@ -618,14 +424,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const resolution = yield* Deferred.make<PendingUserInputResolution>();
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
pendingUserInputs.set(requestId, { resolution });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractXAiAskUserQuestions(params) },
raw: {
@@ -642,7 +447,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolvedAnswers },
raw: {
@@ -681,14 +486,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
pendingApprovals.set(requestId, { decision });
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
@@ -708,7 +512,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
@@ -774,7 +578,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
interruptedTurnIds: new Set(),
promptsInFlight: 0,
currentModelId: boundModelId,
stopped: false,
@@ -783,39 +586,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
if (event._tag === "EventStreamBarrier") {
yield* Deferred.succeed(event.acknowledge, undefined);
return;
}
if (
event._tag === "PlanUpdated" ||
event._tag === "ToolCallUpdated" ||
event._tag === "ContentDelta"
) {
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
}
if (event._tag === "ModeChanged") {
return;
}
const notificationTurnId = resolveNotificationTurnId(ctx);
if (
notificationTurnId === undefined ||
ctx.interruptedTurnIds.has(notificationTurnId)
) {
return;
}
const stamp = yield* makeEventStamp();
switch (event._tag) {
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
@@ -824,44 +602,40 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* emitPlanUpdate(
ctx,
notificationTurnId,
stamp,
event.payload,
event.rawPayload,
"session/update",
);
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp,
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: notificationTurnId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
@@ -923,15 +697,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
// Bind the turn id before cooperative yields so interruptTurn can
// settle this prompt even if stop arrives during preparation.
ctx.activeTurnId = turnId;
ctx.session = {
...ctx.session,
status: steeringTurnId === undefined ? "connecting" : "running",
activeTurnId: turnId,
updatedAt: yield* nowIso,
};
return yield* Effect.gen(function* () {
const turnModelSelection =
@@ -1000,27 +765,12 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
if (ctx.interruptedTurnIds.has(turnId)) {
yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {
completedStopReason: "cancelled",
emitTurnCompletion: false,
settleAllPrompts: true,
});
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok prompt was interrupted during preparation.",
});
}
ctx.activeTurnId = turnId;
if (steeringTurnId === undefined) {
ctx.lastPlanFingerprint = undefined;
}
ctx.session = {
...ctx.session,
status: "running",
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
@@ -1046,27 +796,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
};
}).pipe(
Effect.tapCause(() =>
Effect.gen(function* () {
const liveCtx = sessions.get(input.threadId);
if (!liveCtx) {
return;
}
yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {
errorMessage: "Grok prompt preparation failed.",
emitTurnCompletion: false,
});
Effect.sync(() => {
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
}),
),
);
}),
);
const promptSettled = yield* Ref.make(false);
const promptRpcSucceeded = yield* Ref.make(false);
const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(
undefined,
);
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
return yield* Effect.gen(function* () {
const result = yield* prepared.acp
@@ -1074,18 +810,6 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
prompt: prepared.promptParts,
})
.pipe(
Effect.tap((promptResult) =>
Effect.all([
Ref.set(promptRpcSucceeded, true),
Ref.set(promptResultRef, promptResult),
]),
),
Effect.tapError((error) =>
Ref.set(
promptFailureMessageRef,
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
).pipe(Effect.andThen(prepared.acp.drainEvents)),
),
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
@@ -1096,88 +820,38 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
errorMessage: "Grok session changed before the turn completed.",
settleAllPrompts: true,
},
);
yield* Ref.set(promptSettled, true);
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
// Keep prompt settlement atomic with respect to Stop and steering.
// interruptTurn marks its target before waiting for this lock, so
// cancellation can still win while queued ACP events are drained.
for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
yield* Effect.yieldNow;
}
yield* prepared.acp.drainEvents;
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
if (
ctx.promptsInFlight <= 0 ||
ctx.activeTurnId !== prepared.turnId ||
ctx.session.activeTurnId !== prepared.turnId
) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
ctx.turns = existingTurnRecord
? ctx.turns.map((turn) =>
turn.id === prepared.turnId
? {
...turn,
items: [...turn.items, { prompt: prepared.promptParts, result }],
}
: turn,
)
: [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
status: "running",
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);
ctx.promptsInFlight = remainingPrompts;
// Only the last remaining prompt settles the turn. A steer-
// superseded prompt resolving while another is in flight or
// pending must leave the merged turn running.
if (
remainingPrompts === 0 &&
ctx.activeTurnId === prepared.turnId &&
ctx.session.activeTurnId === prepared.turnId
) {
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
yield* Ref.set(promptSettled, true);
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}
const completedAt = yield* nowIso;
const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;
ctx.activeTurnId = undefined;
ctx.session = {
...readySession,
status: "ready",
updatedAt: completedAt,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
const completedStopReason = completedStopReasonFromPromptResponse(result);
// Only the last remaining prompt settles the turn — a steer-
// superseded prompt resolving (usually cancelled) while another
// is in flight or pending must leave the merged turn running.
if (ctx.promptsInFlight === 1) {
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
@@ -1186,13 +860,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: completedStopReason,
stopReason: result.stopReason ?? null,
},
});
ctx.interruptedTurnIds.delete(prepared.turnId);
yield* Ref.set(promptSettled, true);
} else if (remainingPrompts > 0) {
yield* Ref.set(promptSettled, true);
}
return {
@@ -1204,153 +874,27 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
);
}).pipe(
Effect.ensuring(
Effect.gen(function* () {
if (yield* Ref.get(promptSettled)) {
return;
Effect.sync(() => {
const liveCtx = sessions.get(input.threadId);
if (liveCtx) {
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
}
if (yield* Ref.get(promptRpcSucceeded)) {
const promptResult = yield* Ref.get(promptResultRef);
if (promptResult === undefined) {
return;
}
yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
errorMessage: "Grok session changed before the turn completed.",
settleAllPrompts: true,
},
);
return;
}
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
return;
}
if (
ctx.promptsInFlight <= 0 ||
ctx.activeTurnId !== prepared.turnId ||
ctx.session.activeTurnId !== prepared.turnId
) {
return;
}
appendPromptResultToTurn(
ctx,
prepared.turnId,
prepared.promptParts,
promptResult,
);
yield* settlePromptInFlight(
input.threadId,
prepared.turnId,
prepared.acpSessionId,
{
completedStopReason: completedStopReasonFromPromptResponse(promptResult),
},
);
}),
);
return;
}
const errorMessage = yield* Ref.get(promptFailureMessageRef);
yield* withThreadLock(
input.threadId,
settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {
errorMessage: errorMessage ?? "Grok prompt request failed.",
}),
);
}).pipe(Effect.catch(() => Effect.void)),
}),
),
);
});
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId, turnId) =>
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const observed = yield* Effect.sync(() => {
const ctx = sessions.get(threadId);
if (!ctx || ctx.stopped) {
return {
_tag: "Proceed" as const,
acpSessionId: undefined,
interruptedTurnId: turnId,
};
}
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
return { _tag: "Ignore" as const };
}
const interruptedTurnId = turnId ?? activeTurnId;
if (interruptedTurnId !== undefined) {
ctx.interruptedTurnIds.add(interruptedTurnId);
}
return {
_tag: "Proceed" as const,
acpSessionId: ctx.acpSessionId,
interruptedTurnId,
};
});
if (observed._tag === "Ignore") {
return;
}
yield* withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {
return;
}
const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;
if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {
return;
}
if (
observed.interruptedTurnId !== undefined &&
activeTurnId !== undefined &&
activeTurnId !== observed.interruptedTurnId
) {
return;
}
const interruptedTurnId =
observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
if (interruptedTurnId) {
ctx.interruptedTurnIds.add(interruptedTurnId);
yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {
completedStopReason: "cancelled",
settleAllPrompts: true,
});
} else if (
ctx.promptsInFlight > 0 ||
ctx.session.status === "running" ||
ctx.session.status === "connecting"
) {
const updatedAt = yield* nowIso;
ctx.promptsInFlight = 0;
ctx.activeTurnId = undefined;
const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;
ctx.session = {
...readySession,
status: "ready",
updatedAt,
};
}
}),
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
});
@@ -7,9 +7,6 @@ import * as NodeFS from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as TestClock from "effect/testing/TestClock";
import * as Stream from "effect/Stream";
import { describe, expect } from "vite-plus/test";
@@ -116,122 +113,6 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("drops session updates emitted for a child ACP session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(
notes
.filter((note) => note._tag === "ContentDelta")
.map((note) => note.text)
.join(""),
).toBe("root before child root after child");
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_FOREIGN_SESSION_UPDATES: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("supports successive standard ACP prompts", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" });
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("releases a fully silent prompt when session/cancel is requested", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
const promptFiber = yield* runtime
.prompt({
prompt: [{ type: "text", text: "hang forever" }],
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust("500 millis");
yield* runtime.cancel;
const firstPromptResult = yield* Fiber.join(promptFiber);
expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" });
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
},
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("segments assistant text around ACP tool calls", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
@@ -465,109 +346,6 @@ describe("AcpSessionRuntime", () => {
);
});
it.effect("fails session startup when session/load returns an error", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const error = yield* runtime.start().pipe(Effect.flip);
expect(error._tag).toBe("AcpRequestError");
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_FAIL_LOAD_SESSION: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "stale-session-id",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("ignores session/update replay notifications during session/load", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
"AssistantItemStarted",
"ContentDelta",
"AssistantItemCompleted",
]);
expect(notes.some((note) => note._tag === "ToolCallUpdated")).toBe(false);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_EMIT_LOAD_REPLAY: "1",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
),
);
it.effect("completes session/load after replay becomes idle while its RPC stays pending", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start().pipe(Effect.timeout("2 seconds"));
expect(started.sessionId).toBe("mock-session-1");
expect(started.sessionSetupResult._meta).toMatchObject({
t3SessionLoadReady: "replay_idle",
});
const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe(
Effect.timeoutOption("100 millis"),
);
expect(Option.isNone(unexpectedReplayEvent)).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
env: {
T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1",
T3_ACP_LOAD_SESSION_DELAY_MS: "10000",
},
},
cwd: process.cwd(),
resumeSessionId: "mock-session-1",
sessionLoadReplayIdleGap: "50 millis",
sessionLoadTimeout: "1 second",
clientInfo: { name: "t3-test", version: "0.0.0" },
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
TestClock.withLive,
),
);
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-"));
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
@@ -8,8 +8,6 @@ import {
parsePermissionRequest,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
syntheticLoadSessionResponseFromInitialize,
} from "./AcpRuntimeModel.ts";
describe("AcpRuntimeModel", () => {
@@ -61,95 +59,6 @@ describe("AcpRuntimeModel", () => {
expect(modelConfigId).toBe("model");
});
it("detects Grok session replay updates from _meta.isReplay", () => {
expect(
sessionUpdateIsReplay({
_meta: { isReplay: true },
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "replayed" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(true);
expect(
sessionUpdateIsReplay({
sessionId: "session-1",
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "live" },
},
} satisfies EffectAcpSchema.SessionNotification),
).toBe(false);
});
it("builds a synthetic load response from initialize model state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build" }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.currentModelId).toBe("grok-build");
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("accepts initialize model descriptions with null", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [{ modelId: "grok-build", name: "Grok Build", description: null }],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.models?.availableModels[0]?.description).toBeNull();
});
it("ignores malformed initialize model state in synthetic load responses", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modelState: {
currentModelId: "grok-build",
availableModels: [null],
},
modeState: {
currentModeId: "code",
availableModes: [{ id: "code", name: 12 }],
},
},
} as EffectAcpSchema.InitializeResponse);
expect(response.models).toBeUndefined();
expect(response.modes).toBeUndefined();
expect(response._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
});
it("builds a synthetic load response with initialize mode state", () => {
const response = syntheticLoadSessionResponseFromInitialize({
protocolVersion: 1,
_meta: {
modeState: {
currentModeId: "code",
availableModes: [
{ id: "ask", name: "Ask" },
{ id: "code", name: "Code" },
],
},
},
} satisfies EffectAcpSchema.InitializeResponse);
expect(response.modes?.currentModeId).toBe("code");
expect(response.modes?.availableModes).toHaveLength(2);
});
it("projects typed ACP tool call updates into runtime events", () => {
const created = parseSessionUpdateEvent({
sessionId: "session-1",
@@ -1,8 +1,3 @@
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import type * as EffectAcpSchema from "effect-acp/schema";
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
import type { ToolLifecycleItemType } from "@t3tools/contracts";
@@ -11,40 +6,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
if (!isRecord(value) || typeof value.currentModelId !== "string") {
return false;
}
if (!Array.isArray(value.availableModels)) {
return false;
}
return value.availableModels.every(
(model) =>
isRecord(model) &&
typeof model.modelId === "string" &&
typeof model.name === "string" &&
(model.description === undefined ||
model.description === null ||
typeof model.description === "string"),
);
}
function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
if (!isRecord(value) || typeof value.currentModeId !== "string") {
return false;
}
if (!Array.isArray(value.availableModes)) {
return false;
}
return value.availableModes.every(
(mode) =>
isRecord(mode) &&
typeof mode.id === "string" &&
typeof mode.name === "string" &&
(mode.description === undefined || typeof mode.description === "string"),
);
}
export interface AcpSessionMode {
readonly id: string;
readonly name: string;
@@ -453,58 +414,6 @@ export function parsePermissionRequest(
};
}
export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
const meta = params._meta;
return isRecord(meta) && meta.isReplay === true;
}
export interface SessionLoadGate {
readonly active: boolean;
readonly lastActivityAtMillis: number | undefined;
readonly idleGap: Duration.Duration;
readonly initializeResult: EffectAcpSchema.InitializeResponse;
}
export const waitForSessionLoadReplayIdle = (input: {
readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
Effect.gen(function* () {
const pollInterval = Duration.millis(25);
while (true) {
const gate = yield* Ref.get(input.gateRef);
if (
Option.isSome(gate) &&
gate.value.active &&
gate.value.lastActivityAtMillis !== undefined
) {
const idleGapMillis = Duration.toMillis(gate.value.idleGap);
const nowMillis = yield* Clock.currentTimeMillis;
if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
}
}
yield* Effect.sleep(pollInterval);
}
});
export function syntheticLoadSessionResponseFromInitialize(
initializeResult: EffectAcpSchema.InitializeResponse,
): EffectAcpSchema.LoadSessionResponse {
const meta = initializeResult._meta;
const modelState = isRecord(meta) ? meta.modelState : undefined;
const modeState = isRecord(meta) ? meta.modeState : undefined;
const models = isSessionModelState(modelState) ? modelState : undefined;
const modes = isSessionModeState(modeState) ? modeState : undefined;
return {
...(models ? { models } : {}),
...(modes ? { modes } : {}),
_meta: {
t3SessionLoadReady: "replay_idle",
},
};
}
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
readonly modeId?: string;
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
+46 -177
View File
@@ -1,16 +1,12 @@
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -27,9 +23,6 @@ import {
mergeToolCallState,
parseSessionModeState,
parseSessionUpdateEvent,
sessionUpdateIsReplay,
waitForSessionLoadReplayIdle,
type SessionLoadGate,
type AcpParsedSessionEvent,
type AcpSessionModeState,
type AcpToolCallState,
@@ -39,16 +32,6 @@ function formatConfigOptionValue(value: string | boolean): string {
return JSON.stringify(value);
}
export interface AcpSessionEventStreamBarrier {
readonly _tag: "EventStreamBarrier";
readonly acknowledge: Deferred.Deferred<void>;
}
export type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;
const defaultSessionLoadTimeout = Duration.seconds(90);
const defaultSessionLoadReplayIdleGap = Duration.seconds(2);
export interface AcpSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -60,8 +43,6 @@ export interface AcpSessionRuntimeOptions {
readonly spawn: AcpSpawnInput;
readonly cwd: string;
readonly resumeSessionId?: string;
readonly sessionLoadTimeout?: Duration.Input;
readonly sessionLoadReplayIdleGap?: Duration.Input;
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
readonly clientInfo: {
readonly name: string;
@@ -179,9 +160,7 @@ export class AcpSessionRuntime extends Context.Service<
*/
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
/** Stream of parsed ACP session events emitted after startup. */
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
/** Waits until the current event consumer has processed every queued event. */
readonly drainEvents: Effect.Effect<void>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
/** Latest mode state observed from session setup and `session/update` notifications. */
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
/** Latest configuration options observed from session setup and configuration writes. */
@@ -275,17 +254,12 @@ export const make = (
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
const promptSerializationSemaphore = yield* Semaphore.make(1);
const activePromptFiberRef = yield* Ref.make<
Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>
>(Option.none());
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
const logRequest = (event: AcpSessionRequestLogEvent) =>
options.requestLogger ? options.requestLogger(event) : Effect.void;
@@ -357,40 +331,15 @@ export const make = (
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
yield* acp.handleSessionUpdate((notification) =>
Effect.gen(function* () {
const gate = yield* Ref.get(sessionLoadGateRef);
if (Option.isSome(gate) && gate.value.active) {
const lastActivityAtMillis = yield* Clock.currentTimeMillis;
yield* Ref.set(
sessionLoadGateRef,
Option.some({
...gate.value,
lastActivityAtMillis,
}),
);
return;
}
if (sessionUpdateIsReplay(notification)) {
return;
}
const startState = yield* Ref.get(startStateRef);
// One runtime projects one root ACP session. Child-session updates need
// explicit lineage routing and must never be flattened into this stream.
if (
startState._tag !== "Started" ||
notification.sessionId !== startState.result.sessionId
) {
return;
}
yield* handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
});
handleSessionUpdate({
queue: eventQueue,
modeStateRef,
toolCallsRef,
assistantSegmentRef,
params: notification,
}),
);
const initializeClientCapabilities = {
fs: {
readTextFile: false,
@@ -550,74 +499,27 @@ export const make = (
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.LoadSessionRequest;
const sessionLoadTimeout = Duration.fromInputUnsafe(
options.sessionLoadTimeout ?? defaultSessionLoadTimeout,
);
const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(
options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,
);
yield* Ref.set(
sessionLoadGateRef,
Option.some({
active: true,
lastActivityAtMillis: undefined,
idleGap: sessionLoadReplayIdleGap,
initializeResult,
}),
);
sessionId = options.resumeSessionId;
sessionSetupResult = yield* Effect.gen(function* () {
yield* logRequest({
method: "session/load",
payload: loadPayload,
status: "started",
});
const idleFiber = yield* waitForSessionLoadReplayIdle({
gateRef: sessionLoadGateRef,
}).pipe(Effect.forkIn(runtimeScope));
const loaded = yield* Effect.raceFirst(
acp.agent.loadSession(loadPayload),
Fiber.join(idleFiber),
).pipe(
Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),
Effect.timeoutOption(sessionLoadTimeout),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new EffectAcpErrors.AcpTransportError({
operation: "call-rpc",
method: "session/load",
detail: "session/load timed out waiting for RPC response or replay idle gap",
cause: undefined,
}),
),
onSome: Effect.succeed,
}),
),
Effect.tap((result) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "succeeded",
result,
}),
),
Effect.onError((cause) =>
logRequest({
method: "session/load",
payload: loadPayload,
status: "failed",
cause,
}),
),
const resumed = yield* runLoggedRequest(
"session/load",
loadPayload,
acp.agent.loadSession(loadPayload),
).pipe(Effect.exit);
if (Exit.isSuccess(resumed)) {
sessionId = options.resumeSessionId;
sessionSetupResult = resumed.value;
} else {
const createPayload = {
cwd: options.cwd,
mcpServers: options.mcpServers ?? [],
} satisfies EffectAcpSchema.NewSessionRequest;
const created = yield* runLoggedRequest(
"session/new",
createPayload,
acp.agent.createSession(createPayload),
);
return loaded;
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
sessionId = created.sessionId;
sessionSetupResult = created;
}
} else {
const createPayload = {
cwd: options.cwd,
@@ -694,48 +596,25 @@ export const make = (
handleExtNotification: acp.handleExtNotification,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
drainEvents: Effect.gen(function* () {
const acknowledge = yield* Deferred.make<void>();
yield* Queue.offer(eventQueue, {
_tag: "EventStreamBarrier",
acknowledge,
});
yield* Deferred.await(acknowledge);
}),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
prompt: (payload) =>
promptSerializationSemaphore.withPermit(
Effect.gen(function* () {
const started = yield* getStartedState;
yield* closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
});
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
...payload,
} satisfies EffectAcpSchema.PromptRequest;
const cancelledResponse = {
stopReason: "cancelled",
} satisfies EffectAcpSchema.PromptResponse;
const promptRpcFiber = yield* runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
).pipe(Effect.forkIn(runtimeScope));
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
return yield* Fiber.join(promptRpcFiber).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.succeed(cancelledResponse)
: Effect.failCause(cause),
),
Effect.ensuring(
Effect.gen(function* () {
yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);
yield* Ref.set(activePromptFiberRef, Option.none());
}),
return closeActiveAssistantSegment({
queue: eventQueue,
assistantSegmentRef,
}).pipe(
Effect.andThen(
runLoggedRequest(
"session/prompt",
requestPayload,
acp.agent.prompt(requestPayload),
),
),
Effect.tap(() =>
closeActiveAssistantSegment({
@@ -747,17 +626,7 @@ export const make = (
}),
),
cancel: getStartedState.pipe(
Effect.flatMap((started) =>
Effect.gen(function* () {
const activePromptFiber = yield* Ref.get(activePromptFiberRef);
if (Option.isSome(activePromptFiber)) {
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
}
yield* acp.agent
.cancel({ sessionId: started.sessionId })
.pipe(Effect.ignore, Effect.forkIn(runtimeScope));
}),
),
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
),
setMode: (modeId) =>
Ref.get(modeStateRef).pipe(
@@ -836,7 +705,7 @@ const handleSessionUpdate = ({
assistantSegmentRef,
params,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
@@ -932,7 +801,7 @@ const ensureActiveAssistantSegment = ({
assistantSegmentRef,
sessionId,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
}) =>
@@ -969,7 +838,7 @@ const closeActiveAssistantSegment = ({
queue,
assistantSegmentRef,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
}) =>
Ref.modify(assistantSegmentRef, (current) => {
@@ -8,7 +8,6 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import { normalizeModelSlug } from "@t3tools/shared/model";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
@@ -69,10 +68,9 @@ export const makeGrokAcpRuntime = (
),
),
);
const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(acpContext),
);
return yield* makeXAiPromptCompletionRuntime(runtime);
});
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
@@ -1,39 +1,12 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { describe, expect } from "vite-plus/test";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
makeXAiPromptCompletionRuntime,
XAiAskUserQuestionRequest,
} from "./XAiAcpExtension.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const makePromptCompletionRuntime = (env: NodeJS.ProcessEnv) =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.make({
spawn: {
command: process.execPath,
args: [mockAgentPath],
env,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
});
return yield* makeXAiPromptCompletionRuntime(runtime);
});
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
@@ -274,59 +247,4 @@ describe("XAiAcpExtension", () => {
},
});
});
it.effect("resolves a hung standard prompt from xAI prompt completion", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG: "1",
});
yield* runtime.start();
const promptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const promptId = promptResult._meta?.promptId;
expect(typeof promptId).toBe("string");
expect(promptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
sessionId: "mock-session-1",
promptId,
requestId: promptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("ignores stale xAI completion from an already settled prompt", () =>
Effect.gen(function* () {
const runtime = yield* makePromptCompletionRuntime({
T3_ACP_EMIT_STALE_XAI_PROMPT_COMPLETE_BEFORE_SECOND_HANG: "1",
});
yield* runtime.start();
const firstPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "first" }],
});
expect(firstPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: { promptId: "mock-stale-xai-prompt-1" },
});
const secondPromptResult = yield* runtime.prompt({
prompt: [{ type: "text", text: "second" }],
});
const secondPromptId = secondPromptResult._meta?.promptId;
expect(typeof secondPromptId).toBe("string");
expect(secondPromptId).not.toBe("mock-stale-xai-prompt-1");
expect(secondPromptResult).toMatchObject({
stopReason: "end_turn",
_meta: {
promptId: secondPromptId,
requestId: secondPromptId,
},
});
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -1,29 +1,5 @@
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import type * as EffectAcpSchema from "effect-acp/schema";
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
const XAiPromptCompleteNotification = Schema.Struct({
sessionId: Schema.String,
promptId: Schema.optional(Schema.String),
stopReason: Schema.optional(Schema.String),
agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),
});
type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
interface PendingXAiPromptCompletion {
readonly sessionId: string;
readonly promptId: string;
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
}
const completedXAiPromptIdLimit = 128;
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
const XAiAskUserQuestionOption = Schema.Struct({
label: Schema.String,
@@ -195,238 +171,3 @@ export function makeXAiAskUserQuestionResponse(
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
return { outcome: "cancelled" };
}
/**
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
* The underlying runtime remains unaware of xAI methods and metadata.
*/
export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletionRuntime")(
function* (runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]) {
const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);
const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);
const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);
let nextPromptFallbackId = 0;
const allocatePromptFallbackId = Effect.sync(() => {
nextPromptFallbackId += 1;
return `t3-xai-prompt-${nextPromptFallbackId}`;
});
yield* runtime.handleExtNotification(
"_x.ai/session/prompt_complete",
XAiPromptCompleteNotification,
(notification) =>
resolveXAiPromptCompletionFallback({
pendingRef,
completedPromptIdsRef,
notification,
}),
);
return {
...runtime,
start: () =>
runtime
.start()
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
prompt: (payload) =>
Effect.gen(function* () {
const sessionId = yield* Ref.get(activeSessionIdRef);
if (sessionId === undefined) {
return yield* runtime.prompt(payload);
}
const promptId = yield* allocatePromptFallbackId;
const fallback = yield* registerXAiPromptCompletionFallback(
pendingRef,
sessionId,
promptId,
);
const requestPayload = {
...payload,
_meta: {
...payload._meta,
promptId: fallback.promptId,
requestId: fallback.promptId,
},
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
return yield* Effect.raceFirst(
runtime.prompt(requestPayload),
Deferred.await(fallback.deferred),
).pipe(
Effect.tap((response) =>
rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),
),
Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),
);
}),
cancel: Ref.get(activeSessionIdRef).pipe(
Effect.flatMap((sessionId) =>
sessionId === undefined
? runtime.cancel
: abortPendingPromptCompletions(pendingRef, sessionId).pipe(
Effect.andThen(runtime.cancel),
),
),
),
} satisfies AcpSessionRuntime.AcpSessionRuntime["Service"];
},
);
const registerXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
promptId: string,
) =>
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
Effect.tap((deferred) =>
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
),
Effect.map((deferred) => ({ deferred, promptId })),
);
const unregisterXAiPromptCompletionFallback = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
const abortPendingPromptCompletions = (
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
sessionId: string,
) =>
Ref.modify(pendingRef, (pending) => {
const [toAbort, remaining] = pending.reduce<
[ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]
>(
([aborting, kept], entry) =>
entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],
[[], []],
);
if (toAbort.length === 0) {
return [Effect.void, pending] as const;
}
return [
Effect.forEach(
toAbort,
(entry) =>
Deferred.succeed(
entry.deferred,
promptResponseFromXAi({
sessionId: entry.sessionId,
promptId: entry.promptId,
stopReason: "cancelled",
agentResult: null,
}),
),
{ concurrency: "unbounded" },
).pipe(Effect.asVoid),
remaining,
] as const;
}).pipe(Effect.flatten);
const resolveXAiPromptCompletionFallback = ({
pendingRef,
completedPromptIdsRef,
notification,
}: {
readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;
readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;
readonly notification: XAiPromptCompleteNotification;
}) =>
Ref.get(completedPromptIdsRef).pipe(
Effect.flatMap((completedPromptIds) => {
if (
notification.promptId !== undefined &&
completedPromptIds.includes(notification.promptId)
) {
return Effect.void;
}
return Ref.modify(pendingRef, (pending) => {
const index =
notification.promptId !== undefined
? pending.findIndex(
(entry) =>
entry.sessionId === notification.sessionId &&
entry.promptId === notification.promptId,
)
: pending.findIndex((entry) => entry.sessionId === notification.sessionId);
if (index < 0) {
return [Effect.void, pending] as const;
}
const entry = pending[index];
if (!entry) {
return [Effect.void, pending] as const;
}
return [
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
[...pending.slice(0, index), ...pending.slice(index + 1)],
] as const;
}).pipe(Effect.flatten);
}),
);
const rememberCompletedXAiPromptId = (
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
response: EffectAcpSchema.PromptResponse,
fallbackPromptId: string,
) => {
const promptId = promptIdFromResponse(response) ?? fallbackPromptId;
return Ref.update(completedPromptIdsRef, (completedPromptIds) => {
if (completedPromptIds.includes(promptId)) {
return completedPromptIds;
}
return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);
});
};
function promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {
const meta = response._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
export function promptResponseHasMissingXAiStopReason(
response: EffectAcpSchema.PromptResponse,
): boolean {
const meta = response._meta;
return meta !== null && typeof meta === "object" && meta[xAiStopReasonMissingMetaKey] === true;
}
function promptResponseFromXAi(
notification: XAiPromptCompleteNotification,
): EffectAcpSchema.PromptResponse {
const stopReason = normalizeXAiStopReason(notification.stopReason);
const meta: Record<string, unknown> = {
sessionId: notification.sessionId,
};
if (notification.stopReason === undefined) {
meta[xAiStopReasonMissingMetaKey] = true;
}
if (notification.promptId !== undefined) {
meta.promptId = notification.promptId;
meta.requestId = notification.promptId;
}
if (notification.agentResult !== undefined) {
meta.agentResult = notification.agentResult;
}
return {
stopReason,
_meta: meta,
};
}
function normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {
switch (value) {
case "cancelled":
case "end_turn":
case "max_tokens":
case "max_turn_requests":
case "refusal":
return value;
default:
return "end_turn";
}
}
-67
View File
@@ -653,7 +653,6 @@ const buildAppUnderTest = (options?: {
Layer.mock(PreviewManager.PreviewManager)({
open: () => Effect.die("PreviewManager not stubbed in this test"),
navigate: () => Effect.die("PreviewManager not stubbed in this test"),
resize: () => Effect.die("PreviewManager not stubbed in this test"),
reportStatus: () => Effect.void,
refresh: () => Effect.void,
close: () => Effect.void,
@@ -3234,32 +3233,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) {
it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: { devUrl: new URL(crossOriginClientOrigin) },
});
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const response = yield* fetchEffect(sessionUrl, {
method: "OPTIONS",
headers: {
origin: desktopOrigin,
"access-control-request-method": "GET",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assertBrowserApiCorsPreflightHeaders(response.headers, {
origin: desktopOrigin,
credentials: true,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
}
it.effect("includes CORS headers on remote websocket-ticket auth failures", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -4126,46 +4099,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("shares one preview automation broker across websocket sessions", () =>
Effect.scoped(
Effect.gen(function* () {
yield* buildAppUnderTest();
const wsUrl = yield* getWsServerUrl("/ws");
const firstConnected = yield* Deferred.make<string>();
const firstClosed = yield* Deferred.make<void>();
const host = {
clientId: "shared-preview-host",
environmentId: testEnvironmentDescriptor.environmentId,
} as const;
yield* withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.previewAutomationConnect](host).pipe(
Stream.tap((event) =>
event.type === "connected"
? Deferred.succeed(firstConnected, event.connectionId)
: Effect.void,
),
Stream.runDrain,
Effect.ensuring(Deferred.succeed(firstClosed, undefined)),
),
).pipe(Effect.forkScoped);
const firstConnectionId = yield* Deferred.await(firstConnected);
const replacementEvent = yield* withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead),
).pipe(Effect.map(Option.getOrThrow));
const firstStreamClosed = yield* Deferred.await(firstClosed).pipe(
Effect.timeoutOption("2 seconds"),
);
assert.equal(replacementEvent.type, "connected");
assert.notEqual(replacementEvent.connectionId, firstConnectionId);
assert.isTrue(Option.isSome(firstStreamClosed));
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+1 -2
View File
@@ -36,7 +36,6 @@ import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/Provide
import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as PortScanner from "./preview/PortScanner.ts";
import * as ProcessRunner from "./processRunner.ts";
@@ -358,7 +357,7 @@ export const makeRoutesLayer = Layer.mergeAll(
websocketRpcRouteLayer,
),
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(Layer.provide(PreviewAutomationBroker.layer), Layer.provide(browserApiCorsLayer));
).pipe(Layer.provide(browserApiCorsLayer));
export const makeServerLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -4,9 +4,8 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
@@ -346,63 +345,11 @@ describe("AzureDevOpsCli.layer", () => {
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.operation, "execute");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.argumentCount, 2);
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
}).pipe(Effect.provide(layer)),
);
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
Effect.gen(function* () {
const cwd = "/missing/repo";
const platformCause = PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
syscall: "chdir",
pathOrDescriptor: cwd,
});
const cause = new VcsProcessSpawnError({
operation: "AzureDevOpsCli.execute",
command: "az",
cwd,
argumentCount: 2,
cause: platformCause,
});
mockRun.mockReturnValueOnce(Effect.fail(cause));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
assert.strictEqual(error.cwd, cwd);
assert.strictEqual(error.cause, cause);
}).pipe(Effect.provide(layer)),
);
it.effect("keeps invalid pull request output diagnostics structured", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.command, "az");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.outputLength, 8);
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
assert.exists(error.cause);
assert.strictEqual(
error.message,
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
);
}).pipe(Effect.provide(layer)),
);
});
+83 -166
View File
@@ -1,11 +1,9 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlRepositoryVisibility,
type VcsError,
@@ -21,61 +19,16 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const azureDevOpsCommandErrorFields = {
operation: Schema.Literal("execute"),
command: Schema.Literal("az"),
cwd: Schema.String,
argumentCount: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
"AzureDevOpsCliUnavailableError",
azureDevOpsCommandErrorFields,
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
"AzureDevOpsCliError",
{
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {
get detail(): string {
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
"AzureDevOpsCliAuthenticationError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
"AzureDevOpsPullRequestNotFoundError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
"AzureDevOpsCommandFailedError",
azureDevOpsCommandErrorFields,
) {
get detail(): string {
return "Azure DevOps CLI command failed.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -85,109 +38,53 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azure
readonly operation: "execute";
readonly command: "az";
readonly cwd: string;
readonly argumentCount: number;
},
cause: VcsError,
error: VcsError | unknown,
): AzureDevOpsCliError {
const fields = { ...context, cause };
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: az") || lower.includes("enoent")) {
return new AzureDevOpsCliError({
...context,
detail:
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
cause: error,
});
}
if (
cause._tag === "VcsProcessSpawnError" &&
cause.cause instanceof PlatformError.PlatformError &&
cause.cause.reason._tag === "NotFound" &&
cause.cause.reason.pathOrDescriptor !== context.cwd &&
cause.cause.reason.syscall !== "chdir"
lower.includes("az devops login") ||
lower.includes("please run az login") ||
lower.includes("not logged in") ||
lower.includes("authentication failed") ||
lower.includes("unauthorized")
) {
return new AzureDevOpsCliUnavailableError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
cause: error,
});
}
if (cause._tag === "VcsProcessExitError") {
if (cause.failureKind === "authentication") {
return new AzureDevOpsCliAuthenticationError(fields);
}
if (cause.failureKind === "not-found") {
return new AzureDevOpsPullRequestNotFoundError(fields);
}
if (
lower.includes("pull request") &&
(lower.includes("not found") || lower.includes("does not exist"))
) {
return new AzureDevOpsCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new AzureDevOpsCommandFailedError(fields);
return new AzureDevOpsCliError({
...context,
detail: "Azure DevOps CLI command failed.",
cause: error,
});
}
}
const azureDevOpsDecodeErrorFields = {
command: Schema.Literal("az"),
cwd: Schema.String,
outputLength: NonNegativeInt,
cause: Schema.Defect(),
};
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
"AzureDevOpsPullRequestListDecodeError",
{
operation: Schema.Literal("listPullRequests"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid PR list JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
"AzureDevOpsPullRequestDecodeError",
{
operation: Schema.Literal("getPullRequest"),
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid pull request JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
"getRepositoryCloneUrls",
"getDefaultBranch",
"createRepository",
]);
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
"AzureDevOpsRepositoryDecodeError",
{
operation: AzureDevOpsRepositoryDecodeOperation,
...azureDevOpsDecodeErrorFields,
},
) {
get detail(): string {
return "Azure DevOps CLI returned invalid repository JSON.";
}
override get message(): string {
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const AzureDevOpsCliError = Schema.Union([
AzureDevOpsCliUnavailableError,
AzureDevOpsCliAuthenticationError,
AzureDevOpsPullRequestNotFoundError,
AzureDevOpsCommandFailedError,
AzureDevOpsPullRequestListDecodeError,
AzureDevOpsPullRequestDecodeError,
AzureDevOpsRepositoryDecodeError,
]);
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
export interface AzureDevOpsRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
@@ -249,6 +146,17 @@ export class AzureDevOpsCli extends Context.Service<
}
>()("t3/sourceControl/AzureDevOpsCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
function normalizeChangeRequestId(reference: string): string {
const trimmed = reference.trim().replace(/^#/, "");
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
@@ -317,18 +225,19 @@ function parseRepositorySpecifier(repository: string): {
function decodeAzureDevOpsJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(cause) =>
new AzureDevOpsRepositoryDecodeError({
(error) =>
new AzureDevOpsCliError({
operation,
command: "az",
cwd,
outputLength: raw.length,
cause,
detail: invalidDetail,
cause: error,
}),
),
);
@@ -348,13 +257,8 @@ export const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError((error) =>
AzureDevOpsCommandFailedError.fromVcsError(
{
operation: "execute",
command: "az",
cwd: input.cwd,
argumentCount: input.args.length,
},
AzureDevOpsCliError.fromVcsError(
{ operation: "execute", command: "az", cwd: input.cwd },
error,
),
),
@@ -393,11 +297,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestListDecodeError({
new AzureDevOpsCliError({
operation: "listPullRequests",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -427,11 +331,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new AzureDevOpsPullRequestDecodeError({
new AzureDevOpsCliError({
operation: "getPullRequest",
command: "az",
cwd: input.cwd,
outputLength: raw.length,
detail: "Azure DevOps CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -453,6 +357,7 @@ export const make = Effect.gen(function* () {
raw,
RawAzureDevOpsRepositorySchema,
"getRepositoryCloneUrls",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
@@ -478,7 +383,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"createRepository",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
);
@@ -510,7 +421,13 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
decodeAzureDevOpsJson(
raw,
RawAzureDevOpsRepositorySchema,
"getDefaultBranch",
"Azure DevOps CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
),
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
it.effect("adds change-request context while retaining Azure CLI causes", () =>
Effect.gen(function* () {
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
operation: "execute",
command: "az",
cwd: "/repo",
argumentCount: 2,
detail: "Azure DevOps CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
@@ -544,61 +544,6 @@ it.effect("preserves the HTTP client failure without deriving the domain message
}).pipe(Effect.provide(layer));
});
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
const responseBody = '{"error":{"message":"credential=secret-value"}}';
const { layer } = makeLayer({
response: () => new Response(responseBody, { status: 403 }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 403);
assert.strictEqual(error.responseBodyLength, responseBody.length);
assert.notProperty(error, "responseBody");
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
);
assert.notInclude(error.message, "secret-value");
}).pipe(Effect.provide(layer));
});
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
const cause = new Error("response stream failed");
const { layer } = makeLayer({
response: () =>
new Response(
new ReadableStream<Uint8Array>({
start: (controller) => controller.error(cause),
}),
{ status: 502 },
),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const error = yield* bitbucket
.getPullRequest({ cwd: "/repo", reference: "42" })
.pipe(Effect.flip);
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
assert.strictEqual(error.operation, "getPullRequest");
assert.strictEqual(error.status, 502);
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
assert.strictEqual(error.cause.cause, cause);
assert.strictEqual(
error.message,
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
);
}).pipe(Effect.provide(layer));
});
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
const { git, layer } = makeLayer({
response: () =>
@@ -685,9 +630,8 @@ it.effect("preserves Git checkout failures without deriving the domain message f
}),
);
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.reference, "42");
assert.strictEqual(error.operation, "checkoutPullRequest");
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
assert.strictEqual(
error.message,
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
+41 -176
View File
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
NonNegativeInt,
TrimmedNonEmptyString,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
@@ -37,156 +36,20 @@ const BitbucketApiEnvConfig = Config.all({
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
});
const BitbucketApiOperation = Schema.Literals([
"resolveRepository",
"getRepository",
"getBranchingModel",
"getPullRequest",
"listPullRequests",
"createRepository",
"createPullRequest",
"probeAuth",
"checkoutPullRequest",
]);
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
"BitbucketRepositoryLocatorError",
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
"BitbucketApiError",
{
repository: Schema.String,
operation: Schema.String,
detail: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
}
}
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
"BitbucketRequestError",
{
operation: BitbucketApiOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
}
}
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
"BitbucketResponseError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
responseBodyLength: NonNegativeInt,
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
"BitbucketResponseBodyReadError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
}
}
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
"BitbucketResponseDecodeError",
{
operation: BitbucketApiOperation,
status: Schema.Int,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
}
}
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
"BitbucketRepositoryVcsResolveError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
"BitbucketRepositoryRemotesListError",
{
cwd: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
}
}
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
"BitbucketRepositoryRemoteNotFoundError",
{
cwd: Schema.String,
},
) {
override get message(): string {
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
}
}
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
"BitbucketPullRequestBodyReadError",
{
cwd: Schema.String,
bodyFile: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
}
}
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
"BitbucketCheckoutError",
{
cwd: Schema.String,
reference: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
}
}
export const BitbucketApiError = Schema.Union([
BitbucketRepositoryLocatorError,
BitbucketRequestError,
BitbucketResponseError,
BitbucketResponseBodyReadError,
BitbucketResponseDecodeError,
BitbucketRepositoryVcsResolveError,
BitbucketRepositoryRemotesListError,
BitbucketRepositoryRemoteNotFoundError,
BitbucketPullRequestBodyReadError,
BitbucketCheckoutError,
]);
export type BitbucketApiError = typeof BitbucketApiError.Type;
export const isBitbucketApiError = Schema.is(BitbucketApiError);
const isBitbucketApiError = Schema.is(BitbucketApiError);
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
@@ -346,14 +209,16 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
}
function requireRepositoryLocator(
operation: string,
repository: string,
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
const locator = parseBitbucketRepositorySlug(repository);
return locator
? Effect.succeed(locator)
: Effect.fail(
new BitbucketRepositoryLocatorError({
repository,
new BitbucketApiError({
operation,
detail: "Bitbucket repositories must be specified as workspace/repository.",
}),
);
}
@@ -474,24 +339,20 @@ function authFromConfig(
}
function responseError(
operation: BitbucketApiOperation,
operation: string,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<never, BitbucketApiError> {
return response.text.pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseBodyReadError({
operation,
status: response.status,
cause,
}),
),
Effect.orElseSucceed(() => ""),
Effect.flatMap((body) =>
Effect.fail(
new BitbucketResponseError({
new BitbucketApiError({
operation,
status: response.status,
responseBodyLength: body.length,
detail:
body.trim().length > 0
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
: `Bitbucket returned HTTP ${response.status}.`,
}),
),
),
@@ -518,7 +379,7 @@ export const make = Effect.gen(function* () {
};
const decodeResponse = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
schema: S,
response: HttpClientResponse.HttpClientResponse,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
@@ -527,9 +388,9 @@ export const make = Effect.gen(function* () {
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
Effect.mapError(
(cause) =>
new BitbucketResponseDecodeError({
new BitbucketApiError({
operation,
status: success.status,
detail: "Bitbucket returned invalid JSON for the requested resource.",
cause,
}),
),
@@ -538,15 +399,16 @@ export const make = Effect.gen(function* () {
})(response);
const executeJson = <S extends Schema.Top>(
operation: BitbucketApiOperation,
operation: string,
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
Effect.mapError(
(cause) =>
new BitbucketRequestError({
new BitbucketApiError({
operation,
detail: "Failed to send the Bitbucket request.",
cause,
}),
),
@@ -571,8 +433,9 @@ export const make = Effect.gen(function* () {
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryVcsResolveError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
cause,
}),
),
@@ -580,8 +443,9 @@ export const make = Effect.gen(function* () {
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
Effect.mapError(
(cause) =>
new BitbucketRepositoryRemotesListError({
cwd: input.cwd,
new BitbucketApiError({
operation: "resolveRepository",
detail: `Failed to list remotes for ${input.cwd}.`,
cause,
}),
),
@@ -593,8 +457,9 @@ export const make = Effect.gen(function* () {
if (parsed) return parsed;
}
return yield* new BitbucketRepositoryRemoteNotFoundError({
cwd: input.cwd,
return yield* new BitbucketApiError({
operation: "resolveRepository",
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
});
});
@@ -735,7 +600,7 @@ export const make = Effect.gen(function* () {
getRepositoryCloneUrls: (input) =>
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
createRepository: (input) =>
requireRepositoryLocator(input.repository).pipe(
requireRepositoryLocator("createRepository", input.repository).pipe(
Effect.flatMap((repository) =>
executeJson(
"createRepository",
@@ -760,9 +625,9 @@ export const make = Effect.gen(function* () {
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
Effect.mapError(
(cause) =>
new BitbucketPullRequestBodyReadError({
cwd: input.cwd,
bodyFile: input.bodyFile,
new BitbucketApiError({
operation: "createPullRequest",
detail: `Failed to read pull request body file ${input.bodyFile}.`,
cause,
}),
),
@@ -878,9 +743,9 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) =>
isBitbucketApiError(cause)
? cause
: new BitbucketCheckoutError({
cwd: input.cwd,
reference: input.reference,
: new BitbucketApiError({
operation: "checkoutPullRequest",
detail: "Failed to check out the Bitbucket pull request.",
cause,
}),
),
@@ -53,10 +53,11 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
it.effect("adds repository context while retaining Bitbucket API causes", () =>
Effect.gen(function* () {
const upstreamCause = new Error("raw upstream failure");
const cause = new BitbucketApi.BitbucketRequestError({
const cause = new BitbucketApi.BitbucketApiError({
operation: "getRepository",
cause: upstreamCause,
detail: "upstream detail that should remain in the cause",
status: 503,
cause: new Error("raw upstream failure"),
});
const provider = yield* makeProvider({
getRepositoryCloneUrls: () => Effect.fail(cause),
@@ -85,7 +86,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
},
);
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(upstreamCause.message), false);
assert.equal(error.message.includes(cause.detail), false);
}),
);
@@ -1,9 +1,8 @@
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
import { VcsProcessExitError } from "@t3tools/contracts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubCli from "./GitHubCli.ts";
@@ -31,27 +30,6 @@ afterEach(() => {
});
describe("GitHubCli.layer", () => {
it("does not classify a missing cwd as an unavailable gh executable", () => {
const context = { command: "gh", cwd: "/repo" } as const;
const missingCwd = new VcsProcessSpawnError({
operation: "GitHubCli.execute",
command: "gh",
cwd: context.cwd,
cause: PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "access",
pathOrDescriptor: context.cwd,
}),
});
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
assert.equal(commandFailure._tag, "GitHubCliCommandError");
assert.strictEqual(commandFailure.cause, missingCwd);
assert.notProperty(commandFailure, "operation");
});
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockRun.mockReturnValueOnce(
@@ -296,7 +274,6 @@ describe("GitHubCli.layer", () => {
command: "gh pr view",
cwd: "/repo",
exitCode: 1,
failureKind: "not-found",
detail:
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
});
@@ -311,7 +288,6 @@ describe("GitHubCli.layer", () => {
.pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
assert.strictEqual(error.command, "gh");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
+106 -166
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -19,163 +18,67 @@ import {
const DEFAULT_TIMEOUT_MS = 30_000;
const gitHubCliFailureFields = {
command: Schema.Literal("gh"),
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
"GitHubCliUnavailableError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI (`gh`) is required but not available on PATH.";
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
"GitHubCliAuthenticationError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "gh";
readonly cwd: string;
},
error: VcsError | unknown,
): GitHubCliError {
const lower = errorText(error).toLowerCase();
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
"GitHubPullRequestNotFoundError",
gitHubCliFailureFields,
) {
get detail(): string {
return "Pull request not found. Check the PR number or URL and try again.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
"GitHubCliCommandError",
gitHubCliFailureFields,
) {
get detail(): string {
return "GitHub CLI command failed.";
}
override get message(): string {
return `GitHub CLI failed in execute: ${this.detail}`;
}
}
const gitHubCliDecodeFields = {
command: Schema.Literal("gh"),
cwd: Schema.String,
cause: Schema.Defect(),
} as const;
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
"GitHubPullRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid PR list JSON.";
}
override get message(): string {
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
}
}
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
"GitHubChangeRequestListDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid change request JSON.";
}
override get message(): string {
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
}
}
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
"GitHubPullRequestDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid pull request JSON.";
}
override get message(): string {
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
}
}
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
"GitHubRepositoryDecodeError",
gitHubCliDecodeFields,
) {
get detail(): string {
return "GitHub CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
}
}
export const GitHubCliError = Schema.Union([
GitHubCliUnavailableError,
GitHubCliAuthenticationError,
GitHubPullRequestNotFoundError,
GitHubCliCommandError,
GitHubPullRequestListDecodeError,
GitHubChangeRequestListDecodeError,
GitHubPullRequestDecodeError,
GitHubRepositoryDecodeError,
]);
export type GitHubCliError = typeof GitHubCliError.Type;
export const isGitHubCliError = Schema.is(GitHubCliError);
export function fromVcsError(
context: {
readonly command: "gh";
readonly cwd: string;
},
error: VcsError,
): GitHubCliError {
if (
error._tag === "VcsProcessSpawnError" &&
error.cause instanceof PlatformError.PlatformError &&
error.cause.reason._tag === "NotFound" &&
error.cause.reason.module === "ChildProcess" &&
error.cause.reason.method === "spawn"
) {
return new GitHubCliUnavailableError({ ...context, cause: error });
}
if (error._tag === "VcsProcessExitError") {
if (error.failureKind === "authentication") {
return new GitHubCliAuthenticationError({ ...context, cause: error });
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
return new GitHubCliError({
...context,
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
cause: error,
});
}
if (error.failureKind === "not-found") {
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
}
}
return new GitHubCliCommandError({ ...context, cause: error });
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new GitHubCliError({
...context,
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
cause: error,
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
...context,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
...context,
detail: "GitHub CLI command failed.",
cause: error,
});
}
}
export interface GitHubPullRequestSummary {
@@ -247,14 +150,22 @@ export class GitHubCli extends Context.Service<
}
>()("t3/sourceControl/GitHubCli") {}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
);
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
@@ -303,6 +214,27 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
command: "gh",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -315,7 +247,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
.pipe(
Effect.mapError((error) =>
GitHubCliError.fromVcsError(
{ operation: "execute", command: "gh", cwd: input.cwd },
error,
),
),
);
return GitHubCli.of({
execute,
@@ -343,9 +282,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestListDecodeError({
new GitHubCliError({
operation: "listOpenPullRequests",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid PR list JSON.",
cause: decoded.failure,
}),
);
@@ -375,9 +316,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitHubPullRequestDecodeError({
new GitHubCliError({
operation: "getPullRequest",
command: "gh",
cwd: input.cwd,
detail: "GitHub CLI returned invalid pull request JSON.",
cause: decoded.failure,
}),
);
@@ -397,15 +340,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitHubRepositoryDecodeError({
command: "gh",
cwd: input.cwd,
cause,
}),
),
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -70,9 +70,11 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
const cause = new GitHubCli.GitHubCliError({
operation: "execute",
command: "gh",
cwd: "/repo",
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -158,17 +158,23 @@ export const make = Effect.gen(function* () {
})),
)
: Effect.fail(
new GitHubCli.GitHubChangeRequestListDecodeError({
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
command: "gh",
cwd: input.cwd,
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
input.headSelector,
),
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError(
(error) =>
Effect.catchTags({
GitHubCliError: (error) =>
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
@@ -180,7 +186,7 @@ export const make = Effect.gen(function* () {
detail: error.detail,
cause: error,
}),
),
}),
);
};
@@ -315,11 +315,10 @@ layer("GitLabCli.layer", (it) => {
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
command: "glab mr view 4888",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 merge request not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
@@ -331,37 +330,11 @@ layer("GitLabCli.layer", (it) => {
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
assert.equal(error.message.includes("Merge request not found"), true);
assert.strictEqual(error.command, "glab");
assert.strictEqual(error.cwd, "/repo");
assert.strictEqual(error.cause, cause);
assert.equal(error.message.includes(cause.detail), false);
}),
);
it.effect("keeps non-merge-request not-found failures generic", () =>
Effect.gen(function* () {
const cause = new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 project not found",
failureKind: "not-found",
});
mockedRun.mockReturnValueOnce(Effect.fail(cause));
const error = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getRepositoryCloneUrls({
cwd: "/repo",
repository: "missing/project",
});
}).pipe(Effect.flip);
assert.strictEqual(error._tag, "GitLabCliCommandError");
assert.strictEqual(error.cause, cause);
}),
);
});
+122 -270
View File
@@ -1,7 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Match from "effect/Match";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
@@ -22,56 +21,13 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const gitLabCliExecutionErrorContext = {
operation: Schema.Literal("execute"),
command: Schema.Literal("glab"),
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
cause: Schema.Defect(),
};
const gitLabCliDecodeErrorContext = {
command: Schema.Literal("glab"),
cwd: Schema.String,
cause: Schema.Defect(),
};
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
"GitLabCliUnavailableError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI (`glab`) is required but not available on PATH.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
"GitLabCliAuthenticationError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
"GitLabMergeRequestNotFoundError",
{
...gitLabCliExecutionErrorContext,
reference: Schema.String,
},
) {
get detail(): string {
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
}
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
@@ -81,148 +37,52 @@ export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<Git
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
readonly reference: string;
},
error: VcsError,
error: VcsError | unknown,
): GitLabCliError {
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
const lower = errorText(error).toLowerCase();
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
return new GitLabCliError({
...context,
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
cause: error,
});
}
return GitLabCliCommandError.fromVcsError(
{
operation: context.operation,
command: context.command,
cwd: context.cwd,
},
error,
);
}
}
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("glab auth login") ||
lower.includes("token")
) {
return new GitLabCliError({
...context,
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
cause: error,
});
}
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
"GitLabCliCommandError",
gitLabCliExecutionErrorContext,
) {
get detail(): string {
return "GitLab CLI command failed.";
}
if (
lower.includes("merge request not found") ||
lower.includes("not found") ||
lower.includes("404")
) {
return new GitLabCliError({
...context,
detail: "Merge request not found. Check the MR number or URL and try again.",
cause: error,
});
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
static fromVcsError(
context: {
readonly operation: "execute";
readonly command: "glab";
readonly cwd: string;
},
error: VcsError,
): GitLabCliError {
return Match.valueTags(error, {
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
VcsProcessExitError: (cause) => {
switch (cause.failureKind) {
case "authentication":
return new GitLabCliAuthenticationError({ ...context, cause });
case "not-found":
case "command-failed":
case undefined:
return new GitLabCliCommandError({ ...context, cause });
}
},
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
return new GitLabCliError({
...context,
detail: "GitLab CLI command failed.",
cause: error,
});
}
}
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
"GitLabMergeRequestListDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("listMergeRequests"),
},
) {
get detail(): string {
return "GitLab CLI returned invalid MR list JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
"GitLabMergeRequestDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("getMergeRequest"),
reference: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid merge request JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
"GitLabRepositoryDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
repository: Schema.optional(Schema.String),
},
) {
get detail(): string {
return "GitLab CLI returned invalid repository JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
"GitLabNamespaceDecodeError",
{
...gitLabCliDecodeErrorContext,
operation: Schema.Literal("createRepository"),
namespacePath: Schema.String,
},
) {
get detail(): string {
return "GitLab CLI returned invalid namespace JSON.";
}
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export const GitLabCliError = Schema.Union([
GitLabCliUnavailableError,
GitLabCliAuthenticationError,
GitLabMergeRequestNotFoundError,
GitLabCliCommandError,
GitLabMergeRequestListDecodeError,
GitLabMergeRequestDecodeError,
GitLabRepositoryDecodeError,
GitLabNamespaceDecodeError,
]);
export type GitLabCliError = typeof GitLabCliError.Type;
export const isGitLabCliError = Schema.is(GitLabCliError);
export interface GitLabMergeRequestSummary {
readonly number: number;
readonly title: string;
@@ -242,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
readonly sshUrl: string;
}
function errorText(error: VcsError | unknown): string {
if (typeof error === "object" && error !== null) {
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
const message = "message" in error && typeof error.message === "string" ? error.message : "";
return [tag, detail, message].filter(Boolean).join("\n");
}
return String(error);
}
export class GitLabCli extends Context.Service<
GitLabCli,
{
@@ -297,6 +168,15 @@ export class GitLabCli extends Context.Service<
}
>()("t3/sourceControl/GitLabCli") {}
function isVcsProcessSpawnError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "VcsProcessSpawnError"
);
}
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
path_with_namespace: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
@@ -312,14 +192,6 @@ const RawGitLabNamespaceSchema = Schema.Struct({
id: Schema.Number,
});
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
);
const decodeGitLabDefaultBranch = Schema.decodeEffect(
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
);
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
@@ -330,6 +202,27 @@ function normalizeRepositoryCloneUrls(
};
}
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
invalidDetail: string,
cwd: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitLabCliError({
operation,
command: "glab",
cwd,
detail: invalidDetail,
cause: error,
}),
),
);
}
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
@@ -390,10 +283,7 @@ function parseRepositoryPath(repository: string): {
export const make = Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
const run = (
input: Parameters<GitLabCli["Service"]["execute"]>[0],
mapError: (error: VcsError) => GitLabCliError,
) =>
const execute: GitLabCli["Service"]["execute"] = (input) =>
process
.run({
operation: "GitLabCli.execute",
@@ -402,32 +292,14 @@ export const make = Effect.gen(function* () {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError(mapError));
const execute: GitLabCli["Service"]["execute"] = (input) =>
run(input, (error) =>
GitLabCliCommandError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
);
const executeMergeRequest = (input: {
readonly cwd: string;
readonly reference: string;
readonly args: ReadonlyArray<string>;
}) =>
run(input, (error) =>
GitLabMergeRequestNotFoundError.fromVcsError(
{
operation: "execute",
command: "glab",
cwd: input.cwd,
reference: input.reference,
},
error,
),
);
.pipe(
Effect.mapError((error) =>
GitLabCliError.fromVcsError(
{ operation: "execute", command: "glab", cwd: input.cwd },
error,
),
),
);
return GitLabCli.of({
execute,
@@ -454,10 +326,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestListDecodeError({
new GitLabCliError({
operation: "listMergeRequests",
command: "glab",
cwd: input.cwd,
detail: "GitLab CLI returned invalid MR list JSON.",
cause: decoded.failure,
}),
);
@@ -469,9 +342,8 @@ export const make = Effect.gen(function* () {
),
),
getMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "view", input.reference, "--output", "json"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
@@ -480,11 +352,11 @@ export const make = Effect.gen(function* () {
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabMergeRequestDecodeError({
new GitLabCliError({
operation: "getMergeRequest",
command: "glab",
cwd: input.cwd,
reference: input.reference,
detail: "GitLab CLI returned invalid merge request JSON.",
cause: decoded.failure,
}),
);
@@ -502,17 +374,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getRepositoryCloneUrls",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -526,17 +393,12 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabNamespace(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabNamespaceDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
namespacePath,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabNamespaceSchema,
"createRepository",
"GitLab CLI returned invalid namespace JSON.",
input.cwd,
),
),
Effect.map((namespace) => namespace.id),
@@ -566,17 +428,12 @@ export const make = Effect.gen(function* () {
),
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabRepositoryCloneUrls(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "createRepository",
command: "glab",
cwd: input.cwd,
repository: input.repository,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"createRepository",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map(normalizeRepositoryCloneUrls),
@@ -610,24 +467,19 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabDefaultBranch(raw).pipe(
Effect.mapError(
(cause) =>
new GitLabRepositoryDecodeError({
operation: "getDefaultBranch",
command: "glab",
cwd: input.cwd,
cause,
}),
),
decodeGitLabJson(
raw,
RawGitLabDefaultBranchSchema,
"getDefaultBranch",
"GitLab CLI returned invalid repository JSON.",
input.cwd,
),
),
Effect.map((value) => value.default_branch ?? null),
),
checkoutMergeRequest: (input) =>
executeMergeRequest({
execute({
cwd: input.cwd,
reference: input.reference,
args: ["mr", "checkout", input.reference],
}).pipe(Effect.asVoid),
});
@@ -54,10 +54,11 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
it.effect("adds repository context while retaining GitLab CLI causes", () =>
Effect.gen(function* () {
const cause = new GitLabCli.GitLabCliCommandError({
const cause = new GitLabCli.GitLabCliError({
operation: "execute",
command: "glab",
cwd: "/repo",
detail: "GitLab CLI command failed.",
cause: new Error("raw upstream detail that should remain in the cause"),
});
const provider = yield* makeProvider({
@@ -1,4 +1,4 @@
import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Duration from "effect/Duration";
@@ -11,8 +11,8 @@ import { beforeEach, expect } from "vite-plus/test";
import * as ServerConfig from "../config.ts";
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
import * as TextGeneration from "./TextGeneration.ts";
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
state: {
@@ -20,11 +20,8 @@ const runtimeMock = {
promptUrls: [] as string[],
authHeaders: [] as Array<string | null>,
closeCalls: [] as string[],
sessionCreateError: undefined as unknown,
sessionResult: undefined as { data?: { id: string } } | undefined,
promptRequestError: undefined as unknown,
promptResult: undefined as
| { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
| undefined,
},
reset() {
@@ -32,9 +29,6 @@ const runtimeMock = {
this.state.promptUrls.length = 0;
this.state.authHeaders.length = 0;
this.state.closeCalls.length = 0;
this.state.sessionCreateError = undefined;
this.state.sessionResult = undefined;
this.state.promptRequestError = undefined;
this.state.promptResult = undefined;
},
};
@@ -67,20 +61,12 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
({
session: {
create: async () => {
if (runtimeMock.state.sessionCreateError !== undefined) {
throw runtimeMock.state.sessionCreateError;
}
return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
},
create: async () => ({ data: { id: `${baseUrl}/session` } }),
prompt: async () => {
runtimeMock.state.promptUrls.push(baseUrl);
runtimeMock.state.authHeaders.push(
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
);
if (runtimeMock.state.promptRequestError !== undefined) {
throw runtimeMock.state.promptRequestError;
}
return (
runtimeMock.state.promptResult ?? {
data: {
@@ -113,13 +99,6 @@ const DEFAULT_TEST_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("opencode"),
model: "openai/gpt-5",
};
const DEFAULT_COMMIT_MESSAGE_INPUT = {
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
};
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
@@ -163,7 +142,7 @@ function withOpenCodeTextGeneration<A, E, R>(
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
const textGeneration = yield* makeOpenCodeTextGeneration(settings);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
@@ -242,99 +221,22 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
).pipe(Effect.provide(TestClock.layer())),
);
it.effect("preserves the SDK cause when session creation fails", () =>
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
const sdkCause = new Error("session endpoint unavailable");
runtimeMock.state.sessionCreateError = sdkCause;
runtimeMock.state.promptResult = { data: {} };
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.message).toContain("OpenCode session.create request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
it.effect("reports a missing session payload without manufacturing a cause", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.sessionResult = {};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode session.create returned no session payload.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationSessionPayloadError",
operation: "generateCommitMessage",
cwd: process.cwd(),
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
it.effect("preserves the SDK cause and request context when prompting fails", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
const sdkCause = new Error("prompt endpoint unavailable");
runtimeMock.state.promptRequestError = sdkCause;
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode session.prompt request failed.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptRequestError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
cause: sdkCause,
});
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
}),
),
);
it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
runtimeMock.state.promptResult = {
data: {
parts: [null, { type: "tool" }, { type: "text", text: " " }],
},
};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("OpenCode returned empty output.");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationEmptyOutputError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
responsePartCount: 3,
textPartCount: 1,
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -387,21 +289,16 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
};
const error = yield* textGeneration
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/opencode-reuse",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.flip);
expect(error.message).toContain("Model did not produce structured output");
expect(error.cause).toMatchObject({
_tag: "OpenCodeTextGenerationPromptResponseError",
operation: "generateCommitMessage",
cwd: process.cwd(),
sessionId: "http://127.0.0.1:4301/session",
providerId: "openai",
modelId: "gpt-5",
providerErrorName: "StructuredOutputError",
providerMessage: "Model did not produce structured output",
});
expect(error.cause).not.toHaveProperty("cause");
}),
),
);
@@ -6,7 +6,6 @@ import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import {
NonNegativeInt,
TextGenerationError,
type ChatAttachment,
type ModelSelection,
@@ -34,106 +33,11 @@ import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
const OpenCodeTextGenerationOperation = Schema.Literals([
"generateCommitMessage",
"generatePrContent",
"generateBranchName",
"generateThreadTitle",
]);
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
const openCodeTextGenerationErrorContext = {
operation: OpenCodeTextGenerationOperation,
cwd: Schema.String,
};
export class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(
"OpenCodeTextGenerationSessionRequestError",
{
...openCodeTextGenerationErrorContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;
}
}
export class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(
"OpenCodeTextGenerationSessionPayloadError",
openCodeTextGenerationErrorContext,
) {
override get message(): string {
return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;
}
}
const openCodePromptErrorContext = {
...openCodeTextGenerationErrorContext,
sessionId: Schema.String,
providerId: Schema.String,
modelId: Schema.String,
};
export class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(
"OpenCodeTextGenerationPromptRequestError",
{
...openCodePromptErrorContext,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;
}
}
export class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(
"OpenCodeTextGenerationPromptResponseError",
{
...openCodePromptErrorContext,
providerErrorName: Schema.optional(Schema.String),
providerMessage: Schema.String,
},
) {
override get message(): string {
const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : "";
return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;
}
}
export class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(
"OpenCodeTextGenerationEmptyOutputError",
{
...openCodePromptErrorContext,
responsePartCount: NonNegativeInt,
textPartCount: NonNegativeInt,
},
) {
override get message(): string {
return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;
}
}
interface OpenCodePromptFailure {
readonly name?: string;
readonly message: string;
}
interface OpenCodeTextPart {
readonly type: "text";
readonly text: string;
}
function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {
function getOpenCodePromptErrorMessage(error: unknown): string | null {
if (!error || typeof error !== "object") {
return null;
}
const name =
"name" in error && typeof error.name === "string" && error.name.trim().length > 0
? error.name.trim()
: undefined;
const message =
"data" in error &&
error.data &&
@@ -143,34 +47,31 @@ function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null
? error.data.message.trim()
: "";
if (message.length > 0) {
return {
...(name ? { name } : {}),
message,
};
return message;
}
if (name) {
return { name, message: name };
if ("name" in error && typeof error.name === "string") {
const name = error.name.trim();
return name.length > 0 ? name : null;
}
return null;
}
function isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {
return (
part !== null &&
typeof part === "object" &&
"type" in part &&
part.type === "text" &&
"text" in part &&
typeof part.text === "string"
);
}
function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
return (parts ?? [])
.filter(isOpenCodeTextPart)
.map((part) => part.text)
.flatMap((part) => {
if (!part || typeof part !== "object") {
return [];
}
if (!("type" in part) || part.type !== "text") {
return [];
}
if (!("text" in part) || typeof part.text !== "string") {
return [];
}
return [part.text];
})
.join("")
.trim();
}
@@ -359,7 +260,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
);
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
readonly operation: OpenCodeTextGenerationOperation;
readonly operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
readonly cwd: string;
readonly prompt: string;
readonly outputSchemaJson: S;
@@ -380,121 +285,54 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
});
const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
});
const session = yield* Effect.tryPromise({
try: () =>
client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
}),
catch: (cause) =>
new OpenCodeTextGenerationSessionRequestError({
operation: input.operation,
cwd: input.cwd,
cause,
}),
});
if (!session.data) {
return yield* new OpenCodeTextGenerationSessionPayloadError({
operation: input.operation,
cwd: input.cwd,
const runAgainstServer = (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) =>
Effect.tryPromise({
try: async () => {
const client = openCodeRuntime.createOpenCodeSdkClient({
baseUrl: server.url,
directory: input.cwd,
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
? { serverPassword: openCodeSettings.serverPassword }
: {}),
});
}
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
const selectedVariant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
const promptContext = {
operation: input.operation,
cwd: input.cwd,
sessionId: session.data.id,
providerId: parsedModel.providerID,
modelId: parsedModel.modelID,
};
const session = await client.session.create({
title: `T3 Code ${input.operation}`,
permission: [{ permission: "*", pattern: "*", action: "deny" }],
});
if (!session.data) {
throw new Error("OpenCode session.create returned no session payload.");
}
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
const selectedVariant = getModelSelectionStringOptionValue(
input.modelSelection,
"variant",
);
const result = yield* Effect.tryPromise({
try: () =>
client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
}),
catch: (cause) =>
new OpenCodeTextGenerationPromptRequestError({
...promptContext,
cause,
}),
});
const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
if (promptFailure) {
return yield* new OpenCodeTextGenerationPromptResponseError({
...promptContext,
...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),
providerMessage: promptFailure.message,
const result = await client.session.prompt({
sessionID: session.data.id,
model: parsedModel,
...(selectedAgent ? { agent: selectedAgent } : {}),
...(selectedVariant ? { variant: selectedVariant } : {}),
parts: [{ type: "text", text: input.prompt }, ...fileParts],
});
}
const responseParts = result.data?.parts ?? [];
const rawText = getOpenCodeTextResponse(responseParts);
if (rawText.length === 0) {
return yield* new OpenCodeTextGenerationEmptyOutputError({
...promptContext,
responsePartCount: responseParts.length,
textPartCount: responseParts.filter(isOpenCodeTextPart).length,
});
}
return rawText;
},
Effect.catchTags({
OpenCodeTextGenerationSessionRequestError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.create request failed.",
cause,
}),
),
OpenCodeTextGenerationSessionPayloadError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.create returned no session payload.",
cause,
}),
),
OpenCodeTextGenerationPromptRequestError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode session.prompt request failed.",
cause,
}),
),
OpenCodeTextGenerationPromptResponseError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: cause.providerMessage,
cause,
}),
),
OpenCodeTextGenerationEmptyOutputError: (cause) =>
Effect.fail(
new TextGenerationError({
operation: cause.operation,
detail: "OpenCode returned empty output.",
cause,
}),
),
}),
);
const info = result.data?.info;
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
if (errorMessage) {
throw new Error(errorMessage);
}
const rawText = getOpenCodeTextResponse(result.data?.parts);
if (rawText.length === 0) {
throw new Error("OpenCode returned empty output.");
}
return rawText;
},
catch: (cause) =>
new TextGenerationError({
operation: input.operation,
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
cause,
}),
});
const rawOutput =
openCodeSettings.serverUrl.length > 0
-65
View File
@@ -11,7 +11,6 @@ import {
VcsProcessSpawnError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import * as ProcessRunner from "../processRunner.ts";
import * as VcsProcess from "./VcsProcess.ts";
const run = (input: VcsProcess.VcsProcessInput) =>
@@ -25,25 +24,6 @@ const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
effect.pipe(Effect.provide(liveLayer));
const baseInput = {
operation: "test.process-boundary",
command: "git",
args: ["status", "--short"],
cwd: "/workspace",
} satisfies VcsProcess.VcsProcessInput;
const captureProcessResult = (
result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
) =>
VcsProcess.make.pipe(
Effect.provideService(
ProcessRunner.ProcessRunner,
ProcessRunner.ProcessRunner.of({ run: () => result }),
),
Effect.flatMap((service) => service.run(baseInput)),
Effect.flip,
);
describe("VcsProcess.run", () => {
it.effect("collects stdout", () =>
Effect.gen(function* () {
@@ -161,51 +141,6 @@ describe("VcsProcess.run", () => {
}).pipe(provideLive),
);
it.effect("preserves real boundary causes without manufacturing structural ones", () =>
Effect.gen(function* () {
const cause = new Error("secret stdin failure");
const error = yield* captureProcessResult(
Effect.fail(
new ProcessRunner.ProcessStdinError({
command: baseInput.command,
argumentCount: baseInput.args.length,
cwd: baseInput.cwd,
stdinBytes: 47,
cause,
}),
),
);
expect(error).toMatchObject({
_tag: "VcsProcessStdinWriteError",
operation: baseInput.operation,
stdinBytes: 47,
cause,
});
expect(error.message).not.toContain(cause.message);
const missingExitCodeError = yield* captureProcessResult(
Effect.succeed({
stdout: "",
stderr: "",
code: null,
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
expect(missingExitCodeError).toMatchObject({
_tag: "VcsProcessMissingExitCodeError",
operation: baseInput.operation,
command: baseInput.command,
cwd: baseInput.cwd,
argumentCount: baseInput.args.length,
});
expect(missingExitCodeError).not.toHaveProperty("cause");
}),
);
it.effect("returns output when non-zero exits are allowed", () =>
Effect.gen(function* () {
const result = yield* run({
+5 -21
View File
@@ -5,14 +5,11 @@ import * as Match from "effect/Match";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
VcsOutputDecodeError,
type VcsError,
VcsProcessExitError,
type VcsProcessExitFailureKind,
VcsProcessMissingExitCodeError,
VcsProcessOutputLimitError,
VcsProcessOutputReadError,
VcsProcessSpawnError,
VcsProcessStdinWriteError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
import * as ProcessRunner from "../processRunner.ts";
@@ -117,32 +114,19 @@ export const make = Effect.gen(function* () {
ProcessSpawnError: (error) =>
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
ProcessOutputLimitError: (error) =>
new VcsProcessOutputLimitError({
...baseError,
stream: error.stream,
maxBytes: error.maxBytes,
observedBytes: error.observedBytes,
}),
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
ProcessTimeoutError: (error) =>
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
ProcessStdinError: (error) =>
new VcsProcessStdinWriteError({
...baseError,
stdinBytes: error.stdinBytes,
cause: error.cause,
}),
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
ProcessReadError: (error) =>
new VcsProcessOutputReadError({
...baseError,
stream: error.stream,
cause: error.cause,
}),
VcsOutputDecodeError.fromProcessReadError(baseError, error),
}),
),
);
if (result.code === null) {
return yield* new VcsProcessMissingExitCodeError(baseError);
return yield* VcsOutputDecodeError.missingExitCode(baseError);
}
if (!input.allowNonZeroExit && result.code !== 0) {
+15 -20
View File
@@ -96,19 +96,16 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd });
assert.equal(kind, "jj");
const [message, context] = messages[0] as [string, Record<string, unknown>];
const failedCandidate = path.join(cwd, ".t3code", "vcs.json");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
assert.equal(
error.message,
"Failed to inspect VCS project config at " + failedCandidate + ".",
);
assert.deepInclude(error, {
assert.equal(message, "Failed to inspect VCS project config at " + failedCandidate + ".");
assert.deepInclude(context, {
operation: "inspect",
cwd,
configPath: failedCandidate,
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
@@ -149,19 +146,18 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
const [message, context] = messages[0] as [string, Record<string, unknown>];
assert.equal(
error.message,
message,
"Failed to decode VCS project config at " + path.join(configDir, "vcs.json") + ".",
);
assert.deepInclude(error.cause, { _tag: "SchemaError" });
assert.deepInclude(error, {
assert.deepInclude(context, {
operation: "decode",
cwd: root,
configPath: path.join(configDir, "vcs.json"),
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
@@ -186,16 +182,15 @@ describe("VcsProjectConfig", () => {
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
const [error] = messages[0] as ReadonlyArray<unknown>;
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
assert.equal(error.message, "Failed to read VCS project config at " + configPath + ".");
assert.deepInclude(error.cause, { _tag: "PlatformError" });
assert.deepInclude(error, {
const [message, context] = messages[0] as [string, Record<string, unknown>];
assert.equal(message, "Failed to read VCS project config at " + configPath + ".");
assert.deepInclude(context, {
operation: "read",
cwd: root,
configPath,
_tag: "VcsProjectConfigError",
errorTag: "VcsProjectConfigError",
});
assert.equal("cause" in context, false);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
});
+7 -8
View File
@@ -55,14 +55,13 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
}
const logVcsProjectConfigError = (error: VcsProjectConfigError) =>
Effect.logWarning(error).pipe(
Effect.annotateLogs({
operation: error.operation,
cwd: error.cwd,
configPath: error.configPath,
errorTag: error._tag,
}),
);
Effect.logWarning(error.message, {
operation: error.operation,
cwd: error.cwd,
configPath: error.configPath,
errorTag: error._tag,
stack: error.stack,
});
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+9 -18
View File
@@ -151,29 +151,20 @@ export const make = Effect.gen(function* () {
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
return;
}
const recoverRefreshFailure = (
cause:
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
});
yield* Effect.gen(function* () {
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
yield* searchIndex.refresh();
}).pipe(
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
Effect.catchTags({
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
}),
Effect.catch((cause) =>
Effect.gen(function* () {
yield* Effect.logWarning("Failed to refresh workspace search index", {
cwd,
cause,
});
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
}),
),
);
},
);
@@ -1,8 +1,6 @@
import { FileFinder } from "@ff-labs/fff-node";
import { afterEach, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { vi } from "vite-plus/test";
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
@@ -51,35 +49,6 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
}),
);
it.effect("preserves FileFinder destroy failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("native destroy failed");
const finder = {
destroy: vi.fn(() => {
throw cause;
}),
isScanning: vi.fn(() => false),
} as unknown as FileFinder;
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
Effect.exit,
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasDies(exit.cause)).toBe(true);
const error = Cause.squash(exit.cause);
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
expect(error).toMatchObject({
_tag: "WorkspaceSearchIndexDestroyFailed",
cwd: "/workspace/project",
cause,
});
}
}),
);
it.effect("preserves search and refresh failures with operation context", () =>
Effect.scoped(
Effect.gen(function* () {
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff. Show more